text
stringlengths
10
2.72M
package com.tencent.mm.plugin.traceroute.ui; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.tencent.mm.R; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.s; public class NetworkDiagnoseIntroUI extends MMActivity { private Button oDO; private TextView oDP; public void onCreate(Bundle bundle) { super.onCreate(bundle); initView(); } protected final void initView() { this.oDO = (Button) findViewById(R.h.start_diagnose); this.oDO.setOnClickListener(new OnClickListener() { public final void onClick(View view) { au.HU(); if (!c.isSDCardAvailable()) { s.gH(NetworkDiagnoseIntroUI.this); } else if (au.DF().Lg() == 0) { Toast.makeText(NetworkDiagnoseIntroUI.this, NetworkDiagnoseIntroUI.this.getString(R.l.fmt_iap_err), 0).show(); } else { NetworkDiagnoseIntroUI.this.startActivity(new Intent(NetworkDiagnoseIntroUI.this, NetworkDiagnoseUI.class)); NetworkDiagnoseIntroUI.this.finish(); } } }); this.oDP = (TextView) findViewById(R.h.net_diagnose_privacy_intro); this.oDP.setOnClickListener(new 2(this)); setMMTitle(""); setBackBtn(new 3(this)); } protected final int getLayoutId() { return R.i.network_diagnose_ready; } }
// In the while loop, the 1st while loop is to find nodes that need to preserve, so we keep 2 pointers prev and cur while cur is at 1 node ahead of prev. // In the 2nd while loop, we keep moving cur to get nodes that need to be deleted. At the end, every node between prev and cur are nodes that need to be removed, so prev.next = cur. // Keep doing and we’ll get the result. class Solution { public static void main(String[] args) { } public ListNode deleteNodes(ListNode head, int m, int n) { ListNode cur = head; ListNode prev = head; while(cur != null) { int countM = m; int countN = n; while(cur != null && countM > 0) { prev = cur; cur = cur.next; countM--; } while(cur != null && countN > 0) { cur = cur.next; countN--; } prev.next = cur; } return head; } }
package studentadmin; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; /** * Representeert een Student. * @author Erwin Engel */ public class Student extends Leerling { private double aantalStudiepunten = 0.0; private final double MAXSTUDIEPUNTEN = 250.0; private Opleiding opleiding = null; public Student (String naam, Opleiding opleiding){ super(naam); this.opleiding = opleiding; } @Override public boolean isGeslaagd() { return this.aantalStudiepunten >= opleiding.getTotStudiepunten(); } @Override public String toString() { DecimalFormat df = new DecimalFormat("####0.00", new DecimalFormatSymbols(Locale.US)); String geslaagd = "niet geslaagd"; if (isGeslaagd()){ geslaagd = "geslaagd"; } return (""+ super.getNaam() + "," + opleiding.getNaam() + "," + df.format(this.aantalStudiepunten) + " studiepunten," + geslaagd); } /** * Verhoog huidige aantal studiepunten met gegeven verhoging * @param verhoging * @throws StudentAdminException : indien maximale aantal modules overschreden */ public void verhoogStudiepunten(double verhoging) throws StudentAdminException { if (this.aantalStudiepunten + verhoging <= MAXSTUDIEPUNTEN) { this.aantalStudiepunten = this.aantalStudiepunten + verhoging; } else { throw new StudentAdminException("aantal studiepunten kan nog met maximaal " + (MAXSTUDIEPUNTEN- this.aantalStudiepunten) + " verhoogd worden"); } } public void setOpleiding(Opleiding opleiding) { this.opleiding = opleiding; } public Opleiding getOpleiding() { return opleiding; } public double getAantalStudiepunten() { return aantalStudiepunten; } public void setAantalStudiepunten(double aantalStudiepunten) { this.aantalStudiepunten = aantalStudiepunten; } public Object clone() throws CloneNotSupportedException{ Student s = (Student)super.clone(); s.opleiding = (Opleiding) this.opleiding.clone(); return s; } }
package commandline.language.parser; import org.jetbrains.annotations.NotNull; /** * User: gno, Date: 02.08.13 - 12:59 */ public class MockArgumentParser extends ArgumentParser<Object> { public MockArgumentParser() { super(); } @Override public boolean isCompatibleWithOutputClass(@NotNull Class<?> clazz) { return clazz.isAssignableFrom(Object.class); } @NotNull @Override public Object parse(@NotNull String value) throws ArgumentParseException { return value; } }
/* Document : SME_Lending Created on : August 21, 2015, 11:56:42 AM Author : Anuj Verma */ package com.spring.controller; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.spring.service.ReportService; import com.spring.service.UserService; import com.spring.util.EmailerServiceInno; //import org.springframework.validation.BindingResult; @Controller @RequestMapping("/getService") public class SalesForceCallbackURLServiceController { private static Logger logger = Logger.getLogger(SalesForceCallbackURLServiceController.class); @Autowired ReportService reportService; @Autowired UserService userService; @Autowired EmailerServiceInno emailerServiceInno; @Value("${sfCallBackServiceKey}") private String sfCallBackServiceKey; @RequestMapping(value = "/dealers/{sfCallBackServiceKey1}", method = RequestMethod.GET) public void salesForceCallbackURLService(@PathVariable("sfCallBackServiceKey1") String sfCallBackServiceKey1,ModelMap model) { logger.info("inside :salesForceCallbackURLService "); int row=0; String bodyAdditionalInfo=""; if(sfCallBackServiceKey1.equals(sfCallBackServiceKey)) { logger.info("Key Matched"); logger.info("sfCallBackServiceKey : "+sfCallBackServiceKey); } else { logger.info("Key not Matched"); logger.info("Excel file is not generate for CC Print"); } } public static String getCurrentDateInMMDD(){ String pattern = "dd-mm-yyyy"; String dateInString =new SimpleDateFormat(pattern).format(new Date()); return dateInString; } }
package backjun.silver; import java.util.Scanner; class Person { int weight; int height; int rank; } public class Main_7568_덩치 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); Person[] person = new Person[N]; for (int i = 0; i < N; i++) { person[i] = new Person(); person[i].weight = sc.nextInt(); person[i].height = sc.nextInt(); person[i].rank = 1; } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (person[i].weight > person[j].weight && person[i].height > person[j].height) { person[j].rank++; } } } for (int i = 0; i < N; i++) { System.out.print(person[i].rank + " "); } } }
package test; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.*; @RunWith(Parameterized.class) public class demoTest { demo d; @Parameterized.Parameters public static Collection<?> data(){ return Arrays.asList(new Object[][]{{"1+2", 3}, {"1+3+5", 9}, {"1+3+5+7", 16}}); } @Parameterized.Parameter(0) public String input; @Parameterized.Parameter(1) public int result; @Before public void before(){ d = new demo(); } // @Test // public void getIn() { // // assertEquals("aa", d.getIn("aa")); // // } @Test public void calculate() { assertEquals(result, d.calculate(this.input)); } }
import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringTokens { public static void main(String[] args) { // He is a very very good boy, isn't he? // [A-Za-z !,?._'@]+ Scanner scan = new Scanner(System.in); String s = scan.nextLine(); // String test0 = "He is a very very good boy, isn't he?"; // String test1 = "_aa. A "; // String test2 = "!!!"; // String test3 = "!SSSSS"; // String test4 = "test ! ! He is a very very good boy, isn't he? test"; // String test5 = " "; String regexPattern = "[ !,?._'@]+"; String regexPatternReplace = "^[^A-Za-z]*"; String replacedWith = ""; String tempString = s.replaceAll(regexPatternReplace, replacedWith); String[] stringArray = (tempString.length() == 0) ? new String[0] : tempString.split(regexPattern); System.out.println(stringArray.length); Arrays.stream(stringArray).forEach(System.out::println); scan.close(); } }
/** * 與遊戲場地有關的事件 */ package com.ericlam.mc.minigames.core.event.arena;
package com.mes.old.meta; import com.bstek.urule.model.Label; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final /** * Aaa generated by hbm2java */ public class Aaa implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; @Label("AaaµÄid") private AaaId id; public Aaa() { } public Aaa(AaaId id) { this.id = id; } public AaaId getId() { return this.id; } public void setId(AaaId id) { this.id = id; } }
package no.uib.info331.activities; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.CardView; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Toast; import com.google.gson.Gson; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import no.uib.info331.R; import no.uib.info331.adapters.GroupListViewAdapter; import no.uib.info331.models.Group; import no.uib.info331.models.messages.GroupListEvent; import no.uib.info331.queries.GroupQueries; import no.uib.info331.util.Animations; /** * Activity that lets the profileUser search for groups in db and click on it in the searched groups list, * they are then taken to the group profile page, GroupProfileActivity * * @author Edvard P. Bjørgen * */ public class JoinGroupActivity extends AppCompatActivity { @BindView(R.id.join_group_card) CardView cardViewJoinGroup; @BindView(R.id.edittext_search_for_groups) EditText editTextSearchForGroups; @BindView(R.id.listview_add_group_list) ListView listViewGroupList; @BindView(R.id.imagebutton_search_for_group_join) ImageButton imageBtnSearchForGroups; private GroupListViewAdapter searchedGroupListViewAdapter; private GroupQueries groupQueries = new GroupQueries(); private Animations anim = new Animations(); private Context context; private int shortAnimTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_join_group); ButterKnife.bind(this); initGui(); initListeners(); } private void initGui() { context = getApplicationContext(); shortAnimTime = anim.getShortAnimTime(context); anim.moveViewToTranslationY(cardViewJoinGroup, 0 , shortAnimTime, 5000, false); anim.fadeInView(cardViewJoinGroup, 0, shortAnimTime); anim.moveViewToTranslationY(cardViewJoinGroup, 100 , shortAnimTime, 0, false); groupQueries.getAllGroups(context); } private void initListeners() { imageBtnSearchForGroups.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String query = String.valueOf(editTextSearchForGroups.getText()); if(query == null || query.equals("") || query.equals(" ")){ groupQueries.getAllGroups(context); }else { groupQueries.getGroupsByStringFromDb(context, query); } } }); listViewGroupList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Group group = searchedGroupListViewAdapter.getItem(i); Gson gson = new Gson(); String userStringObject = gson.toJson(group); Intent intent = new Intent(context, GroupProfileActivity.class); intent.putExtra("group", userStringObject); startActivity(intent); } }); } @Subscribe(threadMode = ThreadMode.MAIN) public void onGroupListEvent(GroupListEvent groupListEvent){ initListViewGroupList(groupListEvent.getGroupList()); } private void initListViewGroupList(List<Group> searchedGroups) { searchedGroupListViewAdapter = new GroupListViewAdapter(context, R.layout.list_element_join_group, searchedGroups); listViewGroupList.setAdapter(searchedGroupListViewAdapter); } public void onBackPressed() { super.onBackPressed(); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } @Override protected void onResume() { super.onResume(); EventBus.getDefault().register(this); } @Override protected void onPause() { EventBus.getDefault().unregister(this); super.onPause(); } }
package com.tencent.mm.ui.chatting.viewitems; import android.view.View; import android.view.ViewStub; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.R; class p$i extends p$b { ImageView hrp; TextView jWm; p$i() { } public final void cn(View view) { if (this.hri == null) { ViewStub viewStub = (ViewStub) view.findViewById(R.h.viewstub_top_voice_slot); if (viewStub != null) { viewStub.inflate(); this.hri = view.findViewById(R.h.chatting_item_biz_voice); this.eGX = (TextView) this.hri.findViewById(R.h.title); this.jWm = (TextView) this.hri.findViewById(R.h.time_tv); this.hrp = (ImageView) this.hri.findViewById(R.h.play_icon); } } } }
package org.pajacyk.ZadanieDodatkowe; public class MojTyp { static { System.out.println("blok static"); } { System.out.println("blok"); } public MojTyp() { System.out.println("blok konstruktor"); } }
package graphalgorithms; public class A_Star { }
package org.example; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; /** * Unit test for simple App. */ public class AppTest { /** * Rigorous Test :-) */ @Test public void shouldAnswerWithTrue() { TemplateEngine engine = new TemplateEngine(); ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); engine.setTemplateResolver(resolver); Context context = new Context(); context.setVariable("name","lisi"); String html= engine.process("main.html", context); System.out.println(html); } }
package com.duofei.db.mysql.custom; import com.duofei.db.mysql.entity.User; import org.springframework.stereotype.Repository; /** * 使用 拓展的 jpa 接口 * @author duofei * @date 2019/9/28 */ @Repository public interface CustomUserRepository extends ExpandJpaRepository<User, Long> { }
package pl.finsys.helloWorld; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-helloWorld.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloBean"); obj.sayHello(); } }
/** @file $Id: WinRobot.java 95 2011-10-11 16:06:14Z caoym $ * @author caoym * @brief WinRobot */ package com.caoym; import java.awt.AWTException; import java.awt.Color; import java.awt.GraphicsDevice; import java.awt.Point; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; /** * a implementation of java.awt.Robot under windows * @author caoym * */ public class WinRobot extends Robot { /* predefined cursor type */ public static final int CURSOR_APPSTARTIN = 0 ;/**< Standard arrow and small hourglass*/ public static final int CURSOR_ARROW = 1;/**< Standard arrow*/ public static final int CURSOR_CROSS = 2;/**< Crosshair*/ public static final int CURSOR_HAND = 3;/**< Windows 98/Me; Windows 2000/XP: Hand*/ public static final int CURSOR_HELP = 4;/**< Arrow and question mark*/ public static final int CURSOR_IBEAM = 5;/**< I-beam*/ public static final int CURSOR_ICON = 6;/**< Obsolete for applications marked version 4.0 or later.*/ public static final int CURSOR_NO = 7;/**< Slashed circle*/ public static final int CURSOR_SIZE = 8;/**< Obsolete for applications marked version 4.0 or later. Use CURSOR_SIZEALL.*/ public static final int CURSOR_SIZEALL = 9;/**< Four-pointed arrow pointing north; south; east; and west*/ public static final int CURSOR_SIZENESW = 10;/**< Double-pointed arrow pointing northeast and southwest*/ public static final int CURSOR_SIZENS = 11;/**< Double-pointed arrow pointing north and south*/ public static final int CURSOR_SIZENWSE = 12;/**< Double-pointed arrow pointing northwest and southeast*/ public static final int CURSOR_SIZEWE = 13;/**< Double-pointed arrow pointing west and east*/ public static final int CURSOR_UPARROW = 14;/**< Vertical arrow*/ public static final int CURSOR_WAIT = 15;/**< Hourglass*/ public static final int CURSOR_UNKNOWN = -1;/**< unknown cursor,not predefined */ public static final int JNI_LIB_VERSION = 121; public WinRobot() throws AWTException { super(); /*initialize JNI object*/ CreateJNIObj(null); } public WinRobot(GraphicsDevice device) throws AWTException { super(); /*initialize JNI object*/ if (device == null) { CreateJNIObj(null); } else { CreateJNIObj(device.getIDstring()); } } /** * export library to temp dir * @throws Exception */ private static boolean exportLibFromJar(String name) { // try { // read library from resource,this may fail if not run from a jar file InputStream in = WinRobot.class.getResourceAsStream("/" + name); if (in == null) { System.out.println("getResourceAsStream " + " from /" + name + " failed"); } if (in == null) { // read library from resource failed,so we try to load from file System.out.println("try to get " + name + " from file"); File file = new File(name); in = new FileInputStream(file); if (in == null) { System.out.println("get " + name + "from file failed"); } } if (in == null) { return false; } String path = System.getProperty("java.io.tmpdir") + "WinRobot\\" + JNI_LIB_VERSION +"\\"+ name; path = path.replace('/', '\\'); // make dirs File mkdir = new File(path.substring(0, path.lastIndexOf('\\'))); mkdir.mkdirs(); File fileOut = new File(path); System.out.println("Writing dll to: " + path); OutputStream out; out = new FileOutputStream(fileOut); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); in.close(); } catch (Exception e) { System.out.println(e.toString()); return false; } return true; } static private void deleteFile(File file,File except) { if(file.equals(except)) return; if (file.exists()) { if (file.isFile()) { try { file.delete(); } catch (Exception e) { System.out.println(e.toString()); } } else if (file.isDirectory()) { File files[] = file.listFiles(); for (int i = 0; i < files.length; i++) { deleteFile(files[i],except); } } file.delete(); } } static private void ClearOldVersion(){ deleteFile(new File(System.getProperty("java.io.tmpdir") + "WinRobot\\"), new File(System.getProperty("java.io.tmpdir") + "WinRobot\\"+JNI_LIB_VERSION)); } /** * load JNIAdapter.dll */ static { boolean bLoaded = false; //load from jar String libs[] = {"JNIAdapterx86.dll", "WinRobotCorex86.dll", "WinRobotHostx86.exe", "WinRobotHookx86.dll", "WinRobotHostPSx86.dll", "JNIAdapterx64.dll", "WinRobotCorex64.dll", "WinRobotHostx64.exe", "WinRobotHookx64.dll", "WinRobotHostPSx64.dll"}; for (int i = 0; i < libs.length; i++) { exportLibFromJar(libs[i]); } ClearOldVersion(); String path = new String(); //try{ path = System.getProperty("java.io.tmpdir") + "WinRobot\\" + JNI_LIB_VERSION; //} catch (Exception e) { // System.out.println(e.toString()); //} /*String path = getJarFolderByClassLoader(); if(path.isEmpty()){ path = getJarFolderByCodeSource(); }*/ //System.out.print(path); try { System.load(path + "\\JNIAdapterx64.dll"); bLoaded = true; } catch (UnsatisfiedLinkError e) { System.out.print("load " + path + "\\JNIAdapterx64.dll" + " failed," + e.getMessage() + "\r\n"); } if (!bLoaded) { try { System.load(path + "\\JNIAdapterx86.dll"); bLoaded = true; } catch (UnsatisfiedLinkError e) { System.out.print("load " + path + "\\JNIAdapterx86.dll" + " failed," + e.getMessage() + "\r\n"); } } if (!bLoaded) { try { System.loadLibrary("JNIAdapterx86"); bLoaded = true; } catch (UnsatisfiedLinkError e) { System.out.print("load JNIAdapterx86 failed," + e.getMessage() + "\r\n"); } } if (!bLoaded) { try { System.loadLibrary("JNIAdapterx64"); bLoaded = true; } catch (UnsatisfiedLinkError e) { System.out.print("load JNIAdapterx64 failed," + e.getMessage() + "\r\n"); } } } @Override protected void finalize() { /*terminate jni object*/ DestroyJNIObj(); try { super.finalize(); } catch (Throwable e) { System.out.println(e.toString()); } } /** * Creates an image containing pixels read from the screen. * @param screenRect the rect to capture * @return screen image */ public native WinFileMappingBuffer createScreenCaptureAsFileMapping(Rectangle screenRect); /** * Creates an image containing pixels read from the screen. * @param screenRect the rect to capture * @return screen image */ @Override public BufferedImage createScreenCapture(Rectangle screenRect) { if (screenRect == null) { return null; } WinFileMappingBuffer fm = createScreenCaptureAsFileMapping(screenRect); //return null; if (fm == null) { return null; } BufferedImage image = CreateBuffedImage(fm, false); fm.close(); return image; } /** * Sleeps for the specified time. */ @Override public native void delay(int ms); /** * Returns the number of milliseconds this Robot sleeps after generating an event. */ @Override public native int getAutoDelay(); /** * Returns the color of a pixel at the given screen coordinates. */ @Override public native Color getPixelColor(int x, int y); /** * * Returns whether this Robot automatically invokes waitForIdle after generating an event. */ @Override public native boolean isAutoWaitForIdle(); /** * Presses a given key. */ @Override public native void keyPress(int keycode); /** * Releases a given key. */ @Override public native void keyRelease(int keycode); /** * Moves mouse pointer to given screen coordinates. */ @Override public native void mouseMove(int x, int y); /** * Presses one or more mouse buttons. */ @Override public native void mousePress(int buttons); /** * Releases one or more mouse buttons. */ @Override public native void mouseRelease(int buttons); /** * Rotates the scroll wheel on wheel-equipped mice. */ @Override public native void mouseWheel(int wheelAmt); /** * Sets the number of milliseconds this Robot sleeps after generating an event. */ @Override public native void setAutoDelay(int ms); /** * Sets whether this Robot automatically invokes waitForIdle after generating an event. */ @Override public native void setAutoWaitForIdle(boolean isOn); /** * Returns a string representation of this Robot. */ @Override public native String toString(); /** * Waits until all events currently on the event queue have been processed. */ @Override public native void waitForIdle(); /** * capture mouse cursor to WinFileMappingBuffer * @param origin [out] point of the mouse cursor * @param hotspot [out] hotspot of the mouse cursor * @return mouse cursor */ public native WinFileMappingBuffer captureMouseCursorAsFileMapping(Point origin, Point hotspot, int[] type); /** * capture mouse cursor * @param origin [out] point of the mouse cursor * @param hotspot [out] hotspot of the mouse cursor * @param type [out] return the type if cursor is predefined ,or reurn CURSOR_UNKNOWN * @return mouse cursor */ public BufferedImage captureMouseCursor(java.awt.Point origin , java.awt.Point hotspot, int[] type) { WinFileMappingBuffer fm = captureMouseCursorAsFileMapping(origin, hotspot, type); if (fm == null) { return null; } if (m_last_cursor_buffer == fm && m_last_cursor_image != null) { return m_last_cursor_image; } if (m_last_cursor_buffer != null) { m_last_cursor_buffer.close(); } m_last_cursor_buffer = fm; m_last_cursor_image = CreateBuffedImage(fm, true); return m_last_cursor_image; } /** * send character * * send the supplied character as keyboard input as if the * corresponding character was generated on the keyboard */ public native void keyType(char c); /** * send CTRL-ALT-DEL */ public native void sendCtrlAltDel(); /** * Change keyboard layout of the input thread * @param KLID KeyboardLayout id @see http://msdn.microsoft.com/en-us/library/ms646305(v=vs.85).aspx */ public native void setKeyboardLayout(String KLID); /** * initialize jni object * * create a jni object which implements native methods,and * then bind to the the java object. * @param device */ private native void CreateJNIObj(String device); /** * delete the binded jni object. */ private native void DestroyJNIObj(); /** * used by jni * * save the jni object's pointer */ @SuppressWarnings("unused") private long __pJniObj; /** * Create BufferedImage from WinFileMappingBuffer * @param fm * @return */ private BufferedImage CreateBuffedImage(WinFileMappingBuffer fm, boolean bWithAlphaChanle) { BitmapFileBuffer bitmap = new BitmapFileBuffer(); if (!bitmap.Load(fm.getBuffer())) { return null; } return bitmap.GetBuffedImage(bWithAlphaChanle); } //storage last captured cursor,to decide whether //cursor is change sine the last capture private WinFileMappingBuffer m_last_cursor_buffer; private BufferedImage m_last_cursor_image; }
package com.tencent.xweb.xwalk; import android.content.Context; import org.xwalk.core.Log; import org.xwalk.core.WebViewExtension; import org.xwalk.core.WebViewExtensionListener; class XWalkWebFactory$a { private static boolean iEe = false; private static boolean vCW = false; private static boolean vDO = false; public static boolean hasInited() { return iEe; } public static boolean hasInitedCallback() { return vCW; } public static boolean isCoreReady() { return vDO; } public static boolean io(Context context) { if (iEe) { return iEe; } Log.i("XWebViewHelper", "preInit"); if (h.eM(context)) { Log.i("XWebViewHelper", "preInit finished"); iEe = true; vDO = true; } else { Log.i("XWebViewHelper", "preInit xwalk is not available"); } return iEe; } public static void initCallback(WebViewExtensionListener webViewExtensionListener) { if (!vCW) { Log.i("XWebViewHelper", "initCallback"); WebViewExtension.SetExtension(webViewExtensionListener); vCW = true; } } }
package io.flexio.services.api.documentation.Exceptions; public class ResourceManagerException extends Exception { public ResourceManagerException() { super(); } public ResourceManagerException(String s) { super(s); } public ResourceManagerException(String s, Throwable throwable) { super(s, throwable); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package co.th.aten.hospital.service; import co.th.aten.hospital.Constants; import co.th.aten.hospital.event.MessageEvent; import co.th.aten.hospital.model.MessageModel; import co.th.aten.hospital.util.Sound; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.richclient.application.Application; /** * * @author Mai */ public class MessageManagerBean implements MessageManager { private String msg; private int type; private List<Thread> restoreList; public MessageManagerBean() { restoreList = new ArrayList<Thread>(); } @Override public void showMessage(String msg) { // Sound.getInstance().stopPlayError(); this.msg = msg; type = Constants.MSG_NORMAL; for (Thread thread : restoreList) { if (thread != null) { thread.interrupt(); } } restoreList.clear(); Application.instance().getApplicationContext().publishEvent(new MessageEvent(new MessageModel(Constants.MSG_NORMAL, msg))); } @Override public void showMessage(String msg, int wait) { // Sound.getInstance().stopPlayError(); Sound.getInstance().playClick(); for (Thread thread : restoreList) { if (thread != null) { thread.interrupt(); } } restoreList.clear(); Application.instance().getApplicationContext().publishEvent(new MessageEvent(new MessageModel(Constants.MSG_NORMAL, msg))); RestoreMessage thread = new RestoreMessage(wait); thread.setName("MSG_RESTORE"); thread.start(); restoreList.add(thread); } @Override public void showError(String msg) { // Sound.getInstance().playContError(); this.msg = msg; type = Constants.MSG_ERROR_BLINK; for (Thread thread : restoreList) { if (thread != null) { thread.interrupt(); } } restoreList.clear(); Application.instance().getApplicationContext().publishEvent(new MessageEvent(new MessageModel(Constants.MSG_ERROR_BLINK, msg))); } @Override public void showError(String msg, int wait) { // Sound.getInstance().playError(); for (Thread thread : restoreList) { if (thread != null) { thread.interrupt(); } } restoreList.clear(); Application.instance().getApplicationContext().publishEvent(new MessageEvent(new MessageModel(Constants.MSG_ERROR, msg))); RestoreMessage thread = new RestoreMessage(wait); thread.setName("MSG_RESTORE"); thread.start(); restoreList.add(thread); } @Override public void clear() { showMessage(""); } @Override public String currentMessage() { return this.msg; } class RestoreMessage extends Thread { boolean stop; int delay; public RestoreMessage(int delay) { this.delay = delay; this.stop = false; } @Override public void interrupt() { stop = true; } @Override public void run() { try { while (!stop && delay > 0) { Thread.sleep(1000); delay--; } if (!stop) { Application.instance().getApplicationContext().publishEvent(new MessageEvent(new MessageModel(Constants.MSG_NORMAL, currentMessage()))); } } catch (InterruptedException ex) { Logger.getLogger(MessageManagerBean.class.getName()).log(Level.SEVERE, null, ex); } } } }
package com.duanxr.yith.easy; /** * @author 段然 2021/3/8 */ public class CustomersWhoNeverOrder { /** * Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything. * * Table: Customers. * * +----+-------+ * | Id | Name | * +----+-------+ * | 1 | Joe | * | 2 | Henry | * | 3 | Sam | * | 4 | Max | * +----+-------+ * Table: Orders. * * +----+------------+ * | Id | CustomerId | * +----+------------+ * | 1 | 3 | * | 2 | 1 | * +----+------------+ * Using the above tables as example, return the following: * * +-----------+ * | Customers | * +-----------+ * | Henry | * | Max | * +-----------+ * * 某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。 * * Customers 表: * * +----+-------+ * | Id | Name | * +----+-------+ * | 1 | Joe | * | 2 | Henry | * | 3 | Sam | * | 4 | Max | * +----+-------+ * Orders 表: * * +----+------------+ * | Id | CustomerId | * +----+------------+ * | 1 | 3 | * | 2 | 1 | * +----+------------+ * 例如给定上述表格,你的查询应返回: * * +-----------+ * | Customers | * +-----------+ * | Henry | * | Max | * +-----------+ * */ private String solution = "SELECT Customers.name AS Customers \n" + "FROM Customers LEFT JOIN Orders ON Customers.Id = Orders.CustomerId \n" + "WHERE Orders.CustomerId IS NULL"; }
package com.rc.portal.webapp.action.unionlogin; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.rc.app.framework.webapp.action.BaseAction; import com.rc.commons.util.InfoUtil; import com.rc.portal.alipay.util.AlipayNotify; import com.rc.portal.service.ICartManager; import com.rc.portal.service.OpenSqlManage; import com.rc.portal.service.TCouponCardManager; import com.rc.portal.service.TMemberManager; import com.rc.portal.service.TMemberThreeBindingManager; import com.rc.portal.util.CookieUtil; import com.rc.portal.util.NetworkUtil; import com.rc.portal.util.cookieManager; import com.rc.portal.vo.TCoupon; import com.rc.portal.vo.TLeader; import com.rc.portal.vo.TMember; import com.rc.portal.vo.TMemberBaseMessageExt; import com.rc.portal.vo.TMemberGrade; import com.rc.portal.vo.TMemberThreeBinding; import com.rc.portal.webapp.action.CartAction; import com.rc.portal.webapp.util.MD5; public class alipayReturnLoginAction extends BaseAction { private static final long serialVersionUID = 716293088099483404L; private TMemberManager tmembermanager; private TMemberThreeBinding memberThreeBinding; private TMemberThreeBindingManager tmemberthreebindingmanager; private ICartManager cartmanager; private TCouponCardManager tcouponcardmanager; public TCouponCardManager getTcouponcardmanager() { return tcouponcardmanager; } public void setTcouponcardmanager(TCouponCardManager tcouponcardmanager) { this.tcouponcardmanager = tcouponcardmanager; } public ICartManager getCartmanager() { return cartmanager; } public void setCartmanager(ICartManager cartmanager) { this.cartmanager = cartmanager; } private OpenSqlManage opensqlmanage; private TMember tmember; public TMember getTmember() { return tmember; } public void setTmember(TMember tmember) { this.tmember = tmember; } public TMemberManager getTmembermanager() { return tmembermanager; } public void setTmembermanager(TMemberManager tmembermanager) { this.tmembermanager = tmembermanager; } public TMemberThreeBinding getMemberThreeBinding() { return memberThreeBinding; } public void setMemberThreeBinding(TMemberThreeBinding memberThreeBinding) { this.memberThreeBinding = memberThreeBinding; } public TMemberThreeBindingManager getTmemberthreebindingmanager() { return tmemberthreebindingmanager; } public void setTmemberthreebindingmanager(TMemberThreeBindingManager tmemberthreebindingmanager) { this.tmemberthreebindingmanager = tmemberthreebindingmanager; } public OpenSqlManage getOpensqlmanage() { return opensqlmanage; } public void setOpensqlmanage(OpenSqlManage opensqlmanage) { this.opensqlmanage = opensqlmanage; } @SuppressWarnings({ "rawtypes", "unchecked" }) public String alipayAction() throws Exception { String key = cookieManager.getCookieValueByName(this.getRequest(), CartAction.cartKey); //获取支付宝GET过来反馈信息 Map<String,String> params = new HashMap<String,String>(); Map requestParams = this.getRequest().getParameterMap(); for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); String[] values = (String[]) requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ","; } //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化 System.out.println("-------------"+valueStr); //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); System.out.println("转码之后-------------"+valueStr); params.put(name, valueStr); } Map<String,String> paramsss = new HashMap<String,String>(); for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); String[] values = (String[]) requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ","; } //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化 System.out.println("-------------"+valueStr); valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); System.out.println("转码之后-------------"+valueStr); paramsss.put(name, valueStr); } for(Map.Entry<String, String > map:paramsss.entrySet()){ System.out.println( "返回结果的key:"+map.getKey()); System.out.println("返回结果的value:"+map.getValue()); } boolean verify_result = false; boolean verify_result2 = false; verify_result = AlipayNotify.verify(params); System.out.println("verify_result------------"+verify_result); verify_result2 = AlipayNotify.verify(paramsss); System.out.println("verify_result2------------"+verify_result2); System.out.println("params参数------------>"+params); //验证成功 if(verify_result || verify_result2){ System.out.println("支付宝进入此方法当中-----------》"); getRequest().getSession().setAttribute("demo_openid", params.get("user_id")); Map map=new HashMap(); map.put("binding_uuid", params.get("user_id")); // 根据openid判断用户信息是否已经存在 memberThreeBinding = (TMemberThreeBinding) this.opensqlmanage.selectForObjectByMap(map, "t_member_three_binding.ibatorgenerated_selectByBindingUuid"); if(memberThreeBinding == null){ TMemberGrade memberGrade1 = (TMemberGrade) opensqlmanage.selectObjectByObject(null, "t_member_grade.selectDefaultGrade"); TMemberGrade memberGrade2 = (TMemberGrade) opensqlmanage.selectObjectByObject(null, "t_member_grade.selectlowGrade"); memberThreeBinding=new TMemberThreeBinding(); tmember = new TMember(); TMemberBaseMessageExt tmemberBaseMessageext=new TMemberBaseMessageExt(); tmemberBaseMessageext.setNickName(params.get("real_name")); this.getRequest().setAttribute("otherNickName", params.get("real_name")); tmember.setUserName(params.get("user_id")); tmember.setAreaId(0l); if(memberGrade1!=null){ tmember.setMemberGradeId(memberGrade1.getId()); }else{ tmember.setMemberGradeId(memberGrade2.getId()); } tmember.setPassword(MD5.MD5("111"+params.get("user_id")+"yao")); tmember.setNickName(params.get("real_name")); tmember.setStatus(0); tmember.setEnterpriseDiscount(new BigDecimal(0)); tmember.setIsLeader(0); tmember.setIntegral(0); tmember.setSource(2);//支付宝 tmember.setPlatform(1);//1表示PC平台 tmember.setRegisterIp(NetworkUtil.getIpAddress(this.getRequest())); tmember.setRegisterDate(new Date()); tmember.setLastDate(new Date()); tmember.setLastIp(NetworkUtil.getIpAddress(this.getRequest())); tmember.setIsEmailCheck(0); tmember.setIsMobileCheck(0); tmember.setAgentId(getAgentId()); tmember.setIsAgent(0); TLeader leader = getLeader(); tmembermanager.insertSelective(tmember,leader); tmemberBaseMessageext.setMemberId(tmember.getId()); tmembermanager.savetmemberbasemessageext(tmemberBaseMessageext); if (tmember != null) { memberThreeBinding.setMemberId(tmember.getId()); } memberThreeBinding.setSource(2);//支付宝 memberThreeBinding.setCreateDate(new Date()); memberThreeBinding.setBindingUuid(params.get("user_id")); tmembermanager.saveMemberThreeBinding(memberThreeBinding); if(key!=null){ cartmanager.synCart(tmember.getId(), key); } //this.getSession().setAttribute("member", tmember); //新用户送优惠券 String cp = InfoUtil.getInstance().getInfo("config", "regCouponId"); List regCouponMap = new ArrayList(); String regCouponId=""; Map couponMap=new HashMap(); if(cp!=null&&!cp.equals("")){ String c[] = cp.split(","); for (int i = 0; i < c.length; i++) { regCouponId=c[i]; couponMap.put("regCouponId", regCouponId); TCoupon coupon = (TCoupon) opensqlmanage.selectObjectByObject(couponMap, "t_coupon.selectCouponByid"); regCouponMap.add(coupon); } tcouponcardmanager.bindingCoupon(regCouponMap,tmember.getId(), 1); } String attribute = (String)this.getSession().getAttribute("LoginRedirect"); if(tmember.getMobile()==null || tmember.getMobile()==""){ return "popup"; }else{ this.getSession().setAttribute("member", tmember); if (attribute == null) { this.getResponse().sendRedirect("/index.html"); } else { this.getSession().removeAttribute("LoginRedirect"); this.getResponse().sendRedirect(attribute); } } }else{ System.out.println("进入此方法当中-----------》"); Map openmap=new HashMap(); openmap.put("binding_uuid", params.get("user_id")); TMember member = (TMember) opensqlmanage.selectObjectByObject(openmap, "t_member.selectmemberByOpenid"); if(key!=null){ cartmanager.synCart(member.getId(), key); } //this.getSession().setAttribute("member", member); System.out.println("用户名----------------》"+member.getUserName()); String attribute = (String)this.getSession().getAttribute("LoginRedirect"); this.getRequest().setAttribute("otherNickName", params.get("real_name")); if(member.getMobile()==null || member.getMobile()==""){ return "popup"; }else{ this.getSession().setAttribute("member", member); if (attribute == null) { this.getResponse().sendRedirect("/index.html"); } else { this.getSession().removeAttribute("LoginRedirect"); this.getResponse().sendRedirect(attribute); } } } }else{ System.out.println("验证失败"); return "index"; } return "index"; } /* * 领袖下线 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public TLeader getLeader(){ String code = CookieUtil.getCookie(this.getRequest(), "leader");//通过code,查找leader Map map=new HashMap(); map.put("code", code); TLeader tleader = (TLeader) opensqlmanage.selectObjectByObject(map, "t_leader.selectLeaderByCode"); return tleader; } /* * 获取代理人Id */ public Long getAgentId(){ String code = CookieUtil.getCookie(this.getRequest(), "agent");//通过code,获取代理人Id if(code!=null){ return Long.parseLong(code); }else{ return null; } } @Override public Object getModel() { // TODO Auto-generated method stub return null; } @Override public void setModel(Object o) { // TODO Auto-generated method stub } }
package com.tencent.mm.plugin.appbrand.jsapi.camera; import com.tencent.mm.plugin.appbrand.jsapi.h; import com.tencent.mm.plugin.appbrand.page.p; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; public final class e extends h { private static final int CTRL_INDEX = 455; public static final String NAME = "onCameraScanCode"; public static e fOF = new e(); public static void a(p pVar, int i, String str, String str2) { Map hashMap = new HashMap(); hashMap.put("cameraId", Integer.valueOf(i)); hashMap.put("type", str); hashMap.put("result", str2); String jSONObject = new JSONObject(hashMap).toString(); h a = fOF.a(pVar); a.mData = jSONObject; a.ahM(); } }
/* The MIT License (MIT) Copyright (c) 2014 Pierre Lindenbaum 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. History: * 2014 creation */ package com.github.lindenb.jvarkit.util.bio; public abstract class GeneticCode { /** the standard genetic code */ private static final GeneticCode STANDARD=new GeneticCode() { @Override protected String getNCBITable() { return "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"; } }; /** mitochondrial genetic code */ private static final GeneticCode MITOCHONDRIAL=new GeneticCode() { @Override protected String getNCBITable() { return "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSS**VVVVAAAADDEEGGGG"; } }; /** get the genetic-code table (NCBI data) */ protected abstract String getNCBITable(); /** convert a base to index */ private static int base2index(char c) { switch(c) { case 'T': case 't': return 0; case 'C': case 'c': return 1; case 'A': case 'a': return 2; case 'G': case 'g': return 3; default: return -1; } } /** translate cDNA to aminoacid */ public char translate(char b1,char b2,char b3) { final int base1= base2index(b1); final int base2= base2index(b2); final int base3= base2index(b3); if(base1==-1 || base2==-1 || base3==-1) { return '?'; } else { return getNCBITable().charAt(base1*16+base2*4+base3); } } /** get the standard genetic code */ public static GeneticCode getStandard() { return STANDARD; } /** get the mitochondrial genetic code */ public static GeneticCode getMitochondrial() { return MITOCHONDRIAL; } /** returns aminoacid to the 3 letter code. Returns *** for stop, return null if to correspondance */ public static String aminoAcidTo3Letters(char c) { switch(Character.toUpperCase(c)) { case 'A': return "Ala"; case 'R': return "Arg"; case 'N': return "Asn"; case 'D': return "Asp"; case 'C': return "Cys"; case 'E': return "Glu"; case 'Q': return "Gln"; case 'G': return "Gly"; case 'H': return "His"; case 'I': return "Ile"; case 'L': return "Leu"; case 'K': return "Lys"; case 'M': return "Met"; case 'F': return "Phe"; case 'P': return "Pro"; case 'S': return "Ser"; case 'T': return "Thr"; case 'W': return "Trp"; case 'Y': return "Tyr"; case 'V': return "Val"; case '*': return "***"; default: return null; } } }
package com.company; public class Main { // int score = 1000 // // // int positionRank = highScoreTable(1500); // displayHighScorePosition("phill", positionRank); // positionRank = highScoreTable(900); // displayHighScorePosition("lary", positionRank); // positionRank = highScoreTable(400); // displayHighScorePosition("frog", positionRank); // positionRank = highScoreTable(50); // displayHighScorePosition("tim", positionRank); // positionRank = highScoreTable(1000); // displayHighScorePosition("bob", positionRank); // // // } // public static int highScoreTable(int score){ // int rank = 4; // if (score >= 1000) { // rank = 1; // }else if (score >= 500) { // rank = 2; // }else if (score >= 100) { // rank = 3; // } // return rank; // } // public static void displayHighScorePosition(String playerName, int positionRank) { // System.out.println(playerName + " maganed to get to " + positionRank + " on the high score table"); // } //} }
package daoGeneric; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; @SuppressWarnings("deprecation") public abstract class HibernateControl { private static SessionFactory factory; static { try { factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public synchronized static SessionFactory getFactory() { return factory; } public static void shutdown() { getFactory().close(); } public synchronized static Session getSession() { return factory.openSession(); } }
package LC0_200.LC150_200; public class LC176_Second_Highest_Salary { // mysql }
package com.view; import javax.swing.JFrame; public class HPresult extends javax.swing.JFrame { public HPresult() { initComponents(); setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); } public void Main(String pattern, String source) { HPresult hss = new HPresult(); char[] patt = pattern.toLowerCase().toCharArray(); char[] src = source.toLowerCase().toCharArray(); int pos = hss.Horspool(patt, src); if (pos == -1) { msg.setText("<html>SORRY, I COULD NOT FIND WHAT<br> YOU WERE LOOKING FOR.. :( </html>"); } else { msg.setText("<html>I HAVE FOUND " + pos + " AVAILABLE DISH(ES)<br> FOR: " + pattern.toUpperCase() + "</html>"); } } public int Horspool(char[] p, char[] t) { HPresult hss = new HPresult(); int[] shift = hss.shiftTable(p); int counter = 0; int i = p.length - 1; int m = p.length; int k; while (i <= t.length - 1) { k = 0; while ((k <= m - 1) && (p[m - 1 - k] == t[i - k])) { k = k + 1; } if (k == m) { counter++; i = i + shift[t[i]]; //return i - m + 1; } else { i = i + shift[t[i]]; } } if (counter > 0) return counter; else return -1; } public int[] shiftTable(char[] p) { int[] s = new int[500]; int m = p.length; for (int i = 0; i < s.length; i++) { s[i] = m; //yung buonf shift table value muna is yng pattern length } for (int j = 0; j <= m - 2; j++) { s[p[j]] = m - 1 - j; //ito na yung shifts ng mga letters, the rest is yng pattern length } return s; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); msg = new javax.swing.JLabel(); Back = new javax.swing.JButton(); label = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setPreferredSize(new java.awt.Dimension(1366, 720)); jPanel1.setLayout(null); msg.setFont(new java.awt.Font("Baskerville Old Face", 0, 49)); // NOI18N msg.setForeground(new java.awt.Color(255, 222, 0)); msg.setText("jLabel2"); jPanel1.add(msg); msg.setBounds(110, 140, 920, 280); Back.setBackground(new java.awt.Color(153, 153, 153)); Back.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N Back.setText("Again"); Back.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); Back.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BackActionPerformed(evt); } }); jPanel1.add(Back); Back.setBounds(650, 620, 90, 40); label.setFont(new java.awt.Font("Baskerville Old Face", 0, 49)); // NOI18N label.setForeground(new java.awt.Color(255, 222, 0)); label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/view/images/blank.png"))); // NOI18N jPanel1.add(label); label.setBounds(0, 0, 1370, 720); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void BackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackActionPerformed Search srch = new Search(); srch.setVisible(true); dispose(); }//GEN-LAST:event_BackActionPerformed public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(HPresult.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(HPresult.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(HPresult.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(HPresult.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new HPresult().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Back; private javax.swing.JPanel jPanel1; private javax.swing.JLabel label; private javax.swing.JLabel msg; // End of variables declaration//GEN-END:variables }
package qual; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class QualC { //private static final String fileName = "res/C-sample.in"; //private static final String fileName = "res/C-small-attempt0.in"; private static final String fileName = "res/C-large.in"; private static BufferedReader br; private static HashMap<String, HashMap<String, String>> charsMap; public static void main(String[] args) throws Exception { createMap(); br = new BufferedReader(new FileReader(fileName)); // number of test-cases int T = Integer.valueOf(br.readLine()); // process each case for (int t=0; t < T; t++) { long L, X; String LX[] = br.readLine().split(" "); L = Long.valueOf(LX[0]); X = Long.valueOf(LX[1]); String in = br.readLine(); processCase(t+1, L, X, in); } br.close(); } public static void processCase(int t, long L, long X, String in) { long endI = -1, endJ = - 1; while (true) { long cursor = 0; char i = '1'; char j = '1'; char k = '1'; char working = 'i'; boolean negative = false; for (int x = 0; x < X; x++) { for (int l = 0; l < L; l++) { if (working == 'i') { String tmp = multiply(i, in.charAt(l)); i = tmp.charAt(tmp.length()-1); if (tmp.length() == 2) { negative = !negative; } } else if (working == 'j') { String tmp = multiply(j, in.charAt(l)); j = tmp.charAt(tmp.length()-1); if (tmp.length() == 2) { negative = !negative; } } else if (working == 'k') { String tmp = multiply(k, in.charAt(l)); k = tmp.charAt(tmp.length()-1); if (tmp.length() == 2) { negative = !negative; } } if (!negative) { if (working == 'i' && i == 'i' && cursor > endI) { working = 'j'; endI = cursor; endJ = cursor; } else if (working == 'j' && j == 'j' && cursor > endJ) { working = 'k'; endJ = cursor; } } cursor++; } } System.out.println(negative); System.out.println(working); if (!negative && k == 'k') { System.out.println("Case #" + t + ": YES"); break; } else if (working == 'i') { System.out.println("Case #" + t + ": NO"); break; } else if (working == 'j') { endI++; } } } private static void createMap() { charsMap = new HashMap<String, HashMap<String, String>>(); HashMap<String, String> tmpMap; tmpMap = new HashMap<String, String>(); tmpMap.put("1", "1"); tmpMap.put("i", "i"); tmpMap.put("j", "j"); tmpMap.put("k", "k"); charsMap.put("1", tmpMap); tmpMap = new HashMap<String, String>(); tmpMap.put("1", "i"); tmpMap.put("i", "-1"); tmpMap.put("j", "k"); tmpMap.put("k", "-j"); charsMap.put("i", tmpMap); tmpMap = new HashMap<String, String>(); tmpMap.put("1", "j"); tmpMap.put("i", "-k"); tmpMap.put("j", "-1"); tmpMap.put("k", "i"); charsMap.put("j", tmpMap); tmpMap = new HashMap<String, String>(); tmpMap.put("1", "k"); tmpMap.put("i", "j"); tmpMap.put("j", "-i"); tmpMap.put("k", "-1"); charsMap.put("k", tmpMap); } private static String multiply(char a, char b) { String sa = "" + a; String sb = "" + b; return charsMap.get(sa).get(sb); } }
package com.example.SBNZ.repository; import com.example.SBNZ.model.diet.Diet; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface DietRepository extends JpaRepository<Diet, Integer> { }
package accu.my.test; import com.weibo.net.RequestToken; import com.weibo.net.Weibo; import com.weibo.net.WeiboException; import android.app.Activity; import android.os.Bundle; /* *ÎÒÊǽ´ÓÍÄÐ * */ public class TestWeiboOpenPlatformActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Weibo weibo = Weibo.getInstance(); String callback_url = ""; try { RequestToken requestToken = weibo.getRequestToken(getApplication(), weibo.getAppKey(), weibo.getAppSecret(), callback_url); } catch (WeiboException e) { e.printStackTrace(); } } }
package com.google.android.exoplayer2.source; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.i.a; import java.util.Arrays; public final class l { private int aeo; public final Format[] asb; public final int length; public l(Format... formatArr) { a.ap(formatArr.length > 0); this.asb = formatArr; this.length = formatArr.length; } public final int j(Format format) { for (int i = 0; i < this.asb.length; i++) { if (format == this.asb[i]) { return i; } } return -1; } public final int hashCode() { if (this.aeo == 0) { this.aeo = Arrays.hashCode(this.asb) + 527; } return this.aeo; } public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } l lVar = (l) obj; if (this.length == lVar.length && Arrays.equals(this.asb, lVar.asb)) { return true; } return false; } }
/* * Copyright 2017 Sanjin Sehic * * 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 simple.actor; import org.junit.runner.RunWith; import alioli.Scenario; import simple.actor.testing.SameThreadRunner; import simple.actor.testing.SpyActor; import static alioli.Asserts.assertThrows; import static com.google.common.truth.Truth.assertThat; /** Tests for {@link System}. */ @RunWith(Scenario.Runner.class) public class SystemTest extends Scenario { { subject("an actor is registered", () -> { final System system = new System(new SameThreadRunner()); final SpyActor<Message> actor = new SpyActor<>(); final Channel<Message> channel = system.register(actor); should("be started", () -> { assertThat(actor.isStarted()).isTrue(); }); should("not be stopped", () -> { assertThat(actor.isStopped()).isFalse(); }); should("succeed to send and deliver a message ", () -> { final Message message = new Message(); assertThat(channel.send(message)).isTrue(); assertThat(actor.getReceivedMessages()).containsExactly(message); }); and("channel is stopped", () -> { channel.stop(); should("stop the actor", () -> { assertThat(actor.isStopped()).isTrue(); }); should("fail to send a message", () -> { assertThat(channel.send(new Message())).isFalse(); assertThat(actor.getReceivedMessages()).isEmpty(); }); }); and("system is stopped", () -> { system.stop(); should("stop the actor", () -> { assertThat(actor.isStopped()).isTrue(); }); should("fail to send a message", () -> { assertThat(channel.send(new Message())).isFalse(); assertThat(actor.getReceivedMessages()).isEmpty(); }); }); and("system is paused", () -> { system.pause(); should("succeed to send a message but not deliver it", () -> { assertThat(channel.send(new Message())).isTrue(); assertThat(actor.getReceivedMessages()).isEmpty(); }); should("deliver the message after being resumed", () -> { final Message message = new Message(); channel.send(message); system.resume(); assertThat(actor.getReceivedMessages()).containsExactly(message); }); should("deliver the message after system is resumed " + "even if actor's channel was previously stopped", () -> { final Message message = new Message(); assertThat(channel.send(message)).isTrue(); channel.stop(); system.resume(); assertThat(actor.getReceivedMessages()).containsExactly(message); }); should("deliver messages after system is resumed " + "even if system was previously stopped", () -> { final Message message = new Message(); assertThat(channel.send(message)).isTrue(); system.stop(); system.resume(); assertThat(actor.getReceivedMessages()).containsExactly(message); }); and("actor's channel is stopped", () -> { channel.stop(); should("not stop the actor immediately", () -> { assertThat(actor.isStopped()).isFalse(); }); should("stop the actor after system is resumed", () -> { system.resume(); assertThat(actor.isStopped()).isTrue(); }); }); and("then stopped", () -> { system.stop(); should("not stop the actor immediately", () -> { assertThat(actor.isStopped()).isFalse(); }); should("stop the actor after system is resumed", () -> { system.resume(); assertThat(actor.isStopped()).isTrue(); }); }); }); }); subject("system", () -> { final System system = new System(new SameThreadRunner()); when("paused", () -> { system.pause(); and("actor is registered", () -> { final SpyActor<Object> actor = new SpyActor<>(); final Channel<Object> channel = system.register(actor); should("not be started", () -> { assertThat(actor.isStarted()).isFalse(); }); should("not be stopped", () -> { assertThat(actor.isStopped()).isFalse(); }); should("succeed to send a message but not deliver it", () -> { assertThat(channel.send(new Object())).isTrue(); assertThat(actor.getReceivedMessages()).isEmpty(); }); should("be started after being resumed", () -> { system.resume(); assertThat(actor.isStarted()).isTrue(); }); and("actor's channel is stopped", () -> { channel.stop(); should("start the actor after system is resumed", () -> { system.resume(); assertThat(actor.isStarted()).isTrue(); }); should("stop the actor after system is resumed", () -> { system.resume(); assertThat(actor.isStopped()).isTrue(); }); }); and("system is stopped", () -> { system.stop(); should("start the actor after system is resumed", () -> { system.resume(); assertThat(actor.isStarted()).isTrue(); }); should("stop the actor after system is resumed", () -> { system.resume(); assertThat(actor.isStopped()).isTrue(); }); }); should("deliver the message after being resumed", () -> { final Object message = new Object(); channel.send(message); system.resume(); assertThat(actor.getReceivedMessages()).containsExactly(message); }); }); }); when("stopped", () -> { system.stop(); should("fail to register an actor", () -> { final SpyActor<Object> actor = new SpyActor<>(); final Exception failure = assertThrows(() -> system.register(actor)); assertThat(failure).isInstanceOf(IllegalStateException.class); }); }); }); } private static final class Message {} }
package com.bytedance.sandboxapp.protocol.service.a.a.a; public interface c { void a(); } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\protocol\service\a\a\a\c.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package org.hieu.builer; public abstract class ColdDrink implements Item { @Override public String name() { // TODO Auto-generated method stub return null; } @Override public String packing() { // TODO Auto-generated method stub Packing bottle = new Bottle(); return bottle.pack(); } @Override public float price() { // TODO Auto-generated method stub return 0; } }
package com.mideas.rpg.v2.game.item.shop; import com.mideas.rpg.v2.game.item.stuff.Stuff; public class Shop { private Stuff[] stuff = new Stuff[11]; public Stuff[] getstuff() { return stuff; } public Stuff getStuff(int i) { if(i < stuff.length) { return stuff[i]; } return null; } public void setStuff(int i, Stuff stuff) { if(i < this.stuff.length) { this.stuff[i] = stuff; } } }
package petko.osm.model.impl.simple; import java.util.ArrayList; import java.util.Collection; import java.util.List; import petko.osm.model.facade.OSMObjectType; import petko.osm.model.facade.OsmNode; import petko.osm.model.facade.OsmObject; import petko.osm.model.facade.OsmRelation; import petko.osm.model.facade.OsmWay; public class OsmDataFilter { public static List<OsmNode> nodes(Collection<? extends OsmObject> osmData) { if (osmData != null) { List<OsmNode> res = new ArrayList<>(); for (OsmObject iOsmObject : osmData) { if (iOsmObject.getType().equals(OSMObjectType.NODE)) { res.add((OsmNode) iOsmObject); } } return res; } return null; } public static List<OsmWay> ways(Collection<? extends OsmObject> osmData) { if (osmData != null) { List<OsmWay> res = new ArrayList<>(); for (OsmObject iOsmObject : osmData) { if (iOsmObject.getType().equals(OSMObjectType.WAY)) { res.add((OsmWay) iOsmObject); } } return res; } return null; } public static List<OsmRelation> relations(Collection<? extends OsmObject> osmData) { if (osmData != null) { List<OsmRelation> res = new ArrayList<>(); for (OsmObject iOsmObject : osmData) { if (iOsmObject.getType().equals(OSMObjectType.RELATION)) { res.add((OsmRelation) iOsmObject); } } return res; } return null; } }
package com.cszjkj.aisc.cm_message; public class CmMessageApplication { }
package com.tencent.mm.plugin.report.kvdata; import com.tencent.mm.bk.a; import java.util.LinkedList; public class IMBehavior extends a { public IMBehaviorChattingOP chattingOp; public IMBehaviorMsgOP msgOp; public int opType; protected final int a(int i, Object... objArr) { int fQ; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; aVar.fT(1, this.opType); if (this.chattingOp != null) { aVar.fV(2, this.chattingOp.boi()); this.chattingOp.a(aVar); } if (this.msgOp != null) { aVar.fV(3, this.msgOp.boi()); this.msgOp.a(aVar); } return 0; } else if (i == 1) { fQ = f.a.a.a.fQ(1, this.opType) + 0; if (this.chattingOp != null) { fQ += f.a.a.a.fS(2, this.chattingOp.boi()); } if (this.msgOp != null) { return fQ + f.a.a.a.fS(3, this.msgOp.boi()); } return fQ; } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (fQ = a.a(aVar2); fQ > 0; fQ = a.a(aVar2)) { if (!super.a(aVar2, this, fQ)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; IMBehavior iMBehavior = (IMBehavior) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); LinkedList IC; int size; byte[] bArr; f.a.a.a.a aVar4; boolean z; switch (intValue) { case 1: iMBehavior.opType = aVar3.vHC.rY(); return 0; case 2: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); IMBehaviorChattingOP iMBehaviorChattingOP = new IMBehaviorChattingOP(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = iMBehaviorChattingOP.a(aVar4, iMBehaviorChattingOP, a.a(aVar4))) { } iMBehavior.chattingOp = iMBehaviorChattingOP; } return 0; case 3: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); IMBehaviorMsgOP iMBehaviorMsgOP = new IMBehaviorMsgOP(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = iMBehaviorMsgOP.a(aVar4, iMBehaviorMsgOP, a.a(aVar4))) { } iMBehavior.msgOp = iMBehaviorMsgOP; } return 0; default: return -1; } } } }
/* 1: */ package com.kaldin.openid; /* 2: */ /* 3: */ import com.google.appengine.api.urlfetch.URLFetchService; /* 4: */ import com.google.appengine.api.urlfetch.URLFetchServiceFactory; /* 5: */ import com.google.inject.AbstractModule; /* 6: */ import com.google.inject.CreationException; /* 7: */ import com.google.inject.Provides; /* 8: */ import com.google.inject.Singleton; /* 9: */ import com.google.inject.binder.AnnotatedBindingBuilder; /* 10: */ import com.google.step2.discovery.DefaultHostMetaFetcher; /* 11: */ import com.google.step2.discovery.HostMetaFetcher; /* 12: */ import com.google.step2.hybrid.HybridOauthMessage; /* 13: */ import com.google.step2.openid.ax2.AxMessage2; /* 14: */ import com.google.step2.xmlsimplesign.CertValidator; /* 15: */ import com.google.step2.xmlsimplesign.DefaultCertValidator; /* 16: */ import com.google.step2.xmlsimplesign.DisjunctiveCertValidator; /* 17: */ import org.openid4java.consumer.ConsumerAssociationStore; /* 18: */ import org.openid4java.message.Message; /* 19: */ import org.openid4java.message.MessageException; /* 20: */ /* 21: */ public class GuiceModule /* 22: */ extends AbstractModule /* 23: */ { /* 24: */ ConsumerAssociationStore associationStore; /* 25: */ /* 26: */ public GuiceModule(ConsumerAssociationStore associationStore) /* 27: */ { /* 28: 54 */ this.associationStore = associationStore; /* 29: */ } /* 30: */ /* 31: */ protected void configure() /* 32: */ { /* 33: */ try /* 34: */ { /* 35: 60 */ Message.addExtensionFactory(AxMessage2.class); /* 36: */ } /* 37: */ catch (MessageException e) /* 38: */ { /* 39: 62 */ throw new CreationException(null); /* 40: */ } /* 41: */ try /* 42: */ { /* 43: 66 */ Message.addExtensionFactory(HybridOauthMessage.class); /* 44: */ } /* 45: */ catch (MessageException e) /* 46: */ { /* 47: 68 */ throw new CreationException(null); /* 48: */ } /* 49: 71 */ bind(ConsumerAssociationStore.class).toInstance(this.associationStore); /* 50: 75 */ if (isRunningOnAppengine()) { /* 51: 76 */ install(new GuiceModule$AppEngineModule()); /* 52: */ } /* 53: */ } /* 54: */ /* 55: */ private boolean isRunningOnAppengine() /* 56: */ { /* 57: 85 */ if (System.getSecurityManager() == null) { /* 58: 86 */ return false; /* 59: */ } /* 60: 88 */ return System.getSecurityManager().getClass().getCanonicalName().startsWith("com.google"); /* 61: */ } /* 62: */ /* 63: */ @Provides /* 64: */ @Singleton /* 65: */ public CertValidator provideCertValidator(DefaultCertValidator defaultValidator) /* 66: */ { /* 67: 95 */ CertValidator hardCodedValidator = new GuiceModule$1(this); /* 68: */ /* 69: */ /* 70: */ /* 71: */ /* 72: */ /* 73: */ /* 74: */ /* 75:103 */ return new DisjunctiveCertValidator(new CertValidator[] { defaultValidator, hardCodedValidator }); /* 76: */ } /* 77: */ /* 78: */ @Provides /* 79: */ @Singleton /* 80: */ public HostMetaFetcher provideHostMetaFetcher(DefaultHostMetaFetcher fetcher1, GoogleHostedHostMetaFetcher fetcher2) /* 81: */ { /* 82:117 */ return fetcher2; /* 83: */ } /* 84: */ /* 85: */ @Provides /* 86: */ @Singleton /* 87: */ public URLFetchService provideUrlFetchService() /* 88: */ { /* 89:124 */ return URLFetchServiceFactory.getURLFetchService(); /* 90: */ } /* 91: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.openid.GuiceModule * JD-Core Version: 0.7.0.1 */
package com.beiyelin.person.service.impl; import com.beiyelin.common.reqbody.PageReq; import com.beiyelin.common.resbody.PageResp; import com.beiyelin.common.utils.StrUtils; import com.beiyelin.commonsql.jpa.BaseItemCRUDServiceImpl; import com.beiyelin.person.bean.PersonContactInfoQuery; import com.beiyelin.person.entity.Person; import com.beiyelin.person.entity.PersonContactInfo; import com.beiyelin.person.repository.PersonContactInfoRepository; import com.beiyelin.person.service.PersonContactInfoService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import static com.beiyelin.common.constant.MessageCaption.MESSAGE_PARAM_IS_NULL; import static com.beiyelin.common.utils.CheckUtils.notNull; import static java.lang.String.format; /** * @Description: * @Author: newmann * @Date: Created in 20:12 2018-02-23 */ @Service("contactInfoService") @Slf4j public class PersonContactInfoServiceImpl extends BaseItemCRUDServiceImpl<PersonContactInfo, Person> implements PersonContactInfoService { private PersonContactInfoRepository personContactInfoRepository; @Autowired public void setPersonContactInfoRepository(PersonContactInfoRepository personContactInfoRepository) { this.setSuperRepository(personContactInfoRepository); this.personContactInfoRepository = personContactInfoRepository; } // @Override // public List<PersonContactInfo> findAllByPersonIdOrderByType(String personId) { // notNull(personId,MESSAGE_PARAM_IS_NULL); // // log.info(format("开始查询PersonId为 %s 对应的地址",personId)); // // List<PersonContactInfo> result = this.personContactInfoRepository.findAllByPersonIdOrderByType(personId); // // log.info("查询结束,共获取数据 %d 条。",result.size()); // // return result; // } @Override public PageResp<PersonContactInfo> fetchByQuery(PersonContactInfoQuery query, PageReq pageReq) { notNull(query,MESSAGE_PARAM_IS_NULL); notNull(pageReq,MESSAGE_PARAM_IS_NULL); log.info(format("开始查询,查询条件:%s,分页条件:%s",query.toString(),pageReq.toString())); Specification<PersonContactInfo> querySpec = new Specification<PersonContactInfo>(){ @Override public Predicate toPredicate(Root<PersonContactInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { List<Predicate> predicates = new ArrayList<>(); if (!StrUtils.isEmpty(query.getPersonId())){ predicates.add(criteriaBuilder.equal(root.get("personId"), query.getPersonId())); } if (!StrUtils.isEmpty(query.getType())){ predicates.add(criteriaBuilder.like(root.get("type"),"%" + query.getType()+"%")); } if (! StrUtils.isEmpty(query.getContactMethod().getContactCountryId())){ predicates.add(criteriaBuilder.equal(root.get("contactMethod").get("contactCountryId"),query.getContactMethod().getContactCountryId())); } if (! StrUtils.isEmpty(query.getContactMethod().getContactProvinceId())){ predicates.add(criteriaBuilder.equal(root.get("contactMethod").get("contactProvinceId"),query.getContactMethod().getContactProvinceId())); } if (! StrUtils.isEmpty(query.getContactMethod().getContactCityId())){ predicates.add(criteriaBuilder.equal(root.get("contactMethod").get("contactCityId"),query.getContactMethod().getContactCityId())); } if (!StrUtils.isEmpty(query.getContactMethod().getContactDetailAddress())){ predicates.add(criteriaBuilder.like(root.get("contactMethod").get("contactDetailAddress"),"%" + query.getContactMethod().getContactDetailAddress() + "%")); } if (!StrUtils.isEmpty(query.getContactMethod().getContactZipCode())){ predicates.add(criteriaBuilder.like(root.get("contactMethod").get("contactZipCode"),"%" + query.getContactMethod().getContactZipCode() + "%")); } if (!StrUtils.isEmpty(query.getContactMethod().getContactPhone())){ predicates.add(criteriaBuilder.like(root.get("contactMethod").get("contactPhone"),"%" + query.getContactMethod().getContactPhone() + "%")); } if (!StrUtils.isEmpty(query.getContactMethod().getContactEmail())){ predicates.add(criteriaBuilder.like(root.get("contactMethod").get("contactEmail"),"%" + query.getContactMethod().getContactEmail() + "%")); } if (query.getModifyDateBegin()>0) { predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("modifyAction").get("modifyDateTime"),query.getModifyDateBegin())); } if (query.getModifyDateEnd()>0) { predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("modifyAction").get("modifyDateTime"),query.getModifyDateEnd())); } return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); } }; Page<PersonContactInfo> findEntity = personContactInfoRepository.findAll(querySpec,pageReq.toPageable()); log.info(format("查询结束。条数为:%d",findEntity.getSize())); return new PageResp<>(findEntity); } }
package com.xj.library.utils; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; /** * @author meitu.xujun on 2017/4/11 14:31 * @version 0.1 */ public class ClipboardUtils { /** * 实现文本复制功能 * add by wangqianzhou * * @param content */ public static void copy(String content, Context context) { // 得到剪贴板管理器 ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context .CLIPBOARD_SERVICE); cmb.setPrimaryClip(ClipData.newPlainText(null, content.trim())); // cmb.setText(content.trim()); } /** * 实现粘贴功能 * add by wangqianzhou * * @param context * @return */ public static String paste(Context context) { // 得到剪贴板管理器 ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context .CLIPBOARD_SERVICE); return cmb.getPrimaryClip().toString().trim(); // return cmb.getText().toString().trim(); } }
package com.smxknife.java2.thread.executorservice.demo02; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author smxknife * 2019/8/28 */ public class _Run { public static void main(String[] args) { try { CallableException callableException = new CallableException(); CallableNormal callableNormal = new CallableNormal(); CallableExceptionWithAnotherTryCatch callableExceptionWithAnotherTryCatch = new CallableExceptionWithAnotherTryCatch(); List list = new ArrayList<>(); list.add(callableException); list.add(callableNormal); list.add(callableExceptionWithAnotherTryCatch); ExecutorService executorService = Executors.newCachedThreadPool(); String string = (String) executorService.invokeAny(list); System.out.println("result = " + string); } catch (Exception e) { System.out.println("main exception"); e.printStackTrace(); } } }
package othello.ui; public enum Couleur { NOIR, BLANC, NONE }
package com.puti.pachong.example.wukong; import lombok.AllArgsConstructor; import lombok.Data; /** * 悟空问题 */ @Data @AllArgsConstructor public class Question { private String qid; private String title; }
package net.liuzd.spring.boot.v2.dao; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import net.liuzd.spring.boot.v2.domain.Blog; public interface BlogRepository extends ElasticsearchRepository<Blog, String> { //方法名定义查询:根据用户名模糊查询 Page<Blog> findByUsernameContaining(String username, Pageable pageable); }
package com.argentinatecno.checkmanager.main.fragment_add; import android.content.Context; import com.argentinatecno.checkmanager.entities.Check; public interface FragmentAddInteractor { void saveCheck(Check check, Context context); void updateCheck(Check check, Context context); }
/** * 题目:矩阵中的路径 题:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。 如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 思路: 回溯法->递归 */ public class Interview12{ public boolean hasPath(char[][] matrix,char[] str){ /** * 判断matrix矩阵中是否存在字符串str. */ if(matrix ==null || str ==null){ return false; } int rows=matrix.length; int cols=matrix.length; int pathLength=0; // 定义一个访问数组表明matrix数组相应位置有没有被访问过 boolean[][] visited=new boolean[rows][cols]; for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ visited[i][j]=false; } } for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ if(hasPathCore(matrix,rows,cols,i,j,visited,str,pathLength)){ return true; } } } return false; } public boolean hasPathCore(char[][] matrix,int rows,int cols,int row,int col,boolean[][] visited,char[] str,int pathLength){ /** * 从matrix矩阵开始寻找,是否存在路径str的第pathLength个元素的匹配路径. */ // 匹配成功 if(pathLength>=str.length){ return true; } // 递归终止条件 if(row<0||row>=rows||col<0||col>=cols||visited[row][col]==true||str[pathLength]!=matrix[row][col]){ return false; } visited[row][col]=true; // 上下左右存在路径 if (hasPathCore(matrix, rows, cols, row-1, col, visited, str, pathLength+1)|| hasPathCore(matrix, rows, cols, row+1, col, visited, str, pathLength+1)|| hasPathCore(matrix, rows, cols, row, col-1, visited, str, pathLength+1)|| hasPathCore(matrix, rows, cols, row, col+1, visited, str, pathLength+1) ){ return true; } // 到此说明不存在路径 visited[row][col]=false; return false; } public static void main(String[] args) { char[][] matrix={{'a','b','t','g'},{'c','f','c','s'},{'j','d','e','h'}}; char[] str={'a','b','f','b'}; Interview12 interview12=new Interview12(); boolean has_path=interview12.hasPath(matrix, str); System.out.println(has_path); } }
package com.devjam.training.cicourse.service; import static org.junit.Assert.*; import org.junit.Test; public class CalculateTaxTest { @Test public void noTaxInMinnessota() { //fail("Not yet implemented"); } @Test public void noTaxForSchools() { //fail("Not yet implemented"); } @Test public void fivePercentTaxInUtah() { //fail("Not yet implemented"); } @Test public void decimalPercentTaxIllinois() { //fail("Not yet implemented"); } }
package com.example.wristband.activities; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.wristband.R; import com.example.wristband.bean.ResponseInfo; import com.example.wristband.utils.Constans; import com.google.gson.Gson; import com.roger.catloadinglibrary.CatLoadingView; import com.squareup.okhttp.Request; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; public class RegistActivity extends AppCompatActivity { private EditText phone; private EditText name; private EditText pass; private Button regist; private String u_phone; private String username; private String password; private CatLoadingView mCatLoading; private Handler registHandler = new Handler(){ @Override public void handleMessage(Message msg) { if (msg.what == 1){ mCatLoading.dismiss(); Gson gson = new Gson(); ResponseInfo responseInfo = gson.fromJson(msg.obj.toString(),ResponseInfo.class); if (responseInfo.getCode() == 1){ Toast.makeText(RegistActivity.this,"注册成功",Toast.LENGTH_SHORT).show(); finish(); }else{ Toast.makeText(RegistActivity.this,"注册失败,因为"+responseInfo.getContent(),Toast.LENGTH_SHORT).show(); } } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_regist); mCatLoading = new CatLoadingView(); //表单项 phone = findViewById(R.id.r_user_phone); name = findViewById(R.id.r_user_name); pass = findViewById(R.id.r_user_password); //按钮 regist = findViewById(R.id.r_regist); regist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mCatLoading.show(getSupportFragmentManager(),"正在注册···"); u_phone = phone.getText().toString(); username = name.getText().toString(); password = pass.getText().toString(); //注册 userRegist(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: //点击返回 finish(); break; } return true; } private void userRegist() { final String url = Constans.httpHead + Constans.USER_REGISTER; new Thread(new Runnable() { @Override public void run() { OkHttpUtils .post() .url(url) .addParams("u_phone",u_phone) .addParams("username",username) .addParams("password",password) .build() .connTimeOut(5000) .execute(new StringCallback() { @Override public void onError(Request request, Exception e) { // dialog.dismiss(); mCatLoading.dismiss(); Toast.makeText(RegistActivity.this,"注册失败,加载时间过长",Toast.LENGTH_SHORT).show(); } @Override public void onResponse(String response) { Message message = new Message(); message.what = 1; message.obj = response; registHandler.sendMessage(message); } }); } }).start(); } }
package com.afs.invoiceapi.exceptions; public class EmailNotUniqueException extends BaseException { public EmailNotUniqueException(String key, String... args) { super(key, args); } }
package zystudio.cases.graphics.view; import zystudio.demo.R; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.util.Log; import android.view.View; /** 用于了解android.text.StaticLayout或android.text.DynamicLayout的使用方法 */ //从这个例子看,StaticLayout改一下行距和断行还行,其实就不太行了..我想要的文字间隔根本没有,主要是去分行的 public class CaseStaticLayout { private static CaseStaticLayout sCase; private String mStr=null; private Activity mActivity; public static CaseStaticLayout getInstance(Activity act) { if (sCase == null) { sCase = new CaseStaticLayout(act); } return sCase; } private CaseStaticLayout(Activity activity) { mActivity=activity; mStr=mActivity.getResources().getString(R.string.str_demo); } public void work(){ SampleView view=new SampleView(mActivity); view.setText(mStr); mActivity.setContentView(view); } public static class SampleView extends View{ private String mStr; public SampleView(Context context) { super(context, null); } public void setText(String str){ mStr=str; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); TextPaint tp=new TextPaint(Color.BLACK); tp.setTextSize(50); StaticLayout sl=new StaticLayout(mStr,tp,1080,Layout.Alignment.ALIGN_NORMAL,2.0f,20.0f,true); Log.i("ZYStudio", "Canvas:"+canvas.getClass().getName()); sl.draw(canvas); } } }
package pl.cwanix.opensun.authserver.communication; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import pl.cwanix.opensun.authserver.properties.AuthServerProperties; @Service @RequiredArgsConstructor public class DatabaseProxyConnector { private final RestTemplate restTemplate; private final AuthServerProperties properties; public int startAgentServerSession(final String userName) { return restTemplate.postForObject(properties.getAgent().getServerUrl() + "/session/new?userName=" + userName, null, Integer.class); } }
package com.sporsimdi.action.facade; import java.util.List; import java.util.Map; import org.primefaces.model.SortOrder; import com.sporsimdi.model.entity.Kullanici; import com.sporsimdi.model.type.Status; public interface KullaniciFacade { public Kullanici findById(long id); public Kullanici findByKullanici(String kullanici); public List<Kullanici> getAll(); public void persist(Kullanici kullanici); public List<Kullanici> getByStatus(Status status); public void remove(long id); public Long getCount(); public List<Kullanici> listKullanici(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters); }
package com.wipe.zc.journey.domain; import java.util.List; /** * 行程详细对象 */ public class JourneyDetail { private String contnent; private List<String> list_url; public String getContnent() { return contnent; } public void setContnent(String contnent) { this.contnent = contnent; } public List<String> getList_url() { return list_url; } public void setList_url(List<String> list_url) { this.list_url = list_url; } }
package cn.ck.controller.studio; import cn.ck.controller.AbstractController; import cn.ck.entity.*; import cn.ck.entity.bean.JobUsers; import cn.ck.mapper.UsersMapper; import cn.ck.service.*; import cn.ck.utils.ResponseBo; import com.baomidou.mybatisplus.mapper.EntityWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.util.*; /** * @author 马圳彬 * @version 1.0 * @description 创客 * @date 2018/9/26 16:01 **/ @Controller @RequestMapping("/studio") public class studioController extends AbstractController { @Autowired private StudioService studioService; @Autowired private UsersService usersService; @Autowired private JobsService jobsService; @Autowired private PromulgatorService promulgatorService; @Autowired private JobuserService jobuserService; @Autowired private ProjectService projectService; @RequestMapping("/studioNone") public String test1(){ Users u = usersService.selectById(getUser().getAllId()); System.out.println(getUser().getAllId()); if(u.getUserStudio() == null) return "studio/studio_creat"; else return "studio/studio_index"; } /* @GetMapping("/studioList") @ResponseBody public Studio slist(){ String zzid = getUser().getAllId(); Studio stu = studioService.selectOne(new EntityWrapper<Studio>().eq("stu_creatid",zzid)); System.out.println(stu); System.out.println(getUser().getAllId()); return stu; }*/ @GetMapping("/indexList") @ResponseBody public ResponseBo mList(){ /*Studio stu = studioService.selectByzzid(getUser().getAllId());*/ /*工作室信息*/ String zzid = getUser().getAllId(); Studio stu = studioService.selectOne(new EntityWrapper<Studio>().eq("stu_creatid",zzid)); /*项目信息*/ String stuid = stu.getStuId(); List<Project> stuPro = projectService.selectList(new EntityWrapper<Project>().eq("proj_studio",stuid).eq("proj_state","开发完成")); /*成员信息*/ /*String stuid = "cf20d9f3c7554dfdaa9a45a41494f2c4";*/ List<Users> userList = usersService.selectList(new EntityWrapper<Users>().eq("user_studio",stuid)); List<JobUsers> ju = new ArrayList<JobUsers>(); for(Users u:userList){ Jobuser jobuser = jobuserService.selectByUserId(u.getUserId()); Jobs jobs = jobsService.selectByJuId(jobuser.getJuJobs()); JobUsers ju1 = new JobUsers(); ju1.setJobs(jobs); ju1.setUsers(u); ju.add(ju1); } ResponseBo map = new ResponseBo(); map.put("studio",stu); map.put("project",stuPro); map.put("member",ju); return map; } @RequestMapping("/studioAdd") public void add(HttpServletRequest req, Studio studio){ String yhid = getUser().getAllId(); String stuId = studioService.insertStudio(studio,yhid); usersService.updateStuid(yhid,stuId); } }
package com.mygdx.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; /** * Created by David on 31/05/2017. */ public class SoundStation { private static Music clip = Gdx.audio.newMusic(Gdx.files.internal("Assets/Sounds/Vapor/1.mp3")); static void menuPlay() { if (Options.isSound()){ clip = Gdx.audio.newMusic(Gdx.files.internal("Assets/Sounds/menu.mp3")); clip.play();} } static void gamePlay() { if (Options.isSound()) { if (Options.isVaporwave()) clip = Gdx.audio.newMusic(Gdx.files.internal("Assets/Sounds/Vapor/" + (int) (Math.random() * 12 + 1) + ".mp3")); else clip = Gdx.audio.newMusic(Gdx.files.internal("Assets/Sounds/Tech/" + (int)(Math.random()* 4 + 1) + ".mp3")); clip.play(); } } static void stop() { clip.stop(); } static boolean isPlaying() { return clip.isPlaying(); } }
/** * This DefinedStack class implements a “DefinedStack” * which implements a custom stack class * @author maneeshavenigalla maneesha24@vt.edu * @version 1.0 */ public class DefinedStack { /** * contains value of the size of stack */ private static int stacksize = 0; /** * contains value of the the initial node */ private static Node initialNode; /** * @param data value to be added * takes the value as the input to be pushed to the stack */ public static void push(String data) { Node newNode = new Node(data); newNode.setNextNode(initialNode); initialNode = newNode; stacksize++; } /** * removes the value from the stack and returns the removed value * @return the removed value from the stack */ public static String pop() { Node topNode = initialNode; initialNode = initialNode.getNextNode(); stacksize--; return topNode.getValue(); } /** * calculates the size of stack * @return the size of stacksize */ public static int getStackSize() { return stacksize; } /** * empties the stack */ public static void emptyStack() { for (int i = 0; i < stacksize; i++) { pop(); } } }
package com.heycodestudio.auxeva.heylisten_v2.Utils; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Auxeva on 21/07/2015. */ public class DBAdapter { private DBHelper dbHelper; private SQLiteDatabase sqlDB; private final static int DB_VERSION=1; private final static String DB_NAME="AdminSoft"; private CancionAdapter cancion; public DBAdapter(Context context) { dbHelper = new DBHelper(context); } //Abre la conexion con la base de datos public void open() { sqlDB = dbHelper.getWritableDatabase(); cancion = new CancionAdapter(sqlDB); } //Cierra la conexion con la base de datos. public void close() { sqlDB.close(); } public boolean cancionIsEmpty() { return cancion.isEmpty(); } public boolean cancionInsert(int idMusica,String nombre,String curiosidad,int duracion, int puntaje,String respuesta) { return cancion.insert(idMusica,nombre,curiosidad,duracion,puntaje,respuesta); } public Cursor getDatosCancion() { return cancion.getDatos(); } public boolean borraCancion(String nombre) { return cancion.delete(nombre); } private class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context) { super(context,DB_NAME,null,DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CancionAdapter.CR_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exists " + CancionAdapter.CR_TABLE); onCreate(db); } } }
package died.guia06; public class App { public static void main(String[] args) { //INSCRIPCION CORRECTA Alumno a1 = new Alumno("Yamil", 1); Alumno a2 = new Alumno("Arturo", 2); Curso c1 = new Curso(1, "DIED", 2020, 2, 5, 0); try { c1.inscribirAlumno(a1); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } try { c1.inscribirAlumno(a2); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } c1.imprimirInscriptosPorNombre(); System.out.println(); c1.imprimirInscriptosPorNroLibreta(); System.out.println(); c1.imprimirInscriptosPorCantCreditos(); System.out.println(); a1.aprobar(c1); System.out.println("Los creditos de "+a1.getNombre()+" son: "+a1.creditosObtenidos()); System.out.println("Los creditos de "+a2.getNombre()+" son: "+a2.creditosObtenidos()); //CUPO CUBIERTO // Alumno a3 = new Alumno("Rafart", 3); // try { // c1.inscribirAlumno(a3); // } catch (Exception e) { // e.printStackTrace(); // System.out.println(e.getMessage()); // } //CREDITOS INSUFICIENTES // Curso c2 = new Curso(2, "JAVA", 2020, 2, 5, 1); // try { // c2.inscribirAlumno(a3); // } catch (Exception e) { // e.printStackTrace(); // System.out.println(e.getMessage()); // } //YA INSCRIPTO A 3 CURSOS EN ESTE CICLO LECTIVO // Curso c3 = new Curso(3, "C++", 2020, 2, 5, 0); // Curso c4 = new Curso(4, "PYTHON", 2020, 2, 5, 0); // Curso c5 = new Curso(5, "C", 2020, 2, 5, 0); // try { // c1.inscribirAlumno(a3); // } catch (Exception e) { // e.printStackTrace(); // System.out.println(e.getMessage()); // }try { // c3.inscribirAlumno(a3); // } catch (Exception e) { // e.printStackTrace(); // System.out.println(e.getMessage()); // } // try { // c4.inscribirAlumno(a3); // } catch (Exception e) { // e.printStackTrace(); // System.out.println(e.getMessage()); // } // try { // c5.inscribirAlumno(a3); // } catch (Exception e) { // e.printStackTrace(); // System.out.println(e.getMessage()); // } } }
package com.ccxia.cbcraft.item; import com.ccxia.cbcraft.CbCraft; import com.ccxia.cbcraft.creativetab.CreativeTabsCbCraft; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; public class ItemCocoaBread extends ItemFood { public ItemCocoaBread() { super(7, 0.572F, false); this.setUnlocalizedName(CbCraft.MODID + ".cocoaBread"); this.setRegistryName("cocoa_bread"); this.setCreativeTab(CreativeTabsCbCraft.tabCbCraft); } }
package com.example.hara.wkflsrhqlv11.Page1; import android.content.Context; 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.TextView; import com.example.hara.wkflsrhqlv11.DBConnect.DB_Background_get_Task; import com.example.hara.wkflsrhqlv11.DBConnect.Goal; import com.example.hara.wkflsrhqlv11.R; import java.util.ArrayList; import java.util.List; public class Page1_today_list_Adapter extends RecyclerView.Adapter<Page1_today_list_Adapter.ViewHolder> { private ArrayList<String> name, place, price; private Context mcontext; private ViewHolder holder; private int position, flag=0; public Page1_today_list_Adapter(List<String> myDataset, Context context) { name = new ArrayList<String>(); place = new ArrayList<String>(); price = new ArrayList<String>(); for(int i=0; i<myDataset.size(); i++){ String[] data = myDataset.get(i).split(":"); Log.i("ddd","data[0]-"+data[0]+" : data[1]-"+data[1]+" : data[0]-"+data[2]); name.add(data[0]); place.add(data[1]); price.add(data[2]); } mcontext = context; } public static class ViewHolder extends RecyclerView.ViewHolder { public TextView page1_list_tvcardname, page1_list_tvplace, page1_list_tvprice; public ViewHolder(View view) { super(view); page1_list_tvcardname = (TextView)view.findViewById(R.id.page1_list_tvcardname); page1_list_tvplace = (TextView)view.findViewById(R.id.page1_list_tvplace); page1_list_tvprice = (TextView)view.findViewById(R.id.page1_list_tvprice); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.page1_today_list_adapter, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(final ViewHolder holder, int position) { this.holder = holder; this.position = position; if(name.get(position).equals("cash")){ holder.page1_list_tvcardname.setText("현금"); }else { holder.page1_list_tvcardname.setText("카드("+name.get(position)+")"); } holder.page1_list_tvplace.setText(place.get(position)); holder.page1_list_tvprice.setText(price.get(position)); } @Override public int getItemCount() { return name.size(); } }
package com.lanthaps.identime.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.lanthaps.identime.model.LocalAuthority; import com.lanthaps.identime.model.LocalUser; @Repository public interface LocalAuthorityRepository extends CrudRepository<LocalAuthority, Integer> { List<LocalAuthority> findByLocalUser(LocalUser user); }
package com.navin.melalwallet.ui.main.adapter; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import com.navin.melalwallet.ui.main.fragment.CategoryFragment; import com.navin.melalwallet.ui.main.fragment.home.HomeFragment; import com.navin.melalwallet.ui.main.fragment.SettingFragment; import java.util.ArrayList; import java.util.List; public class TabsAdapter extends FragmentStatePagerAdapter { // List<Fragment> fragmentList; List<String> stringList; public TabsAdapter(@NonNull FragmentManager fm, List<Fragment> fragments) { super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); fragmentList = fragments; } public TabsAdapter(@NonNull FragmentManager fm, List<Fragment> fragments, List<String> titlesList) { super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); fragmentList = fragments; stringList = titlesList; } @NonNull @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return stringList.get(position); } }
package programmers; public class GcdPlus { public static void main(String[] args) { System.out.println(solution(13, 17)); } public static int solution(int left, int right) { int answer = 0; for (int i = left; i<=right; i++){ int count = 0; for(int j =1; j<=i; j++){ if(i%j == 0){ count++; } } if(count%2==0){ answer+=i; } else if(count%2!=0){ answer-=i; } } return answer; } }
package com.example.cryptoportfolio; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; // Allows us to interact with the cards to change data (e.g. change text on example_item) public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> { private ArrayList<ExampleItem> mExampleList; private ExampleAdapter.ExampleAdapterListener listener; public static class ExampleViewHolder extends RecyclerView.ViewHolder { public ImageView mImageView; public TextView mTextView1; public TextView mTextView2; public ExampleViewHolder(View itemView) { super(itemView); // get value references mImageView = itemView.findViewById(R.id.imageView); mTextView1 = itemView.findViewById(R.id.textView); mTextView2 = itemView.findViewById(R.id.textView2); } } // constructor gets us values from the array to bind to the cards public ExampleAdapter(ArrayList<ExampleItem> exampleList) { mExampleList = exampleList; } @Override public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false); ExampleViewHolder evh = new ExampleViewHolder(v); // so need to implement in main activity try { listener = (ExampleAdapter.ExampleAdapterListener) v.getContext(); } catch (ClassCastException e) { throw new ClassCastException((v.getContext().toString() + "must implement ExampleDialogListener")); } return evh; } // binds new data to the references, i.e. sets the recyclerview data @Override public void onBindViewHolder(ExampleAdapter.ExampleViewHolder holder, int position) { ExampleItem currentItem = mExampleList.get(position); holder.mImageView.setImageResource(currentItem.getImageResource()); holder.mTextView1.setText(currentItem.getText1()); holder.mTextView2.setText(currentItem.getText2()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // open dialog to remove // Build an AlertDialog AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); // Set a title for alert dialog builder.setTitle("Select your answer."); // Ask the final question builder.setMessage("Are you sure to delete " + currentItem.getText1() + "?"); // Set the alert dialog yes button click listener builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // delete listener.removeCrypto(position); } }); // Set the alert dialog no button click listener builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do something when No button clicked // Toast.makeText(v.getContext(), // "No Button Clicked", Toast.LENGTH_SHORT).show(); } }); AlertDialog dialog = builder.create(); // Display the alert dialog on interface dialog.show(); } }); } public interface ExampleAdapterListener { void removeCrypto(int position); } @Override public int getItemCount() { return mExampleList.size(); } }
package com.blackdragon2447.AAM.gui.dialog; import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import org.aeonbits.owner.ConfigFactory; import com.blackdragon2447.AAM.Reference; import com.blackdragon2447.AAM.gui.AAMGui; import com.blackdragon2447.AAM.util.iface.AAMConfig; import java.awt.GridBagLayout; import javax.swing.JLabel; import java.awt.GridBagConstraints; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.WindowConstants; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileOutputStream; import java.io.IOException; /** * no documetnaion cause depricated * @author Blackdragon2447 * */ @Deprecated public class CustomPFDialog extends JDialog { /** * */ private static final long serialVersionUID = -2635977732325130032L; private final JPanel ContentPanel = new JPanel(); private JTextField TextField; AAMConfig cfg = ConfigFactory.create(AAMConfig.class); public static void createDialog() { try { CustomPFDialog dialog = new CustomPFDialog(); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Create the dialog. */ public CustomPFDialog() { try { UIManager.setLookAndFeel(AAMGui.getLookAndFeel()); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } setBounds(100, 100, 450, 165); getContentPane().setLayout(new BorderLayout()); ContentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(ContentPanel, BorderLayout.CENTER); GridBagLayout gbl_contentPanel = new GridBagLayout(); gbl_contentPanel.columnWidths = new int[]{40, 0, 40, 0}; gbl_contentPanel.rowHeights = new int[]{0, 0, 0, 0}; gbl_contentPanel.columnWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE}; gbl_contentPanel.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE}; ContentPanel.setLayout(gbl_contentPanel); { JLabel lblNewLabel = new JLabel("New Custom Prefix"); GridBagConstraints gbc_lblNewLabel = new GridBagConstraints(); gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5); gbc_lblNewLabel.gridx = 1; gbc_lblNewLabel.gridy = 1; ContentPanel.add(lblNewLabel, gbc_lblNewLabel); } { TextField = new JTextField(); GridBagConstraints gbc_textField = new GridBagConstraints(); gbc_textField.insets = new Insets(0, 0, 0, 5); gbc_textField.fill = GridBagConstraints.HORIZONTAL; gbc_textField.gridx = 1; gbc_textField.gridy = 2; ContentPanel.add(TextField, gbc_textField); TextField.setColumns(10); } { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Reference.CustomPrefix = TextField.getText(); dispose(); cfg.setProperty("customPrefix", TextField.getText()); try { cfg.store(new FileOutputStream("AAMConfig.properties"), "no comments"); } catch (IOException e1) { e1.printStackTrace(); } } }); } { JButton cancelButton = new JButton("Cancel"); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { dispose(); } }); } } } }
package enstabretagne.BE.AnalyseSousMarine.SimEntity.Bateau; import enstabretagne.BE.AnalyseSousMarine.SimEntity.MouvementSequenceur.EntityMouvementSequenceurInit; import enstabretagne.simulation.components.data.SimInitParameters; public class EntityBateauInit extends SimInitParameters { private EntityMouvementSequenceurInit mvtSeqIni; private String name; public EntityBateauInit(String nom,EntityMouvementSequenceurInit mvtSeqIni) { this.mvtSeqIni = mvtSeqIni; this.name = nom; } public String getName() { return name; } public EntityMouvementSequenceurInit getMvtSeqInitial() { return mvtSeqIni; } }
package com.bookerapp.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.bookerapp.model.Image; @Repository public interface ImageRepository extends CrudRepository<Image, Integer>{ }
package oicq.wlogin_sdk.request; public final class f extends d { public f(i iVar) { this.vIl = 2064; this.vIm = 10; this.vIo = iVar; } }
/** * Copyright 2012 Ashish Kalbhor (ashish.kalbhor@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.ashish.BirthdayWishes; import android.content.Context; import android.os.Vibrator; import android.telephony.SmsManager; import android.widget.Toast; /** * SMS Action Class. The life cycle methods are explained as follows * <ul> * <li>onCreate - Called once when creating an instance of this action. Application Context is passed here</li> * <li>perform - Called each time when an action needs to be performed</li> * <li>onDestroy - Called once when this action needs to be destroyed. Clean up needs to be done here</li> * </ul> * * @author Ashish Kalbhor <ashish.kalbhor@gmail.com> * */ public class SmsAction { /** * Android Application Context */ private Context context = null; /** * SmsManager to Send an SMS from device */ SmsManager smsmgr = null; /** * Vibrator Service to Vibrate the device */ Vibrator vibe = null; /** * Called once when creating an instance of this action. * * @param context Android Application Context */ public void onCreate(Context context) { this.context = context; this.smsmgr = SmsManager.getDefault(); this.vibe = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE); } /** * Called each time when an action needs to be performed * * @param cName : Contact Name * @param cNumber : Contact Number */ public void perform(String cName, String cNumber) { Toast.makeText(this.context, "SMS Wishes Sent to " + cNumber + "..!!", Toast.LENGTH_SHORT).show(); this.smsmgr.sendTextMessage(cNumber, null, "Hey " + cName + " !! Many Many Happy returns of the Day ! :) ", null, null); // SMS sent to contact number passed as Argument this.vibe.vibrate(1000); } /** * Called once when this action needs to be destroyed. Clean up needs to be done here */ public void onDestroy() { this.smsmgr = null; } }
package com.santander.bi.services; import java.util.List; import com.santander.bi.dtos.ListaDistribucionDTO; public interface ListaDistribucionService { public ListaDistribucionDTO create(ListaDistribucionDTO user); public ListaDistribucionDTO delete(int id); public List<ListaDistribucionDTO> findAll(); public ListaDistribucionDTO findById(int id); public ListaDistribucionDTO update(ListaDistribucionDTO user); public List<ListaDistribucionDTO> findAllByPatron(String patron); }
package com.example.onlineshop.repository; import com.example.onlineshop.model.CategoriesItem; import java.util.ArrayList; import java.util.List; public class CategoryRepository { private static CategoryRepository instance; private List<CategoriesItem> mCategoriesList; private List<CategoriesItem> mSubCategoriesList; public CategoriesItem getCategory(long categoryId) { for (CategoriesItem category : mCategoriesList) { if (category.getId() == categoryId) return category; } return null; } public int getCurrentCategory(long id) { for (int i = 0; i < mSubCategoriesList.size(); i++) { if (mSubCategoriesList.get(i).getId() == id) return i; } return -1; } private void generateParentList() { for (CategoriesItem category : mCategoriesList) { if (category.getId() == 0) mSubCategoriesList.add(category); } } public List<CategoriesItem> getSubCategoires(long parentId) { List<CategoriesItem> result = new ArrayList<>(); for (CategoriesItem category : mCategoriesList) { if (category.getId() == parentId) result.add(category); } return result; } public List<CategoriesItem> getCategoriesList() { return mCategoriesList; } public void setCategoriesList(List<CategoriesItem> categoriesList) { mCategoriesList.clear(); mSubCategoriesList.clear(); mCategoriesList = categoriesList; generateParentList(); } public List<CategoriesItem> getSubCategoriesList() { return mSubCategoriesList; } public void setSubCategoriesList(List<CategoriesItem> subCategoriesList) { mSubCategoriesList = subCategoriesList; } private CategoryRepository() { mCategoriesList = new ArrayList<>(); mSubCategoriesList = new ArrayList<>(); } public static CategoryRepository getInstance(){ if(instance == null){ instance = new CategoryRepository(); } return instance; } }
package com.example.deepakrattan.fragmentdemo; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button btnReplaceFragment; FragmentManager fragmentManager; FragmentTransaction fragmentTransaction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnReplaceFragment = (Button) findViewById(R.id.replaceFragment); //Adding fragment three FragmentThree fragmentThree = new FragmentThree(); fragmentManager = getSupportFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.fragmentContainer, fragmentThree); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); btnReplaceFragment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FragmentFour fragmentFour = new FragmentFour(); fragmentManager = getSupportFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragmentContainer, fragmentFour); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }); } }
package me.oscardoras.pistonsoverhaul.movingblock; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.FallingBlock; import org.bukkit.util.Vector; import me.oscardoras.pistonsoverhaul.Rotation; public class TurningMovingBlock extends MovingBlock { protected final Rotation rotation; protected final Block axis; protected final double distance; protected final Vector height; protected final double arc; protected final double a; public TurningMovingBlock(FallingBlock fallingBlock, Block from, Rotation rotation, Block axis, double time) { super(fallingBlock, from, getTo(from, rotation, axis)); this.rotation = rotation; this.axis = axis; Location fromLocation = from.getLocation(); this.distance = rotation.getDistance(axis, fromLocation); this.height = rotation.getHeight(axis, fromLocation); Vector vec = from.getLocation().subtract(axis.getLocation()).toVector().multiply(1d/distance); this.arc = distance >= 0.5d ? rotation.getArc(vec) : 0d; this.a = (rotation.isRight() ? 1 : -1) * (Math.PI/2)/time; } @Override public Location getTarget(int tick) { return axis.getLocation() .add(new Vector(rotation.getModX(arc + a*tick), rotation.getModY(arc + a*tick), rotation.getModZ(arc + a*tick)).multiply(distance)) .add(height); } protected static Block getTo(Block from, Rotation rotation, Block axis) { Location fromLocation = from.getLocation(); double distance = rotation.getDistance(axis, fromLocation); if (distance < 0.5d) return from; Vector vec = from.getLocation().subtract(axis.getLocation()).toVector().multiply(1d/distance); double arc = rotation.getArc(vec); arc += (rotation.isRight() ? 1 : -1) * Math.PI/2; return axis.getLocation() .add(new Vector(rotation.getModX(arc), rotation.getModY(arc), rotation.getModZ(arc)).multiply(distance)) .add(rotation.getHeight(axis, fromLocation)) .getBlock(); } }
package top.skyzc.juke.activity; import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import androidx.appcompat.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.Random; import cn.bmob.v3.BmobSMS; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.QueryListener; import cn.bmob.v3.listener.SaveListener; import top.skyzc.juke.R; import top.skyzc.juke.model.User; import top.skyzc.juke.util.BaseActivity; import top.skyzc.juke.util.CheckPhoneNumber; import top.skyzc.juke.util.CountDownTimerUtils; import top.skyzc.juke.util.MyUtil; public class RegisterActivity extends BaseActivity { private static final String TAG = "RegisterActivity"; private EditText edit_username, edit_phoneNumber, edit_verCode, edit_password, edit_repassword; private Button btn_getVerCode, btn_goRegister; private String phoneNumber, verCode, name, password, rePassword; private CountDownTimerUtils countDownTimer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); goBack(); initView(); } private void initView() { edit_username = (EditText) findViewById(R.id.edit_username); edit_phoneNumber = (EditText) findViewById(R.id.edit_phoneNumber); edit_verCode = (EditText) findViewById(R.id.edit_yanzhengma); edit_password = (EditText) findViewById(R.id.edit_password); edit_repassword = (EditText) findViewById(R.id.edit_repassword); btn_getVerCode = (Button) findViewById(R.id.btn_getYanzhengma); btn_goRegister = (Button) findViewById(R.id.btn_goRegister); //发送验证码 btn_getVerCode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { phoneNumber = edit_phoneNumber.getText().toString(); // 判定手机号 if (CheckPhoneNumber.isPhoneNumber(phoneNumber)) { Log.d(TAG, "手机验证码发送中。。。。"); sendBmobSms(phoneNumber); Log.d(TAG, "手机验证码发送完毕"); // 发送成功进入倒计时 countDownTimer = new CountDownTimerUtils(btn_getVerCode, 60000, 1000); countDownTimer.start(); } else { MyUtil.showToast(RegisterActivity.this, "手机号码有误!"); } } }); btn_goRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { phoneNumber = edit_phoneNumber.getText().toString(); verCode = edit_verCode.getText().toString(); name = edit_username.getText().toString(); password = edit_password.getText().toString(); rePassword = edit_repassword.getText().toString(); if (password.equals(rePassword)) { signOrLogin(phoneNumber, verCode, name, password); } else { MyUtil.showToast(RegisterActivity.this, "密码格式有误!请检查:两次密码必须一样且大于6位"); } } }); } public void goBack() { Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle("注册账号"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标 getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用 toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } /* * 检查手机号是否合法 */ // private boolean checkPhoneNumber(String phoneNumber) { // if (phoneNumber.matches(CheckPhoneNumber.REGEX_MOBILE)) { // return true; // } else { // return false; // } // } /* * Bmob发送短信接口 * */ public void sendBmobSms(String phoneNumber) { /** * TODO template 如果是自定义短信模板,此处替换为你在控制台设置的自定义短信模板名称;如果没有对应的自定义短信模板,则使用默认短信模板。 */ BmobSMS.requestSMSCode(phoneNumber, "JukeSMS", new QueryListener<Integer>() { @Override public void done(Integer smsId, BmobException e) { if (e == null) { MyUtil.showToast(RegisterActivity.this, "发送验证码成功"); Log.d(TAG, "发送验证码成功,短信ID:" + smsId + "\n"); } else { MyUtil.showToast(RegisterActivity.this, "发送验证码失败:" + e.getErrorCode() + "-" + e.getMessage() + "\n"); Log.d(TAG, "发送验证码失败:" + e.getErrorCode() + "-" + e.getMessage() + "\n"); } } }); } /** * 一键注册或登录的同时保存其他字段的数据 * * @param phone * @param code */ private void signOrLogin(String phone, String code, String name, String password) { User user = new User(); //设置手机号码(必填) user.setMobilePhoneNumber(phone); //设置用户名,如果没有传用户名,则默认为手机号码 user.setUsername(name); //设置用户密码 user.setPassword(password); user.setMobilePhoneNumberVerified(true); user.setLevel(0); user.setInvID("ck"+ getRandom()); user.signOrLogin(code, new SaveListener<User>() { @Override public void done(User user, BmobException e) { if (e == null) { MyUtil.showToast(RegisterActivity.this, "注册成功:" + user.getUsername()); startActivity(new Intent(RegisterActivity.this, MainActivity.class)); finish(); } else { MyUtil.showToast(RegisterActivity.this, "注册失败:" + e.getErrorCode() + "-" + e.getMessage() + "\n"); } } }); } /* * 6位随机数 * */ public String getRandom(){ String sources = "0123456789"; // 加上一些字母,就可以生成pc站的验证码了 Random rand = new Random(); StringBuffer flag = new StringBuffer(); for (int j = 0; j < 6; j++) { flag.append(sources.charAt(rand.nextInt(9)) + ""); } System.out.println(flag.toString()); return flag.toString(); } }
package com.fleet.neo4j.repository; import com.fleet.neo4j.entity.Student; import org.springframework.data.neo4j.annotation.Depth; import org.springframework.data.repository.CrudRepository; import java.util.Optional; /** * 学生节点 Repository */ public interface StudentRepository extends CrudRepository<Student, Long> { Student findByName(String name); Optional<Student> findByName(String name, @Depth int depth); }
package com.设计模式.单例模式; /** * 复杂单例模式,双层检测,可以多线程、懒加载,无法防止反射构建 * @author wicks * */ public class ComplexSingleton { private ComplexSingleton() {} //私有构造函数 private volatile static ComplexSingleton instance = null; //单例对象,volatile防止指令重排 //静态工厂方法 public static ComplexSingleton getInstance() { if (instance == null) { // 双重检测机制 synchronized (ComplexSingleton.class) { // 同步锁 if (instance == null) { // 双重检测机制 instance = new ComplexSingleton(); } } } return instance; } }
package com.ssgmail.shubhammsoni.materialapp; public class Question { private String question; private Integer code; private String key; private Integer countAgree; private Integer countDisagree; ////////////////////////////////////////////// Question() { } Question(int code, String question, String key, Integer countAgree, Integer countDisagree) { this.code = code; this.question = question; this.key = key; this.countAgree = countAgree; this.countDisagree = countDisagree; } public Integer getCountAgree() { return countAgree; } public String getQuestion() { return question; } public Integer getCode() { return code; } public String getKey() { return key; } public Integer getCountDisagree() { return countDisagree; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package forms; import company.Tools; /** * * @author Wafaa */ public class formReports extends javax.swing.JFrame { /** * Creates new form formReports */ public formReports() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); btnBack = new controls.JMyButton(); btnDept = new controls.JMyButton(); btnEmpReport = new controls.JMyButton(); btnPhones = new controls.JMyButton(); btnProject = new controls.JMyButton(); btnWorkOn = new controls.JMyButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 20)); // NOI18N jLabel1.setText("Main Reports"); btnBack.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnBack.setText("Back"); btnBack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBackActionPerformed(evt); } }); btnDept.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnDept.setText("Department Report"); btnDept.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeptActionPerformed(evt); } }); btnEmpReport.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnEmpReport.setText("Employee Report"); btnEmpReport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEmpReportActionPerformed(evt); } }); btnPhones.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnPhones.setText("Phones Report"); btnPhones.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPhonesActionPerformed(evt); } }); btnProject.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnProject.setText("Project Report"); btnProject.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnProjectActionPerformed(evt); } }); btnWorkOn.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnWorkOn.setText("Work On Report"); btnWorkOn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnWorkOnActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(147, 147, 147) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnBack) .addGroup(layout.createSequentialGroup() .addGap(112, 112, 112) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnDept, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnEmpReport, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnPhones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnProject, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnWorkOn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))) .addContainerGap(137, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel1) .addGap(36, 36, 36) .addComponent(btnDept) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnEmpReport) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnPhones) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnProject) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnWorkOn) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE) .addComponent(btnBack) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed // TODO add your handling code here: this.dispose(); Tools.openForm(new frmMain()); }//GEN-LAST:event_btnBackActionPerformed private void btnDeptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeptActionPerformed // TODO add your handling code here: this.dispose(); Tools.openForm(new formReportDept()); }//GEN-LAST:event_btnDeptActionPerformed private void btnEmpReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEmpReportActionPerformed // TODO add your handling code here: this.dispose(); Tools.openForm(new formReportEmp()); }//GEN-LAST:event_btnEmpReportActionPerformed private void btnPhonesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPhonesActionPerformed // TODO add your handling code here: this.dispose(); Tools.openForm(new formReportPhones()); }//GEN-LAST:event_btnPhonesActionPerformed private void btnProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProjectActionPerformed // TODO add your handling code here: this.dispose(); Tools.openForm(new formReportProject()); }//GEN-LAST:event_btnProjectActionPerformed private void btnWorkOnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnWorkOnActionPerformed // TODO add your handling code here: this.dispose(); Tools.openForm(new formReportWorkOn()); }//GEN-LAST:event_btnWorkOnActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(formReports.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(formReports.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(formReports.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(formReports.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new formReports().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnBack; private javax.swing.JButton btnDept; private javax.swing.JButton btnEmpReport; private javax.swing.JButton btnPhones; private javax.swing.JButton btnProject; private javax.swing.JButton btnWorkOn; private javax.swing.JLabel jLabel1; // End of variables declaration//GEN-END:variables }
package com.tencent.mm.pluginsdk.ui.tools; import android.graphics.Bitmap; import android.util.SparseArray; import com.tencent.mm.pluginsdk.ui.tools.g.c; import com.tencent.mm.sdk.platformtools.x; class g$5 implements Runnable { final /* synthetic */ g qSF; final /* synthetic */ SparseArray qSG; final /* synthetic */ c qSH; g$5(g gVar, SparseArray sparseArray, c cVar) { this.qSF = gVar; this.qSG = sparseArray; this.qSH = cVar; } public final void run() { x.i("MicroMsg.ImageEngine", "begin do recycled"); for (int i = 0; i < this.qSG.size(); i++) { Bitmap bitmap = (Bitmap) this.qSG.valueAt(i); if (bitmap != null) { x.d("MicroMsg.ImageEngine", "recycled def bmp %s", new Object[]{bitmap.toString()}); bitmap.recycle(); } } this.qSG.clear(); x.i("MicroMsg.ImageEngine", "clear drawable cache"); this.qSH.clear(); x.i("MicroMsg.ImageEngine", "end do recycled"); } }
package nowcoder.剑指offer; /** * @Author: Mr.M * @Date: 2019-03-10 11:49 * @Description: 矩阵中的路径 **/ public class T65 { public static boolean hasPath(char[] matrix, int rows, int cols, char[] str) { char[][] m = new char[rows][cols]; int[][] flag; int k = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { m[i][j] = matrix[k++]; } } for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (m[i][j] == str[0]) { flag = new int[rows][cols]; // 需要每次进行初始化,否则上一次标记过的点在下一次仍然处于标记的状态 if (findWorld(m, i, j, str, 0, flag)) { return true; } } } } return false; } private static boolean findWorld(char[][] board, int i, int j, char[] str, int x, int[][] flag) { if (x > str.length - 1) { return true; } if (i >= 0 && i < board.length && j >= 0 && j < board[0].length && x < str.length && flag[i][j] != 1 && board[i][j]==str[x]) { flag[i][j] = 1; x++; return findWorld(board, i + 1, j, str, x, flag) || findWorld(board, i - 1, j, str, x, flag) || findWorld(board, i, j + 1, str, x, flag) || findWorld(board, i, j - 1, str, x, flag); // return findWorld(board, i + 1, j, str, ++x, flag) // || findWorld(board, i - 1, j, str, ++x, flag) // || findWorld(board, i, j + 1, str, ++x, flag) // || findWorld(board, i, j - 1, str, ++x, flag); } return false; } public static void main(String[] args) { char[] chars = "ABCEHJIGSFCSLOPQADEEMNOEADIDEJFMVCEIFGGS".toCharArray(); // char[] re = "bcced".toCharArray(); char[] re = "SGGFIECVAASABCEHJIGQEM".toCharArray(); System.out.println(hasPath(chars, 5, 8, re)); } }
package com.example.demo.config; import com.example.demo.job.FirstJob; import com.example.demo.job.SecondJob; import org.quartz.JobDetail; import org.quartz.Trigger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.CronTriggerFactoryBean; import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean; /** * author:lizhaojie * 创建日期:2019/9/27-13:19 */ @Configuration public class QuartzConfig { //配置定时任务1 @Bean(name = "firstJobDetail") public MethodInvokingJobDetailFactoryBean firstJobDetail(FirstJob firstJob){ MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean(); //并发执行 jobDetail.setConcurrent(true); //为需要执行的实体类对应的对象 jobDetail.setTargetObject(firstJob); //需要执行的方法 jobDetail.setTargetMethod("task"); return jobDetail; } //配置触发器1 @Bean(name = "firstTrigger") public SimpleTriggerFactoryBean firstTrigger(JobDetail firstJobDetail){ SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean(); trigger.setJobDetail(firstJobDetail); // 设置任务启动延迟 trigger.setStartDelay(0); // 每10秒执行一次 trigger.setRepeatInterval(10000); return trigger; } // 配置定时任务2 @Bean(name = "secondJobDetail") public MethodInvokingJobDetailFactoryBean secondJobDetail(SecondJob secondJob) { MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean(); // 是否并发执行,假如设置为10秒一次,如果上一次因为到了时间没有执行那么当前这个任务会并发执行, // 如果为false的话就会等上一次执行完才执行 jobDetail.setConcurrent(true); // 为需要执行的实体类对应的对象 jobDetail.setTargetObject(secondJob); // 需要执行的方法 jobDetail.setTargetMethod("task"); return jobDetail; } // 配置触发器2 @Bean(name = "secondTrigger") public CronTriggerFactoryBean secondTrigger(JobDetail secondJobDetail) { CronTriggerFactoryBean trigger = new CronTriggerFactoryBean(); trigger.setJobDetail(secondJobDetail); // cron表达式,每过10秒执行一次 trigger.setCronExpression("0/10 * * * * ?"); return trigger; } // 配置Scheduler @Bean(name = "scheduler") public SchedulerFactoryBean schedulerFactory(Trigger firstTrigger, Trigger secondTrigger) { SchedulerFactoryBean bean = new SchedulerFactoryBean(); // 延时启动,应用启动5秒后 bean.setStartupDelay(5); // 注册触发器 bean.setTriggers(firstTrigger, secondTrigger); return bean; } }
package com.xcw.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xcw.bean.User; import com.xcw.dao.UserMapper; @Service public class UserService implements IUserService{ @Autowired private UserMapper userMapper; @Override public User getUserById(int id) { User user = userMapper.findUserById(10); return user; } }
/////////////////////////////////////////////////////////////////////////////// // ALL STUDENTS COMPLETE THESE SECTIONS // Title: AppStore // Files: AppStore.java // Semester: (course) Fall 2015 // // Author: Xiaojun He // Email: xhe66@wisc.edu // CS Login: xiaojun // Lecturer's Name: Jim Skrentny /////////////////////////////////////////////////////////////////////////////// import java.time.Instant; import java.util.*; import java.io.File; import java.io.FileNotFoundException; /** * This is the class contains main method, implementing all the command * processing and file reading function. * * @author Xiaojun He * */ public class AppStore { // construct a new appstore database private static AppStoreDB appStoreDB = new AppStoreDB(); private static User appUser = null; private static Scanner scanner = null; /** * main method implement the appstore user interface and initialize the * application * * @param args */ public static void main(String args[]) { if (args.length < 4) { System.err.println("Bad invocation! Correct usage: " + "java AppStore <UserDataFile> <CategoryListFile> " + "<AppDataFile> <AppActivityFile>"); System.exit(1); } boolean didInitialize = initializeFromInputFiles(args[0], args[1], args[2], args[3]); if (!didInitialize) { System.err.println("Failed to initialize the application!"); System.exit(1); } System.out.println("Welcome to the App Store!\n" + "Start by browsing the top free and the top paid apps " + "today on the App Store.\n" + "Login to download or upload your favorite apps.\n"); processUserCommands(); } /** * initialize the database from files, return true if success, otherwise * exit the program * * @param userDataFile * @param categoryListFile * @param appDataFile * @param appActivityFile * @return true if success, otherwise exit the program */ private static boolean initializeFromInputFiles(String userDataFile, String categoryListFile, String appDataFile, String appActivityFile) { try { File userData = new File(userDataFile); File categoryList = new File(categoryListFile); File appData = new File(appDataFile); File appActivity = new File(appActivityFile); readUser(userData, appStoreDB); readCategory(categoryList, appStoreDB); readAppDatas(appData, appStoreDB); readAppActivitys(appActivity, appStoreDB); } catch (FileNotFoundException e) { System.out.println(e); System.out.println("File <Filename> not found"); System.exit(1); } return true; } /** * read user file and create new user object with the information given * * @param userData * : file containing data of users * @param asDB * : the current database object * @throws FileNotFoundException * if the file doesn't exist in directory */ private static void readUser(File userData, AppStoreDB asDB) throws FileNotFoundException { scanner = new Scanner(userData).useDelimiter(",|\n"); while (scanner.hasNext()) { asDB.addUser(scanner.next(), scanner.next(), scanner.next(), scanner.next(), scanner.next(), scanner.next()); } } /** * read category file and create the category list in the databsse * * @param categoryList * : file containing adding categories * @param asDB * : the current database object * @throws FileNotFoundException * if the file doesn't exist in directory */ private static void readCategory(File categoryList, AppStoreDB asDB) throws FileNotFoundException { scanner = new Scanner(categoryList).useDelimiter(",|\n"); while (scanner.hasNext()) { asDB.addCategory(scanner.next()); } } /** * read appData file and store the corresponding information in to database * * * @param appData * : file containing all apps' information * @param asDB * : the current database object * @throws FileNotFoundException * if the file doesn't exist in directory */ private static void readAppDatas(File appData, AppStoreDB asDB) throws FileNotFoundException { scanner = new Scanner(appData).useDelimiter(",|\n"); while (scanner.hasNext()) { // potential problem: what if developer isn't in the database yet User upUser = asDB.findUserByEmail(scanner.next()); asDB.uploadApp(upUser, scanner.next(), scanner.next(), scanner.next(), scanner.nextDouble(), scanner.nextLong()); } } /** * read appActivity file and record related downloading and rating * information in to databse * * @param appActivity * : file containing related app activities * @param asDB * : the current database object * @throws FileNotFoundException * if the file doesn't exist in directory * */ private static void readAppActivitys(File appActivity, AppStoreDB asDB) throws FileNotFoundException { scanner = new Scanner(appActivity).useDelimiter(",|\n"); while (scanner.hasNext()) { if (scanner.next().equals("d")) { String userEmail = scanner.next(); String appid = scanner.next(); asDB.findAppByAppId(appid).download( asDB.findUserByEmail(userEmail)); } else { String userEmail = scanner.next(); String appid = scanner.next(); short rating = scanner.nextShort(); asDB.rateApp(asDB.findUserByEmail(userEmail), asDB.findAppByAppId(appid), rating); } } } private static void processUserCommands() { scanner = new Scanner(System.in); String command = null; do { if (appUser == null) { System.out.print("[anonymous@AppStore]$ "); } else { System.out.print("[" + appUser.getEmail().toLowerCase() + "@AppStore]$ "); } command = scanner.next(); switch (command.toLowerCase()) { case "l": processLoginCommand(); break; case "x": processLogoutCommand(); break; case "s": processSubscribeCommand(); break; case "v": processViewCommand(); break; case "d": processDownloadCommand(); break; case "r": processRateCommand(); break; case "u": processUploadCommand(); break; case "p": processProfileViewCommand(); break; case "q": System.out.println("Quit"); break; default: System.out.println("Unrecognized Command!"); break; } } while (!command.equalsIgnoreCase("q")); scanner.close(); } private static void processLoginCommand() { if (appUser != null) { System.out.println("You are already logged in!"); } else { String email = scanner.next(); String password = scanner.next(); appUser = appStoreDB.loginUser(email, password); if (appUser == null) { System.out.println("Wrong username / password"); } } } private static void processLogoutCommand() { if (appUser == null) { System.out.println("You are already logged out!"); } else { appUser = null; System.out.println("You have been logged out."); } } private static void processSubscribeCommand() { if (appUser == null) { System.out.println("You need to log in " + "to perform this action!"); } else { if (appUser.isDeveloper()) { System.out.println("You are already a developer!"); } else { appUser.subscribeAsDeveloper(); System.out.println("You have been promoted as developer"); } } } private static void processViewCommand() { String restOfLine = scanner.nextLine(); Scanner in = new Scanner(restOfLine); String subCommand = in.next(); int count; String category; switch (subCommand.toLowerCase()) { case "categories": System.out.println("Displaying list of categories..."); List<String> categories = appStoreDB.getCategories(); count = 1; for (String categoryName : categories) { System.out.println(count++ + ". " + categoryName); } break; case "recent": category = null; if (in.hasNext()) { category = in.next(); } displayAppList(appStoreDB.getMostRecentApps(category)); break; case "free": category = null; if (in.hasNext()) { category = in.next(); } displayAppList(appStoreDB.getTopFreeApps(category)); break; case "paid": category = null; if (in.hasNext()) { category = in.next(); } displayAppList(appStoreDB.getTopPaidApps(category)); break; case "app": String appId = in.next(); App app = appStoreDB.findAppByAppId(appId); if (app == null) { System.out.println("No such app found with the given app id!"); } else { displayAppDetails(app); } break; default: System.out.println("Unrecognized Command!"); } in.close(); } private static void processDownloadCommand() { if (appUser == null) { System.out.println("You need to log in " + "to perform this action!"); } else { String appId = scanner.next(); App app = appStoreDB.findAppByAppId(appId); if (app == null) { System.out.println("No such app with the given id exists. " + "Download command failed!"); } else { try { appStoreDB.downloadApp(appUser, app); System.out.println("Downloaded App " + app.getAppName()); } catch (Exception e) { System.out.println("Something went wrong. " + "Download command failed!"); } } } } private static void processRateCommand() { if (appUser == null) { System.out.println("You need to log in " + "to perform this action!"); } else { String appId = scanner.next(); App app = appStoreDB.findAppByAppId(appId); if (app == null) { System.out.println("No such app with the given id exists. " + "Rating command failed!"); } else { try { short rating = scanner.nextShort(); appStoreDB.rateApp(appUser, app, rating); System.out.println("Rated app " + app.getAppName()); } catch (Exception e) { System.out.println("Something went wrong. " + "Rating command failed!"); } } } } private static void processUploadCommand() { if (appUser == null) { System.out.println("You need to log in " + "to perform this action!"); } else { String appName = scanner.next(); String appId = scanner.next(); String category = scanner.next(); double price = scanner.nextDouble(); long uploadTimestamp = Instant.now().toEpochMilli(); try { appStoreDB.uploadApp(appUser, appId, appName, category, price, uploadTimestamp); } catch (Exception e) { System.out.println("Something went wrong. " + "Upload command failed!"); } } } private static void processProfileViewCommand() { String restOfLine = scanner.nextLine(); Scanner in = new Scanner(restOfLine); String email = null; if (in.hasNext()) { email = in.next(); } if (email != null) { displayUserDetails(appStoreDB.findUserByEmail(email)); } else { displayUserDetails(appUser); } in.close(); } private static void displayAppList(List<App> apps) { if (apps.size() == 0) { System.out.println("No apps to display!"); } else { int count = 1; for (App app : apps) { System.out.println(count++ + ". " + "App: " + app.getAppName() + "\t" + "Id: " + app.getAppId() + "\t" + "Developer: " + app.getDeveloper().getEmail()); } } } private static void displayAppDetails(App app) { if (app == null) { System.out.println("App not found!"); } else { System.out.println("App name: " + app.getAppName()); System.out.println("App id: " + app.getAppId()); System.out.println("Category: " + app.getCategory()); System.out.println("Developer Name: " + app.getDeveloper().getFirstName() + " " + app.getDeveloper().getLastName()); System.out.println("Developer Email: " + app.getDeveloper().getEmail()); System.out.println("Total downloads: " + app.getTotalDownloads()); System.out.println("Average Rating: " + app.getAverageRating()); // show revenue from app if the logged-in user is the app developer if (appUser != null && appUser.getEmail().equalsIgnoreCase( app.getDeveloper().getEmail())) { System.out.println("Your Revenue from this app: $" + app.getRevenueForApp()); } } } private static void displayUserDetails(User user) { if (user == null) { System.out.println("User not found!"); } else { System.out.println("User name: " + user.getFirstName() + " " + user.getLastName()); System.out.println("User email: " + user.getEmail()); System.out.println("User country: " + user.getCountry()); // print the list of downloaded apps System.out.println("List of downloaded apps: "); List<App> downloadedApps = user.getAllDownloadedApps(); displayAppList(downloadedApps); // print the list of uploaded app System.out.println("List of uploaded apps: "); List<App> uploadedApps = user.getAllUploadedApps(); displayAppList(uploadedApps); // show the revenue earned, if current user is developer if (appUser != null && user.getEmail().equalsIgnoreCase(appUser.getEmail()) && appUser.isDeveloper()) { double totalRevenue = 0.0; for (App app : uploadedApps) { totalRevenue += app.getRevenueForApp(); } System.out.println("Your total earnings: $" + totalRevenue); } } } }
package com.company; public class Main { public static void main(String[] args) { String s= "tactcoa"; boolean ans1 = PalindromePermutation.canPalindrome(s); System.out.println(ans1); boolean ans2 = PalindromePermutation2.canPalin2(s); System.out.println(ans2); } }
package com.oneteam.graduationproject; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import java.util.HashMap; /** * Created by Mohamed AbdelraZek on 2/17/2017. */ public class UserSession { SharedPreferences zPref; SharedPreferences.Editor zEditor; Context zContext; final int PRIVATE_MODE = 0; private static final String PREF_NAME = "AndroidGProject"; private static final String IS_LOGIN = "IsLoggedIn"; public static final String KEY_NAME = "name"; public static final String KEY_PASSWORD = "password"; public static final String KEY_EMAIL = "email"; public static final String KEY_ID = "id"; public UserSession(Context context) { this.zContext = context; zPref = zContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE); zEditor = zPref.edit(); } public void createLoginSession(String email, String password, String name, String id) { zEditor.putBoolean(IS_LOGIN, true); zEditor.putString(KEY_EMAIL, email); zEditor.putString(KEY_PASSWORD, password); zEditor.putString(KEY_NAME, name); zEditor.putString(KEY_ID, id); zEditor.commit(); } /** * Check login method wil check user login status * If false it will redirect user to login page * Else won't do anything */ public void checkLogin() { // Check login status if (this.isLoggedIn()) { // user is not logged in redirect him to Login Activity zContext.startActivity(new Intent(zContext, HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } } /** * Get stored session data */ public HashMap<String, String> getUserDetails() { HashMap<String, String> user = new HashMap<String, String>(); user.put(KEY_PASSWORD, zPref.getString(KEY_PASSWORD, null)); user.put(KEY_EMAIL, zPref.getString(KEY_EMAIL, null)); user.put(KEY_NAME, zPref.getString(KEY_NAME, null)); user.put(KEY_ID, zPref.getString(KEY_ID, null)); // return user return user; } /** * Clear session details */ public void logout() { zEditor.clear(); zEditor.commit(); zContext.startActivity(new Intent(zContext, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } public boolean isLoggedIn() { return zPref.getBoolean(IS_LOGIN, false); } }
package com.mirth.tools.header.builders; import org.apache.commons.lang.StringUtils; public class NoOpHeaderBuilder extends HeaderBuilder { @Override public String getOpenComment() { return null; } @Override public String getCloseComment() { return null; } @Override public String getBlockComment() { return null; } @Override public String buildHeader(String header) { return StringUtils.EMPTY; } @Override public String removeHeader(String contents) { return contents; } }
/* * Sonar Codesize Plugin * Copyright (C) 2010 Matthijs Galesloot * dev@sonar.codehaus.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sonar.plugins.codesize; import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.commons.configuration.PropertiesConfiguration; import org.junit.Test; import org.sonar.api.resources.Project; public class SizingProfileTest { @Test public void testLineCountMetrics() { Project project = new Project("test"); project.setConfiguration(new PropertiesConfiguration()); SizingProfile profile = new SizingProfile(project.getConfiguration()); int minExpectedMetrics = 5; assertTrue(minExpectedMetrics < profile.getFileSetDefinitions().size()); assertTrue(minExpectedMetrics < profile.getFileSetDefinitions().size()); for (FileSetDefinition metric : profile.getFileSetDefinitions()) { assertNotNull(metric.getName()); assertNotNull(metric.getIncludes()); } } @Test public void profileTest() { PropertiesConfiguration configuration = new PropertiesConfiguration(); configuration.setProperty(CodesizeConstants.SONAR_CODESIZE_PROFILE, "Java\nincludes=*\nexcludes=*"); SizingProfile profile = new SizingProfile(configuration); assertEquals(1, profile.getFileSetDefinitions().size()); assertEquals(1, profile.getFileSetDefinitions().get(0).getIncludes().size()); assertEquals(1, profile.getFileSetDefinitions().get(0).getExcludes().size()); } }
import java.util.Scanner; import java.lang.Math; public class Bros { static Scanner in = new Scanner(System.in); // make convertation of the Arabic symbols into Roman(King the I, Charlie the II, Marcus the IV, X, M, C, and so on. make this inteligently) static int count=0; // the common variables should be static! int age = 144; int id; String ident; String name; boolean dead=false; // true - dead, false - alive double hp = 1; // health points double boostL = 1; public void Aging () {this.age += 10;} public boolean Death(int age, double hp, String name) { if(this.age > 150 | this.hp == 0) // if one of the operands evaluates to true, after comparing BOTH operands returns TRUE { System.out.printf("%s had left this world to do better things elsewhere.\n", name); return this.dead = true; } else return this.dead = false; } public double Damage(double hp, double boostL) { if(boostL <= 0) { boostL = 1; return this.hp -= 1; } else return this.hp; } public double Boost(double boostL) { System.out.println("Do you want to boost?(y/n)"); char cond = in.next().charAt(0); // condition // next() function returns the next token/word in the input as a string and // charAt(0) function returns the first character in that string. if(cond == 'y') { double y; y = Math.sin(Math.PI*(Math.random()/2)); return this.boostL += y; } if(cond == 'n') return this.boostL; else{ System.out.println("You are a strange person.\nThird choise: the one looses boost and 1 hp."); return this.boostL = 0; } } public String getGood(String ident) { if(ident == "Bad") return this.ident = "Good Guy"; else return ident; // | ident == "Villain" } public String junior(String name) { //if an obj with this name already exists, it sets the one's name to "Name jr.(junior)" // can resolve this through array! input there each name of the obj. created and then compare the newly inputed item // if (name == arrName) name += " jr." return name + " jr."; } public void Print(){ System.out.printf("Num: %d. Name: %s. Ident: %s. Age: %d. HP: %f. Boost: %f.\n", this.id, this.name, this.ident, this.age, this.hp, this.boostL); } // default constructor Bros(){ System.out.println("\nThe default constructor was executed."); this.id = Bros.count++; this.name = "Luke"; this.ident = "Bad"; this.ident = getGood(this.ident); Print(); } // Custom constructor Bros(String name, String ident){ System.out.println("\n___________________________________"); System.out.println("The custom constructor was executed."); System.out.println("Give name:"); this.name = in.nextLine(); System.out.println("\nGive identity:"); //ident = in.nextLine(); ident = "Bad"; this.ident = getGood(ident); //this.ident = getGood(in.nextLine()); this.id = Bros.count++; Print(); System.out.println("\n___________________________________"); } static Bros Mary = new Bros(); public static void main(String args[]) { System.out.println("+++++++++++++Tinkering... The MAIN programm has loaded successfully."); System.out.println(); Bros.Mary.getGood(Mary.ident); System.out.printf("%s the %d has became a %s.\n", Mary.name, Mary.id, Mary.ident); Bros bro1 = new Bros(); Bros bro = new Bros("Lia", "He"); bro.Boost(bro.boostL); bro.Damage(bro.hp, bro.boostL); bro.Death(bro.age, bro.hp, bro.name); bro.Print(); if(bro.dead) bro = null; // 'deleting' the obj. by putting it's reference to null Bros bro4 = new Bros(); bro4.Aging(); System.out.println("Aged?"); bro4.Print(); bro4.Death(bro4.age, bro4.hp, bro4.name); if(bro4.dead) bro4 = null; System.out.println(); Bros bro10 = new Bros(); Bros bro2 = new Bros("Freud", "Bad Boy"); Bros bro3 = new Bros("Shakespeare", "Ugly"); System.out.printf("%d Objects were created in total.\n", count); System.out.println("Tinkering... The programm has finished successfully."); } }
package com.mateus.discordah.listener; import com.mateus.discordah.cards.Card; import com.mateus.discordah.cards.PlayedCards; import com.mateus.discordah.game.Game; import com.mateus.discordah.game.GameManager; import com.mateus.discordah.game.Player; import net.dv8tion.jda.api.entities.ChannelType; import net.dv8tion.jda.api.entities.PrivateChannel; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import javax.annotation.Nonnull; public class MessageListener extends ListenerAdapter { @Override public void onMessageReceived(@Nonnull MessageReceivedEvent event) { if (!event.isFromType(ChannelType.PRIVATE)) return; User user = event.getAuthor(); PrivateChannel channel = event.getPrivateChannel(); GameManager gameManager = GameManager.getInstance(); String contentRaw = event.getMessage().getContentRaw(); Game game = gameManager.getUserGame(user); if (game != null) { Player player = game.getPlayer(user); if (game.isCzar(player)) { return; } Card blackCard = game.getBlackCard(); if (contentRaw.toLowerCase().startsWith("dh!play")) { if (game.getVotes().containsKey(user)) { PlayedCards playedCards = game.getVotes().get(user); if (playedCards.getPlayedCards().size() == blackCard.getSlots()) { channel.sendMessage("**You have already played**").queue(); return; } } String[] args = contentRaw.split("\\s+"); try { int votedCardIdx = Integer.parseInt(args[1]); Card votedCard = player.getCards().get(votedCardIdx - 1); PlayedCards votes; if (!game.getVotes().containsKey(user)) { votes = new PlayedCards(); } else { votes = game.getVotes().get(user); if (votes.getPlayedCards().contains(votedCard)) return; } votes.addCard(votedCard); game.getVotes().put(user, votes); if (votes.getPlayedCards().size() == blackCard.getSlots()) { channel.sendMessage("**You played the card!**").queue(); } else if (votes.getPlayedCards().size() < blackCard.getSlots()) { channel.sendMessage("**The card was played, remains " + (blackCard.getSlots() - votes.getPlayedCards().size()) + " card picks**").queue(); } if (game.everyonePlayed()) { game.czarVoting(event.getJDA()); } } catch (NumberFormatException e) { channel.sendMessage("**You need to select the card number**").queue(); } } } } }
package com.android.demo.mvp.entity; import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class UserInfo implements Serializable { private static final long serialVersionUID = -1; @SerializedName("phone") public String phone; @SerializedName("userId") public String userId; @SerializedName("keepOnline") public boolean keepOnline; @Override public String toString() { final StringBuilder sb = new StringBuilder("UserInfo{"); sb.append("phone='").append(phone).append('\''); sb.append(", userId='").append(userId).append('\''); sb.append(", keepOnline=").append(keepOnline); sb.append('}'); return sb.toString(); } }
package com.kodilla.patterns2.observer.forum; import java.util.Objects; public class ForumUser implements Observer { private final String username; private int updateCount; public ForumUser(String username) { this.username = username; } @Override public void update(ForumTopic forumTopic) { System.out.println(username + "New message in topic " + forumTopic.getName() + "\n" + " total: " + forumTopic.getMessages().size() + " messages"); updateCount++; } public String getUsername() { return username; } public int getUpdateCount() { return updateCount; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ForumUser)) return false; ForumUser forumUser = (ForumUser) o; return getUpdateCount() == forumUser.getUpdateCount() && Objects.equals(getUsername(), forumUser.getUsername()); } @Override public int hashCode() { return Objects.hash(getUsername(), getUpdateCount()); } @Override public String toString() { return "ForumUser{" + "username='" + username + '\'' + ", updateCount=" + updateCount + '}'; } }
package tij.concurrents.part3.util; import tij.concurrents.part3.EvenChecker; public class SynchronizedEvenGenerator extends IntGenerator { private int currentEvenValue = 0; @Override public synchronized int next() { ++currentEvenValue; for (int i = 0;i<2;i++) Thread.yield();//yield()会释放锁吗?看来它不会释放锁。那么这段代码的意义是什么? //猜测是对的。TIJ原文也这样描述: /** * 对Thread.yield()的调用被插入到了两个递增操作之间,以提高 * 在currentEvenValue是奇数状态时上下文切换的可能性。因为 * 互斥可以防止多个任务同时进入临界区,所以这不会产生任何失败。但是如果失败 * 将会发生,调用yield()是一种促使其发生的有效方式。 */ ++currentEvenValue; return currentEvenValue; } public static void main(String[] args) { EvenChecker.test(new SynchronizedEvenGenerator()); } }
package com.example.mx.weddingplanner; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class EventFragment extends Fragment { RecyclerView recyclerView; RecyclerView.LayoutManager layoutManager; RecyclerView.Adapter adapter; Button eventdelete;Button addevent; EditText txevent,txdate,txdescription; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view=inflater.inflate(R.layout.fragment_event, container, false); addevent=(Button)view.findViewById(R.id.event_add_button); txevent =(EditText) view.findViewById(R.id.textview_event); txdate =(EditText) view.findViewById(R.id.textview_date); txdescription =(EditText) view.findViewById(R.id.textview_description); addevent.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { event_database db=new event_database(view.getContext()); boolean isInserted=db.insertData(txevent.getText().toString(),txdate.getText().toString(),txdescription.getText().toString()); if(isInserted){ //Toast.makeText(view.getContext(),"sucess",Toast.LENGTH_SHORT).show(); recyclerView = view.findViewById(R.id.recycler_event); layoutManager = new LinearLayoutManager(view.getContext()); recyclerView.setLayoutManager(layoutManager); adapter = new RecyclerAdapter(view.getContext()); recyclerView.setAdapter(adapter); } else{ Toast.makeText(view.getContext(),"failed",Toast.LENGTH_SHORT).show(); } } }); recyclerView = view.findViewById(R.id.recycler_event); layoutManager = new LinearLayoutManager(view.getContext()); recyclerView.setLayoutManager(layoutManager); adapter = new RecyclerAdapter(view.getContext()); recyclerView.setAdapter(adapter); return view; } }
package com.github.pixelase.commands.utils.input; import java.util.Arrays; public class CommandParseResult { private final String commandName; private final String[] args; public CommandParseResult() { this("", new String[0]); } public CommandParseResult(String commandName, String... args) { super(); this.commandName = commandName; this.args = args; } public String getCommandName() { return commandName; } public String[] getArgs() { return args; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(args); result = prime * result + ((commandName == null) ? 0 : commandName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CommandParseResult other = (CommandParseResult) obj; if (!Arrays.equals(args, other.args)) return false; if (commandName == null) { if (other.commandName != null) return false; } else if (!commandName.equals(other.commandName)) return false; return true; } @Override public String toString() { return "CommandParseResult [commandName=" + commandName + ", args=" + Arrays.toString(args) + "]"; } }
package api.longpoll.bots.methods.impl.messages; import api.longpoll.bots.methods.AuthorizedVkApiMethod; import api.longpoll.bots.methods.VkApiProperties; import api.longpoll.bots.model.response.IntegerResponse; /** * Implements <b>messages.restore</b> method. * <p> * Restores a deleted message. * * @see <a href="https://vk.com/dev/messages.restore">https://vk.com/dev/messages.restore</a> */ public class Restore extends AuthorizedVkApiMethod<IntegerResponse> { public Restore(String accessToken) { super(accessToken); } @Override protected String getUrl() { return VkApiProperties.get("messages.restore"); } @Override protected Class<IntegerResponse> getResponseType() { return IntegerResponse.class; } public Restore setMessageId(int messageId) { return addParam("message_id", messageId); } public Restore setGroupId(int groupId) { return addParam("group_id", groupId); } @Override public Restore addParam(String key, Object value) { return (Restore) super.addParam(key, value); } }
package com.x.model.weixin; import com.x.model.XObject; /** * <p>Description:回复文本信息</p> * @Author Chenkangming * @Date 2014-7-9 * @version 1.0 */ public class WeixinMessageText extends XObject { private static final long serialVersionUID = -2019584996216861231L; /** * 文本内容 */ private String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package in.taskoo.search.es.task.repository; import org.springframework.data.repository.CrudRepository; import in.taskoo.search.es.task.document.Task; public interface TaskRepository extends CrudRepository<Task, String> { }