blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
4d23fcb8583b43f0feb35c9e30a94859ea053b5a
4dd51361082b5f8bfd97b5c55d400343a323b7e9
/Proiect Final Fortech Pre-employment Ionut Bogdan/Cinema Reservation Sistem/src/main/java/ro/ionutbogdan/cinema/services/UserService.java
4b0dc79630735636d48820ce17f5ed54f999cdf4
[]
no_license
bogdan-ionut/CinemaReservationApp_UPDATED
868025abb1e83f834cdd1d3156d285ecb278baa4
d4a855a0e89a16d78ccebfcc14cb0a5e548cdf2d
refs/heads/master
2020-03-17T20:56:21.535436
2018-05-18T10:58:37
2018-05-18T10:58:37
133,935,975
0
0
null
null
null
null
UTF-8
Java
false
false
557
java
package ro.ionutbogdan.cinema.services; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.ionutbogdan.cinema.domain.User; import ro.ionutbogdan.cinema.dao.UserDAO; import java.util.Collection; public class UserService { private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class); public UserDAO getDao() { return dao; } public void setDao(UserDAO dao) { this.dao = dao; } private UserDAO dao; public Collection<User> listAll() { return dao.getAll(); } }
[ "ionutbogdan91@gmail.com" ]
ionutbogdan91@gmail.com
8454028d4eef42dca7ddf20e16275bcfc603d00d
a41dd9e4161f33d433ca23cad3f02ec67523bf25
/ibatis/src/com/baokang/service/UserService.java
8a52ca300abdd353d898488dae3a6e99ce989570
[]
no_license
JimHongzongmin/myproject
c59042f2b33c7aaeb3f50a690608fddf2092b5de
273f616676d7aaf1a07763a264fa486ede45bb17
refs/heads/master
2021-01-10T15:54:48.282430
2016-01-08T03:11:41
2016-01-08T03:11:41
49,242,338
0
0
null
null
null
null
UTF-8
Java
false
false
142
java
package com.baokang.service; import com.baokang.domain.User; public interface UserService { public User queryByUser(User user); }
[ "308099172@qq.com" ]
308099172@qq.com
9217108fb29df3be98f938e536cf05d6d84252dc
2779d673ff4f37a190e87072697d9e2cfa6f595f
/src/menubar/FormatStyle.java
8d2b2365ec95d8321aea069b741a105dd5bf22ed
[]
no_license
jefrusse24/JournalNotes
87804bb8dd32d2053a5347103f0b2c4369a42424
f4eb57f8e79a132d18e7edb5d4db213905c7996c
refs/heads/master
2020-06-04T12:54:31.068221
2014-12-19T01:23:40
2014-12-19T01:23:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
799
java
package menubar; import java.awt.event.KeyEvent; public enum FormatStyle { REGULAR("Regular","f_regular",KeyEvent.VK_R), HEADING1("Heading A","f_headinga",KeyEvent.VK_1), HEADING2("Heading B","f_headingb",KeyEvent.VK_2), HEADING3("Heading C","f_headingc",KeyEvent.VK_3), HEADING4("Heading D","f_headingd",KeyEvent.VK_4), CODE("Code","f_code",KeyEvent.VK_M), QUOTE("Quote","f_quote",KeyEvent.VK_I), BOLD("Bold","f_bold",KeyEvent.VK_B); private final String menuName, styleName; int key; private FormatStyle(String n, String f, int k) { menuName = n; styleName = f; key = k; } public String getMenuName() { return menuName; } public String getStyleName() { return styleName; } public String toString() { return menuName; } public int getKey() { return key; } }
[ "jefrusse@yahoo.com" ]
jefrusse@yahoo.com
afde394f11ced9627b52b776302661a5548c644d
e05a290f18b0ae8089709f4fbe92f3f49042daee
/kernel/kernel-core/src/main/java/io/mosip/kernel/core/idgenerator/spi/UinGenerator.java
ec498019af46df3a437ed6af132c85f3bf99f1a9
[]
no_license
Aswin-MN/personal
25e6d6bf306e61a236d0ea886d33ea621bb7dc56
d096fa6ab16e13a66a82be0325cf4d117d3669f3
refs/heads/master
2021-10-11T16:24:08.604019
2019-01-28T12:52:41
2019-01-28T12:52:41
166,238,628
0
1
null
null
null
null
UTF-8
Java
false
false
327
java
package io.mosip.kernel.core.idgenerator.spi; /** * Interface having a function to generate an Id * * @author Dharmesh Khandelwal * @since 1.0.0 * * @param <T> * Type of Id */ public interface UinGenerator<T> { /** * Function to generate an Id * * @return The generated id */ T generateId(); }
[ "info@mosip.io" ]
info@mosip.io
f0a15c452fd8956891caebbf8a3451c62c514c8b
91ff59f4d545662a442219de8dc235fa8f495877
/TeamManager/src/com/sns/teammgr/action/EventDeleteAction.java
21aa752a36d9c29e594d747de7283c0e555a6ceb
[]
no_license
robbroadhead/OpenCode
1a277454a639a0fbc080806c86f8d32e2831d1aa
27739f83369901157a6033d08fe892f4425f7cd9
refs/heads/master
2021-01-10T05:17:11.893802
2016-03-31T19:34:03
2016-03-31T19:34:03
55,176,885
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
2,736
java
package com.sns.teammgr.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.torque.Torque; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import com.sns.teammgr.managers.EventPeer; /** * The controller class for the Link delete action * ******************************************************************* * Copyright Notice: * Copyright © 2007 Sleepless Nights Software, Inc. * All Rights Reserved. * * This computer program is protected by copyright law and * international treaties. Unauthorized use or distribution of * this program, or any portion of it is strictly prohibited. * Violation may result in severe civil or criminal penalties. ******************************************************************* * */ public final class EventDeleteAction extends Action { /** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * Return an <code>ActionForward</code> instance describing where and how * control should be forwarded, or <code>null</code> if the response has * already been completed. * * @param mapping The ActionMapping used to select this instance * @param actionForm The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception Exception if business logic throws an exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Basic cleanup to keep the session as thin as possible request.getSession().removeAttribute("curlist"); if (!Torque.isInit()) { Torque.init("/usr/conf/Teammgr.properties"); } // Make sure the user has logged in. if (request.getSession().getAttribute("teammgr.User") == null) { return mapping.findForward("failure"); } EventPeer.delete(request.getParameter("id")); // Remove the Form Bean - don't need to carry values forward request.removeAttribute(mapping.getAttribute()); // Forward control to the specified success URI ActionMessages msgs = new ActionMessages(); msgs.add("success",new ActionMessage("general.delete.success")); saveMessages(request,msgs); // Assume success if we have reached this point return mapping.findForward("success"); } }
[ "rob@rb-sns.com" ]
rob@rb-sns.com
2438af2117cefe8d969a90b42bd5e8eaefc10540
87671c0bc2df44a2f2561836f54c483d19c3ec16
/app/src/main/java/odeen/weatherpredictor/view/LocationPickerDialog.java
8f6139c5e25fc7f0e27c2a4ebf5ad20204d7bf28
[]
no_license
ezamyatin/lesson8
60088dc2dea5576cb9311d08e1dbd3469a7bfd25
b62f595caf68293ce71a913465a3be634508ed26
refs/heads/master
2023-01-08T10:02:52.193808
2014-12-01T15:44:20
2014-12-01T15:44:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,676
java
package odeen.weatherpredictor.view; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import odeen.weatherpredictor.R; /** * Created by Женя on 27.11.2014. */ public class LocationPickerDialog extends DialogFragment { public static final String EXTRA_CITY_NAME = "EXTRA_CITY_NAME"; private String mName; public static LocationPickerDialog newInstance() { LocationPickerDialog fragment = new LocationPickerDialog(); return fragment; } public void sendResult(int resultCode) { if (getTargetFragment() == null) return; Intent i = new Intent(); i.putExtra(EXTRA_CITY_NAME, mName); getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, i); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { setRetainInstance(true); View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_channel, null); EditText name = (EditText) v.findViewById(R.id.dialog_channel_namePicker); name.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { // getArguments().putString(EXTRA_CITY_NAME, charSequence.toString()); mName = charSequence.toString(); } @Override public void afterTextChanged(Editable editable) { } }); return new AlertDialog.Builder(getActivity()) .setView(v) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { sendResult(Activity.RESULT_OK); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { sendResult(Activity.RESULT_CANCELED); } }).create(); } }
[ "jeka_zamyatin@mail.ru" ]
jeka_zamyatin@mail.ru
aad08aa52d376ce40ea5e34de7b08a3da8d7d286
351c413f6c57dfab2aec70db5fee5f3acc87c284
/ChromaKey/app/src/main/java/com/photo/chroma/Preview.java
40d449936f8337a38738ad007a3c51734f21a950
[ "MIT" ]
permissive
rbnuria/NPI
589162ff7de01df14029edc42d1ca72995b73c33
9154aacf1e2992bd5476d26fd894829cee9d4bc6
refs/heads/master
2021-03-22T04:05:03.051520
2018-01-25T17:42:24
2018-01-25T17:42:24
107,530,237
3
1
null
null
null
null
UTF-8
Java
false
false
4,962
java
package com.photo.chroma; /* import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.hardware.Camera; import android.hardware.Camera.PreviewCallback; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; class Preview extends SurfaceView implements SurfaceHolder.Callback { private static final String TAG = "Preview"; SurfaceHolder mHolder; public Camera camera; Preview(Context context) { super(context); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, acquire the camera and tell it where // to draw. camera = Camera.open(); try { camera.setPreviewDisplay(holder); camera.setPreviewCallback(new PreviewCallback() { public void onPreviewFrame(byte[] data, Camera arg1) { FileOutputStream outStream = null; try { outStream = new FileOutputStream(String.format( "/sdcard/%d.jpg", System.currentTimeMillis())); outStream.write(data); outStream.close(); Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } Preview.this.invalidate(); } }); } catch (IOException e) { e.printStackTrace(); } } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. // Because the CameraDevice object is not a shared resource, it's very // important to release it when the activity is paused. camera.stopPreview(); camera = null; } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Now that the size is known, set up the camera parameters and begin // the preview. Camera.Parameters parameters = camera.getParameters(); parameters.setPreviewSize(w, h); camera.setParameters(parameters); camera.startPreview(); } @Override public void draw(Canvas canvas) { super.draw(canvas); Paint p = new Paint(Color.RED); Log.d(TAG, "draw"); canvas.drawText("PREVIEW", canvas.getWidth() / 2, canvas.getHeight() / 2, p); } } */ import java.io.IOException; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.PixelFormat; import android.graphics.PixelXorXfermode; import android.graphics.drawable.BitmapDrawable; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.hardware.Camera.PreviewCallback; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; class Preview extends SurfaceView implements SurfaceHolder.Callback { // <1> private static final String TAG = "Preview"; SurfaceHolder mHolder; // <2> public Camera camera; // <3> Preview(Context context) { super(context); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); // <4> mHolder.addCallback(this); // <5> mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // <6> } // Called once the holder is ready public void surfaceCreated(SurfaceHolder holder) { // <7> // The Surface has been created, acquire the camera and tell it where // to draw. camera = Camera.open(); // <8> try { camera.setPreviewDisplay(holder); // <9> camera.setPreviewCallback(new PreviewCallback() { // <10> // Called for each frame previewed public void onPreviewFrame(byte[] data, Camera camera) { // <11> Preview.this.invalidate(); // <12> } }); } catch (IOException e) { // <13> e.printStackTrace(); } } // Called when the holder is destroyed public void surfaceDestroyed(SurfaceHolder holder) { // <14> camera.setPreviewCallback(null); camera.stopPreview(); // camera.release(); } // Called when holder has changed public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // <15> // Parameters params = camera.getParameters(); // params.setSceneMode(Parameters.SCENE_MODE_PORTRAIT); // params.setFocusMode(Parameters.FOCUS_MODE_FIXED); // params.setFlashMode(Parameters.FLASH_MODE_ON); // params.setPreviewSize(320, 240); // params.setPictureFormat(PixelFormat.JPEG); // camera.setParameters(params); camera.startPreview(); } }
[ "jlsuarezdiaz@correo.ugr.es" ]
jlsuarezdiaz@correo.ugr.es
009a10ac4f1fbc7ba433d3468a62803575ce0cd6
533dccc8d859b3727f1d13d57e96fcada0367ff1
/src/main/java/ru/Pages/IpotekaPage.java
ebba24eba1651da0f5a9e2237335c7b37aa46809
[]
no_license
PlzSayTy/SberSeleniumCucumberAllure
d61a9ceb40748475e293771344b848cd868c0b43
c0c060ad3fd725cad68391bf97a1e5f18d97770c
refs/heads/master
2021-03-29T19:13:40.462018
2020-03-22T14:30:24
2020-03-22T14:30:24
247,978,735
0
0
null
2020-10-13T20:25:58
2020-03-17T13:36:17
Java
UTF-8
Java
false
false
3,208
java
package ru.Pages; import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.function.Executable; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Wait; import ru.Steps.BaseStep; public class IpotekaPage extends BasePage { @FindBy(id = "iFrameResizer0") WebElement frame; public void changeFrame() { executor.executeScript("window.scrollTo(0, 1600)"); wait.until(ExpectedConditions.presenceOfElementLocated(By.id("iFrameResizer0"))); driver.switchTo().frame(frame); } public void fullFill(String xpath, String yourKeys) { wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath))); driver.findElement(By.xpath(xpath)).clear(); driver.findElement(By.xpath(xpath)).sendKeys(yourKeys); } public void assertChangeFirstTime(String amountOfCredit){ if (!(driver.findElement(By.xpath("//input[contains(@id, 'estateCost')]")).getAttribute("value").equals("5 180 000 \u20BD"))){ fullFill("//input[contains(@id, 'estateCost')]", "5180000"); } } public void waitUntilItChanges(String amountOfCredit, String mounthlyPayment, String requiredIncome, String rate) { wait.until(ExpectedConditions.textToBe(By.xpath("//span[contains(@data-test-id, 'amountOfCredit')]"), amountOfCredit)); wait.until(ExpectedConditions.textToBe(By.xpath("//span[contains(@data-test-id, 'monthlyPayment')]"), mounthlyPayment)); wait.until(ExpectedConditions.textToBe(By.xpath("//span[contains(@data-test-id, 'requiredIncome')]"), requiredIncome)); wait.until(ExpectedConditions.textToBe(By.xpath("//span[contains(@data-test-id, 'rate')]"), rate)); } public void JSclick(String xpath) { executor.executeScript("arguments[0].click();", driver.findElement(By.xpath(xpath))); } public void assertAllOfThem() { Assertions.assertAll("Тест упал из-за процента", (Executable) () ->{ Assert.assertTrue(driver.findElement(By.xpath("//span[contains(@data-test-id, 'amountOfCredit')]")).getText().equals("2 122 000 \\u20BD")); Assert.assertTrue(driver.findElement(By.xpath("//span[contains(@data-test-id, 'monthlyPayment')]")).getText().equals("17 535 \\u20BD")); Assert.assertTrue(driver.findElement(By.xpath("//span[contains(@data-test-id, 'requiredIncome')]")).getText().equals("29 224 \\u20BD")); Assert.assertTrue(driver.findElement(By.xpath("//span[contains(@data-test-id, 'rate')]")).getText().equals("9,4 %")); }); } public void clickWaitAndAssert(String clickAfterWait){ Assert.assertTrue(driver.findElement(By.xpath(clickAfterWait)).isDisplayed()); Assert.assertTrue(driver.findElement(By.xpath(clickAfterWait)).isEnabled()); executor.executeScript("arguments[0].click();", driver.findElement(By.xpath(clickAfterWait))); click(clickAfterWait); } }
[ "kavadrat000@yandex.ru" ]
kavadrat000@yandex.ru
6ae45fab5638638483b9cc7335395c46fa1e8a5f
9f731a74aaebf17de0949a89663a566bcf992d74
/client-service/src/main/java/sep/project/dto/RedirectDTO.java
68ca02df6ac6921938aaa1b4069cfb8ef22266e0
[]
no_license
majak96/sep-project
9fa8a65f863a593c90edab5ea4da3f584854daa0
56405d6cff3f57770d03403bc1697bfa7ce4ce11
refs/heads/master
2022-04-08T06:41:53.528265
2020-02-19T06:19:44
2020-02-19T06:19:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
260
java
package sep.project.dto; public class RedirectDTO { private String url; public RedirectDTO() { super(); // TODO Auto-generated constructor stub } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
[ "44587403+vesnamilic@users.noreply.github.com" ]
44587403+vesnamilic@users.noreply.github.com
e43d78029e96c890ecc0255857d143d33ed67cdb
58a3d797bfc13ff8d4e960aafa97a7816e4e76f4
/app/src/main/java/com/ys/administrator/mydemo/util/WeiXinUtil.java
c284227513a5fc3537da4f87288463b892033b14
[]
no_license
YsInHZ/MyPublicFarm
3c53769cd88e150e3965b22ae58a7bd5014ea78e
7fe40fbf24dd01f65ffb939d2c2b4d120d962b56
refs/heads/master
2020-04-11T07:23:38.570540
2019-03-24T15:43:32
2019-03-24T15:43:32
161,608,767
0
0
null
null
null
null
UTF-8
Java
false
false
2,728
java
package com.ys.administrator.mydemo.util; import android.graphics.Bitmap; import com.ys.administrator.mydemo.application.MyApplication; import com.tencent.mm.opensdk.modelmsg.SendAuth; import com.tencent.mm.opensdk.modelmsg.SendMessageToWX; import com.tencent.mm.opensdk.modelmsg.WXImageObject; import com.tencent.mm.opensdk.modelmsg.WXMediaMessage; import com.tencent.mm.opensdk.modelmsg.WXWebpageObject; import com.tencent.mm.opensdk.openapi.IWXAPI; import com.tencent.mm.opensdk.openapi.WXAPIFactory; /** * 微信工具类 * Created by Administrator on 2018/8/2. */ public class WeiXinUtil { public static IWXAPI api = null; public static IWXAPI getIWXAPI() { if(api==null){ api = WXAPIFactory.createWXAPI(MyApplication.getInstance(),Constant.APP_ID,true); api.registerApp(Constant.APP_ID); } return api; } /** * 微信登录 */ public static void WXLogin(){ if(api==null){ getIWXAPI(); } SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = "wechat_gengnong_login"; api.sendReq(req); } /** * 分享APP * @param aa 分享类型:SendMessageToWX.Req.WXSceneTimeline朋友圈 WXSceneSession对话 */ public static void share(int aa){//SendMessageToWX.Req.WXSceneTimeline WXSceneSession if(api==null){ getIWXAPI(); } WXWebpageObject webpage = new WXWebpageObject(); webpage.webpageUrl = "https://www.hzmyxf119.com/static/app-release.apk"; WXMediaMessage msg = new WXMediaMessage(webpage); msg.title = "名邑消防"; msg.description = "加入名邑消防,开启智慧管理"; SendMessageToWX.Req req = new SendMessageToWX.Req(); req.message = msg; req.scene = aa; api.sendReq(req); } /** * 分享图片 * @param bitmap * @param aa 分享类型:SendMessageToWX.Req.WXSceneTimeline朋友圈 WXSceneSession对话 */ public static void share(Bitmap bitmap, int aa){ if(api==null){ getIWXAPI(); } WXImageObject imageObject = new WXImageObject(bitmap); WXMediaMessage msg = new WXMediaMessage(); msg.title = "极客耘耕"; msg.description = "扫码加入我的农场吧"; msg.mediaObject = imageObject; SendMessageToWX.Req req= new SendMessageToWX.Req(); // req.transaction = System.currentTimeMillis()+""+Constant.getUSERID(); req.message = msg; req.scene = aa; api.sendReq(req); } public static void detach(){ api.detach(); api = null; } }
[ "git@gitee.com:zhizhuokeji/jikeyungeng-android.git" ]
git@gitee.com:zhizhuokeji/jikeyungeng-android.git
d327b7393fb1edacccf1cf955f8cc2a543822959
fe86ac8c9ff8d57b55c96a7923374099ec995ddc
/TrucksApp/src/java/controllers/LocationList.java
19e73c00e53bbdfa0964fd84085dc0cd466e9cc6
[]
no_license
sboregowda/TrucksApp
858940792203893bf5bb5f4cb684b1ec4e8586ed
c6a21b4eaff5cc8ae777e98a5a2741c20a85860e
refs/heads/master
2020-03-25T16:22:59.416576
2018-08-07T21:42:16
2018-08-07T21:42:16
143,927,923
0
0
null
null
null
null
UTF-8
Java
false
false
1,478
java
/* * 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 controllers; import database.Main; import database.Main1; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import model.Customer; import model.Location; /** * * @author Mazen */ public class LocationList { Main1 main = new Main1(); public ArrayList<Location> getLocations(String locationCode) throws Exception { Connection con = main.getConnection(); PreparedStatement selesctCustomers = con.prepareStatement("select locationID, customerID, locationCode, city, state from " + "locations where locationCode = '" + locationCode + "'"); ResultSet rs = selesctCustomers.executeQuery(); ArrayList<Location> locations = new ArrayList<>(); while (rs.next()) { Location loc = new Location(); loc.setCustomerID(rs.getString("customerID")); loc.setLocationID(rs.getString("locationID")); loc.setLocationCode(rs.getString("locationCode")); loc.setCity(rs.getString("city")); loc.setState(rs.getString("state")); locations.add(loc); } return locations; } }
[ "sathwik@Sathwiks-MacBook-Pro.local" ]
sathwik@Sathwiks-MacBook-Pro.local
1dbc000dc21723c96e2eca822f88b8efb0d947b8
d9fbd35c03bcc26422ede68738e2950b180fc092
/bower_components/cometd-jquery/cometd-java/cometd-java-server/src/test/java/org/cometd/server/ConcurrentConnectDisconnectTest.java
7acbd5b252a27004806e9dcaa1df4722ea9fe7f8
[]
no_license
barrackboy/work-stuff
598234f1537b1e5c1d2674669b00910541be0450
0f6ae62f9f4647f0185607fce7888a0ae9a38556
refs/heads/master
2021-01-17T17:52:45.794607
2016-10-28T08:32:24
2016-10-28T08:32:24
70,683,389
0
0
null
null
null
null
UTF-8
Java
false
false
10,601
java
/* * Copyright (c) 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cometd.server; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import org.cometd.bayeux.Channel; import org.cometd.bayeux.Message; import org.cometd.bayeux.server.ServerChannel; import org.cometd.bayeux.server.ServerMessage; import org.cometd.bayeux.server.ServerSession; import org.cometd.common.JettyJSONContextClient; import org.cometd.server.transport.JSONTransport; import org.eclipse.jetty.client.ContentExchange; import org.eclipse.jetty.client.HttpExchange; import org.eclipse.jetty.http.HttpHeaders; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ConcurrentConnectDisconnectTest extends AbstractBayeuxClientServerTest { @Before public void prepare() throws Exception { startServer(null); } @Test public void testConnectListenerThenDisconnectThenConnectHandler() throws Exception { final CountDownLatch connectLatch = new CountDownLatch(2); final CountDownLatch disconnectLatch = new CountDownLatch(1); bayeux.getChannel("/meta/connect").addListener(new ServerChannel.MessageListener() { public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message) { connectLatch.countDown(); if (connectLatch.getCount() == 0) await(disconnectLatch); return true; } }); ContentExchange handshake = newBayeuxExchange("[{" + "\"channel\": \"/meta/handshake\"," + "\"version\": \"1.0\"," + "\"minimumVersion\": \"1.0\"," + "\"supportedConnectionTypes\": [\"long-polling\"]" + "}]"); httpClient.send(handshake); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, handshake.waitForDone()); Assert.assertEquals(200, handshake.getResponseStatus()); String clientId = extractClientId(handshake); String bayeuxCookie = extractBayeuxCookie(handshake); String channelName = "/foo"; ContentExchange subscribe = newBayeuxExchange("[{" + "\"clientId\": \"" + clientId + "\"," + "\"channel\": \"/meta/subscribe\"," + "\"subscription\": \"" + channelName + "\"" + "}]"); httpClient.send(subscribe); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, subscribe.waitForDone()); Assert.assertEquals(200, subscribe.getResponseStatus()); ContentExchange connect1 = newBayeuxExchange("[{" + "\"channel\": \"/meta/connect\"," + "\"clientId\": \"" + clientId + "\"," + "\"connectionType\": \"long-polling\"" + "}]"); connect1.setRequestHeader(HttpHeaders.COOKIE, bayeuxCookie); httpClient.send(connect1); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, connect1.waitForDone()); Assert.assertEquals(200, connect1.getResponseStatus()); ContentExchange connect2 = newBayeuxExchange("[{" + "\"channel\": \"/meta/connect\"," + "\"clientId\": \"" + clientId + "\"," + "\"connectionType\": \"long-polling\"" + "}]"); connect2.setRequestHeader(HttpHeaders.COOKIE, bayeuxCookie); httpClient.send(connect2); // Wait for the second connect to arrive, then disconnect Assert.assertTrue(connectLatch.await(5, TimeUnit.SECONDS)); ContentExchange disconnect = newBayeuxExchange("[{" + "\"channel\": \"/meta/disconnect\"," + "\"clientId\": \"" + clientId + "\"" + "}]"); httpClient.send(disconnect); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, disconnect.waitForDone()); Assert.assertEquals(200, disconnect.getResponseStatus()); disconnectLatch.countDown(); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, connect2.waitForDone()); Assert.assertEquals(200, connect2.getResponseStatus()); JettyJSONContextClient parser = new JettyJSONContextClient(); Message.Mutable connectReply2 = parser.parse(connect2.getResponseContent())[0]; String error = (String)connectReply2.get(Message.ERROR_FIELD); Assert.assertNotNull(error); Assert.assertTrue(error.toLowerCase().contains("unknown")); Map<String,Object> advice = connectReply2.getAdvice(); Assert.assertNotNull(advice); Assert.assertEquals(Message.RECONNECT_NONE_VALUE, advice.get(Message.RECONNECT_FIELD)); Assert.assertNull(bayeux.getSession(clientId)); // Test that sending a connect for an expired session // will return an advice with reconnect:"handshake" ContentExchange connect3 = newBayeuxExchange("[{" + "\"channel\": \"/meta/connect\"," + "\"clientId\": \"" + clientId + "\"," + "\"connectionType\": \"long-polling\"" + "}]"); connect3.setRequestHeader(HttpHeaders.COOKIE, bayeuxCookie); httpClient.send(connect3); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, connect3.waitForDone()); Assert.assertEquals(200, connect3.getResponseStatus()); Message.Mutable connectReply3 = parser.parse(connect3.getResponseContent())[0]; advice = connectReply3.getAdvice(); Assert.assertNotNull(advice); Assert.assertEquals(Message.RECONNECT_HANDSHAKE_VALUE, advice.get(Message.RECONNECT_FIELD)); } @Test public void testConnectHandlerThenDisconnect() throws Exception { final CountDownLatch connectLatch = new CountDownLatch(2); final CountDownLatch disconnectLatch = new CountDownLatch(1); final CountDownLatch suspendLatch = new CountDownLatch(1); bayeux.setTransports(new JSONTransport(bayeux) { { init(); } @Override protected ServerMessage.Mutable bayeuxServerHandle(ServerSessionImpl session, ServerMessage.Mutable message) { ServerMessage.Mutable reply = super.bayeuxServerHandle(session, message); if (Channel.META_CONNECT.equals(message.getChannel())) { connectLatch.countDown(); if (connectLatch.getCount() == 0) await(disconnectLatch); } return reply; } @Override protected void metaConnectSuspended(HttpServletRequest request, ServerSession session, long timeout) { suspendLatch.countDown(); } }); ContentExchange handshake = newBayeuxExchange("[{" + "\"channel\": \"/meta/handshake\"," + "\"version\": \"1.0\"," + "\"minimumVersion\": \"1.0\"," + "\"supportedConnectionTypes\": [\"long-polling\"]" + "}]"); httpClient.send(handshake); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, handshake.waitForDone()); Assert.assertEquals(200, handshake.getResponseStatus()); String clientId = extractClientId(handshake); String bayeuxCookie = extractBayeuxCookie(handshake); String channelName = "/foo"; ContentExchange subscribe = newBayeuxExchange("[{" + "\"clientId\": \"" + clientId + "\"," + "\"channel\": \"/meta/subscribe\"," + "\"subscription\": \"" + channelName + "\"" + "}]"); httpClient.send(subscribe); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, subscribe.waitForDone()); Assert.assertEquals(200, subscribe.getResponseStatus()); ContentExchange connect1 = newBayeuxExchange("[{" + "\"channel\": \"/meta/connect\"," + "\"clientId\": \"" + clientId + "\"," + "\"connectionType\": \"long-polling\"" + "}]"); connect1.setRequestHeader(HttpHeaders.COOKIE, bayeuxCookie); httpClient.send(connect1); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, connect1.waitForDone()); Assert.assertEquals(200, connect1.getResponseStatus()); ContentExchange connect2 = newBayeuxExchange("[{" + "\"channel\": \"/meta/connect\"," + "\"clientId\": \"" + clientId + "\"," + "\"connectionType\": \"long-polling\"" + "}]"); connect2.setRequestHeader(HttpHeaders.COOKIE, bayeuxCookie); httpClient.send(connect2); // Wait for the second connect to arrive, then disconnect Assert.assertTrue(connectLatch.await(5, TimeUnit.SECONDS)); ContentExchange disconnect = newBayeuxExchange("[{" + "\"channel\": \"/meta/disconnect\"," + "\"clientId\": \"" + clientId + "\"" + "}]"); httpClient.send(disconnect); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, disconnect.waitForDone()); Assert.assertEquals(200, disconnect.getResponseStatus()); disconnectLatch.countDown(); // The connect must not be suspended Assert.assertFalse(suspendLatch.await(1, TimeUnit.SECONDS)); Assert.assertEquals(HttpExchange.STATUS_COMPLETED, connect2.waitForDone()); Assert.assertEquals(200, connect2.getResponseStatus()); Assert.assertTrue(connect2.getResponseContent().toLowerCase().contains("\"none\"")); Assert.assertNull(bayeux.getSession(clientId)); } private void await(CountDownLatch latch) { try { latch.await(); } catch (InterruptedException x) { Thread.currentThread().interrupt(); } } }
[ "shout2me@gmail.com" ]
shout2me@gmail.com
d189b28b8f19b0e747cc81b0e75eec2f2cc6f045
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/MATH-60b-5-16-SPEA2-WeightedSum:TestLen:CallDiversity/org/apache/commons/math/distribution/NormalDistributionImpl_ESTest.java
5cb3664f367bc4eb73ac4d9782d696b3d0777c2a
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
587
java
/* * This file was automatically generated by EvoSuite * Sun Jan 19 04:21:44 UTC 2020 */ package org.apache.commons.math.distribution; import org.junit.Test; import static org.junit.Assert.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class NormalDistributionImpl_ESTest extends NormalDistributionImpl_ESTest_scaffolding { @Test public void notGeneratedAnyTest() { // EvoSuite did not generate any tests } }
[ "pouria.derakhshanfar@gmail.com" ]
pouria.derakhshanfar@gmail.com
81b172a586200db8c2fceab553dc8ed6a2ac1bb8
b541c6dd3cef2887426783e1c95d71edd966742b
/src/main/java/pl/bratosz/labelscreator/labels/format/FontName.java
d769f6e28322952fa57edb1770b9d18e40953e2f
[]
no_license
Bratosz/labels-creator
ec78d1fbe1416aa786148dbe496c0628534ab77c
9cb6ac420bb3fab155e855e9af563d2429019b7f
refs/heads/master
2022-07-09T16:06:42.748484
2022-06-29T20:44:00
2022-06-29T20:44:00
230,086,166
0
0
null
null
null
null
UTF-8
Java
false
false
300
java
package pl.bratosz.labelscreator.labels.format; public enum FontName { TIMES_NEW_ROMAN("Times New Roman"), ARIAL("Arial"), TAHOMA("Tahoma"); private String name; FontName(String name){ this.name = name; } public String getName() { return name; } }
[ "palej.bartosz@gmail.com" ]
palej.bartosz@gmail.com
0bf80167b959bdbfe68319d989cda4e35bec9a8b
cd9f23eff5772112c1b107b72a9472ac261d70cc
/taotao-rest/src/main/java/com/taotao/rest/dao/JedisClient.java
30af0f27e3151ff554f8fb65904a6a63d04e3f8d
[]
no_license
laijianming/taotao
2b9687e5604766ac991f86473514829f068f97c4
2e0a7ce1c676f43e1296f7dfa237a0c4b9a0d946
refs/heads/master
2020-04-04T18:24:56.044618
2018-11-05T05:14:16
2018-11-05T05:22:44
156,162,750
0
0
null
null
null
null
UTF-8
Java
false
false
770
java
package com.taotao.rest.dao; /** * jdies dao接口 * * @author Administrator * */ public interface JedisClient { String get(String key); String set(String key, String value); String hget(String hkey, String hget); long hset(String hkey, String key, String value); // 返回一个自增长整形 long incr(String key); /** * 设置有效期,单位秒,-1为永久,-2为过期 命令: expire key 1000(设置过期时间) * * @param key * @param second * @return */ long expire(String key, int second); /** * 命令: 192.168xxx> ttl key (查询剩多少时间) ; * * @param key * @return */ long ttl(String key); long del(String key); long hdel(String hkey, String key); }
[ "2437341214@qq.com" ]
2437341214@qq.com
f2dc0e02d409d34ea4d1b9d3fa154704516e0287
2704538738d3baf96f608414f53ab67f40671c1d
/2.JavaCore/src/com/javarush/task/task14/task1408/Hen.java
81e4ac36aa2aa6eb65f7155bd1a8ace65bcf5506
[]
no_license
OlenaSoboleva/JavaRushTasks
82bf2fdfe88b52054a03416cc3a73f7a70412932
84be702e44900ab302508bc850c7e6bbb64a74cf
refs/heads/master
2020-04-10T18:43:20.201676
2018-12-10T17:19:27
2018-12-10T17:19:27
161,210,446
0
0
null
null
null
null
UTF-8
Java
false
false
248
java
package com.javarush.task.task14.task1408; /** * Created by osob on 8/13/2018. */ public abstract class Hen { public abstract int getCountOfEggsPerMonth(); public String getDescription() { return "Я - курица."; } }
[ "selena.soboleva@gmail.com" ]
selena.soboleva@gmail.com
202c9448c669e30fa014f5c2c637c8a34ae88b50
c95c3bb5c02ccb7cf162a4cc5263f55d2b0a45ce
/src/main/java/cn/kgc/ssm/mapper/AuthorityMapper.java
6d1fa9b658d104f2d3fe6852ca320671cbccf620
[]
no_license
219xiaohongchen/k9508_hotel1
adaba3467d54e3b5f0bc698f1e10ba26c631c622
9f034cbc7209020d3da6195a24cc14b69a3f4772
refs/heads/master
2022-12-23T04:14:53.636578
2020-02-04T10:01:58
2020-02-04T10:01:58
238,107,059
0
0
null
2022-12-16T12:13:58
2020-02-04T02:33:16
JavaScript
UTF-8
Java
false
false
429
java
package cn.kgc.ssm.mapper; import cn.kgc.ssm.entity.Authority; import org.apache.ibatis.annotations.Param; import java.util.List; /* *权限Mapper代理对象 * */ public interface AuthorityMapper extends BaseMapper<Authority>{ //根据角色id和parent查询(一级二级)权限数据 List<Authority> selAuthByRoleIdAndParent(@Param("roleId") Integer roleId, @Param("parent") Integer parent) throws Exception; }
[ "1075829412@qq.com" ]
1075829412@qq.com
6d0a197210dbe51c6c51b55cdba0bfc9a88815f4
5c42f31f17e36f2c0a6d064a6b6b28fc60dbc45b
/iNaturalist/src/main/java/org/inaturalist/android/ItemSearchActivity.java
df2a4b77ab90ca1aeae565611ac032b7bfe80307
[ "MIT" ]
permissive
rleir/iNaturalistAndroid
117233c2fe4ed830ff1f8f87745275737be1ad5b
48eb9bc2069c9625179e35722d7b3e25c2fcfe3e
refs/heads/master
2020-03-28T06:30:35.264895
2018-09-06T18:15:27
2018-09-06T18:15:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,152
java
package org.inaturalist.android; import android.app.Activity; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Typeface; import android.media.projection.MediaProjection; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Filter; import android.widget.Filterable; import android.widget.HeaderViewListAdapter; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.flurry.android.FlurryAgent; import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback; import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class ItemSearchActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, ProjectsAdapter.OnLoading { private static final String LOG_TAG = "ItemSearchActivity"; public static final String IS_USER = "is_user"; public static final String RETURN_RESULT = "return_result"; public static final String RESULT_VIEWER_ACTIVITY = "result_viewer_activity"; public static final String RESULT_VIEWER_ACTIVITY_PARAM_NAME = "result_viewer_activity_param_name"; public static final String SEARCH_HINT_TEXT = "search_hint_text"; public static final String SEARCH_URL = "search_url"; public static final String RESULT = "result"; private Class<Activity> mViewerActivity; private String mViewerActivityParamName; private String mHintText; private String mSearchUrl; private boolean mReturnResult; private boolean mIsUser; private String mSearchString = ""; private ProjectsAdapter mAdapter; private ProgressBar mProgress; private INaturalistApp mApp; private EditText mSearchEditText; private TextView mNoResults; @Override protected void onStart() { super.onStart(); FlurryAgent.onStartSession(this, INaturalistApp.getAppContext().getString(R.string.flurry_api_key)); FlurryAgent.logEvent(this.getClass().getSimpleName()); } @Override public void onResume() { super.onResume(); if (mApp == null) { mApp = (INaturalistApp) getApplicationContext(); } } @Override protected void onStop() { super.onStop(); FlurryAgent.onEndSession(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: setResult(RESULT_CANCELED); finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { setResult(RESULT_CANCELED); finish(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (mApp == null) { mApp = (INaturalistApp) getApplicationContext(); } final Intent intent = getIntent(); mViewerActivity = (Class<Activity>) intent.getSerializableExtra(RESULT_VIEWER_ACTIVITY); mViewerActivityParamName = intent.getStringExtra(RESULT_VIEWER_ACTIVITY_PARAM_NAME); mHintText = intent.getStringExtra(SEARCH_HINT_TEXT); mSearchUrl = intent.getStringExtra(SEARCH_URL); mReturnResult = intent.getBooleanExtra(RETURN_RESULT, false); mIsUser = intent.getBooleanExtra(IS_USER, false); ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowCustomEnabled(true); LayoutInflater li = LayoutInflater.from(this); View customView = li.inflate(R.layout.taxon_search_action_bar, null); actionBar.setCustomView(customView); actionBar.setLogo(R.drawable.ic_arrow_back); setContentView(R.layout.taxon_search); mNoResults = (TextView) findViewById(android.R.id.empty); mNoResults.setVisibility(View.GONE); mProgress = (ProgressBar) findViewById(R.id.progress); mProgress.setVisibility(View.GONE); mSearchEditText = (EditText) customView.findViewById(R.id.search_text); if (savedInstanceState == null) { mAdapter = new ProjectsAdapter(this, mSearchUrl, this, new ArrayList<JSONObject>(), mIsUser ? R.drawable.ic_account_circle_black_48dp : R.drawable.ic_work_black_24dp, mIsUser); } else { mSearchString = savedInstanceState.getString("mSearchString"); mSearchEditText.setText(mSearchString); mAdapter = new ProjectsAdapter(this, mSearchUrl, this, loadListFromBundle(savedInstanceState, "mProjects"), mIsUser ? R.drawable.ic_account_circle_black_48dp : R.drawable.ic_work_black_24dp, mIsUser); } if (mHintText != null) mSearchEditText.setHint(mHintText); mSearchEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(final CharSequence s, int start, int before, int count) { if (!s.toString().equals(mSearchString)) { mSearchString = s.toString(); if (mAdapter != null) ((Filterable) mAdapter).getFilter().filter(s); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); setListAdapter(mAdapter); getListView().setOnItemClickListener(this); } public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) { String item = (String) v.getTag(); if (item != null) { if (mReturnResult) { // Return the selected result instead of opening up a viewer Intent data = new Intent(); data.putExtra(RESULT, item); setResult(RESULT_OK, data); finish(); } else { Intent intent = new Intent(this, mViewerActivity); intent.putExtra(mViewerActivityParamName, item); startActivity(intent); } } } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } private ListView mListView; protected ListView getListView() { if (mListView == null) { mListView = (ListView) findViewById(android.R.id.list); } return mListView; } protected void setListAdapter(ListAdapter adapter) { getListView().setAdapter(adapter); } @Override public void onLoading(final Boolean isLoading, final int count) { runOnUiThread(new Runnable() { @Override public void run() { if (isLoading) { getListView().setVisibility(View.GONE); mProgress.setVisibility(View.VISIBLE); mNoResults.setVisibility(View.GONE); } else { mProgress.setVisibility(View.GONE); getListView().setVisibility(View.VISIBLE); if (count == 0) { mNoResults.setVisibility(View.VISIBLE); } else { mNoResults.setVisibility(View.GONE); } } } }); } @Override protected void onSaveInstanceState(Bundle outState) { saveListToBundle(outState, mAdapter.getItems(), "mProjects"); outState.putString("mSearchString", mSearchString); super.onSaveInstanceState(outState); } private void saveListToBundle(Bundle outState, List<JSONObject> list, String key) { if (list != null) { JSONArray arr = new JSONArray(list); outState.putString(key, arr.toString()); } } private List<JSONObject> loadListFromBundle(Bundle savedInstanceState, String key) { List<JSONObject> results = new ArrayList<JSONObject>(); String obsString = savedInstanceState.getString(key); if (obsString != null) { try { JSONArray arr = new JSONArray(obsString); for (int i = 0; i < arr.length(); i++) { results.add(arr.getJSONObject(i)); } return results; } catch (JSONException exc) { exc.printStackTrace(); return null; } } else { return null; } } }
[ "budowski@gmail.com" ]
budowski@gmail.com
bb463bb30d3a4bc08227a4182ca6944fe07deebb
4a1f36f8fc27a89a96465ca92aa04310e10d8197
/referencedemo/src/androidTest/java/com/example/referencedemo/ExampleInstrumentedTest.java
8709ee0a30124b893176a82cabd91802ab0bf9cd
[]
no_license
suming77/AndroidOptimizeDemo
ef32e5489c1940aad7a8f6cc486b969a21dd4804
e864ef6a2a33ef6bfa1258d1481ed3fcdb76f819
refs/heads/master
2022-03-23T10:28:27.501715
2019-12-04T02:58:43
2019-12-04T02:58:43
219,743,030
1
0
null
null
null
null
UTF-8
Java
false
false
734
java
package com.example.referencedemo; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.referencedemo", appContext.getPackageName()); } }
[ "296099391@qq.com" ]
296099391@qq.com
0dc425530cf9827ea91e4b493df5485de6912e4c
2bd28cff509ddd91cd689f3b2bcb2f64c5799335
/app/src/androidTest/java/com/example/pannam/transitiondemo/ApplicationTest.java
a33c4633801219370a3eed9c684ff290a7f292fd
[]
no_license
jesussmile/TransitionDemo
1435ae0b94846c7946c15354af1ca982771e4b04
a7cd71fa8c1298458461f75e24d28e557ffa090e
refs/heads/master
2021-01-10T09:05:39.762017
2016-03-03T14:13:09
2016-03-03T14:13:09
53,054,880
0
0
null
null
null
null
UTF-8
Java
false
false
364
java
package com.example.pannam.transitiondemo; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
[ "pullbackwild@gmail.com" ]
pullbackwild@gmail.com
bc49748da634f35907f560405df66e7bcace60f0
eba8039e7eda13119fb73249685711d08698c809
/src/main/java/com/smt/kata/code/MagicSigil.java
2b1d52a2f13ff3ed9e61960129b0ac396a62adc6
[ "MIT" ]
permissive
balasmt/Daily-Kata
d7569589bded9ea9c3e47c66ad085e3148524042
6cfc73003f3eb73c9493e363db53abc611b50f78
refs/heads/main
2023-03-12T16:58:57.379628
2021-03-01T00:35:01
2021-03-01T00:35:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,294
java
package com.smt.kata.code; /**************************************************************************** * <b>Title</b>: MagicSigil.java * <b>Project</b>: SMT-Kata * <b>Description: </b> A magic sigil is a glyph which represents a desire one wishes * to manifest in their lives. There are many ways to create a sigil, but the * most common is to write out a specific desire (e.g. "I HAVE WONDERFUL FRIENDS WHO LOVE ME"), * remove all vowels and spaces, remove any duplicate letters (keeping the last occurence), * and then design a glyph from what remains. Using the sentence above as an example, * we would remove duplicate letters: * AUFRINDSWHLOVME * And then remove all vowels, leaving us with: * FRNDSWHLVM * Create a method that takes a string and removes its vowels and duplicate letters. * The returned string should not contain any spaces and be in uppercase. * * <b>Copyright:</b> Copyright (c) 2021 * <b>Company:</b> Silicon Mountain Technologies * * @author James Camire * @version 3.0 * @since Jan 5, 2021 * @updates: ****************************************************************************/ public class MagicSigil { /** * Sigilize the word * @param word * @return */ public String sigilize(String word) { return ""; } }
[ "james@siliconmtn.com" ]
james@siliconmtn.com
6481aedcab86919ba2177f96fa445f751c699641
02467552f089356e015e0631599f5ee0869bce9f
/SudokuGame/View/src/main/java/org/compprog/SecondaryController.java
272443d713658b1e445f10c70c0e24f46376b173
[]
no_license
wojtas112/SudokuGame
37e9e4b33a03a4cce32e28cb599a89422f1b5831
112a97c8b30add060de26b10541d551b4e5fee81
refs/heads/main
2023-06-02T00:33:03.591943
2021-06-15T11:12:26
2021-06-15T11:12:26
377,134,719
0
0
null
null
null
null
UTF-8
Java
false
false
3,068
java
package org.compprog; import java.io.IOException; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.layout.GridPane; import javafx.scene.text.Font; import org.cp.model.DataAccess.Dao; import org.cp.model.DataAccess.SudokuBoardDaoFactory; import org.cp.model.Models.SudokuBoard; import org.cp.model.Solver.BackTrackSudokuSolver; public class SecondaryController { public GridPane sudokuBoardGrid; private SudokuBoard sudoku; @FXML public void fillGrid() { for (int col = 0; col < 9; col++) { for (int row = 0; row < 9; row++) { createTextField(row, col); } } //sudoku.display(); } private void createTextField(int col, int row) { TextField textField = new TextField(); textField.setMinSize(50,50); textField.setFont(Font.font(18)); // restrict input to integers: textField.setTextFormatter(new TextFormatter<Integer>(c -> { if (c.getControlNewText().matches("\\d?")) { return c ; } else { return null ; } })); if(sudoku.get(row, col) != 0) { textField.setText(String.valueOf(sudoku.get(row,col))); //textField.setDisable(true); } sudokuBoardGrid.add(textField, col, row); } @FXML private void initialize() { BackTrackSudokuSolver solver = new BackTrackSudokuSolver(); sudoku = new SudokuBoard(new int[9][9], solver); sudoku.solveGame(); DifficultyLevel lvl = new DifficultyLevel(); sudoku = lvl.chooseDifficulty(App.getLevel(), sudoku); fillGrid(); } public Node getNodeByRowColumnIndex(final int row,final int column,GridPane gridPane) { Node result = null; ObservableList<Node> childrens = gridPane.getChildren(); for(Node node : childrens) { if(gridPane.getRowIndex(node) == row && gridPane.getColumnIndex(node) == column) { result = node; break; } } return result; } @FXML private void save() throws Exception { Dao<SudokuBoard> d = SudokuBoardDaoFactory.getFileDao("SudokuBoardFile"); for(int i = 0; i<9; i++) { for(int j=0; j<9; j++) { String fieldValue = ((TextField) sudokuBoardGrid .getChildren().get(i* 9 + j)).getText(); if(!fieldValue.equals(String.valueOf(sudoku.get(i, j))) && !fieldValue.equals("")) { sudoku.set(i,j,Integer.parseInt(fieldValue)); } } } d.write(sudoku); } @FXML private void load() throws Exception { Dao<SudokuBoard> d = SudokuBoardDaoFactory.getFileDao("SudokuBoardFile"); sudoku = d.read(); sudokuBoardGrid.getChildren().removeAll(); fillGrid(); } }
[ "65348511+wojtas112@users.noreply.github.com" ]
65348511+wojtas112@users.noreply.github.com
c511f3e4ce3ce6c80ed014e9761be19a59d7ffa8
7d6e49fa14c92522e48c9b1f5860e11cb1557253
/Sample Workspace 1.8/Acme BnB/src/main/java/services/AuditorService.java
b1da92372bac856cad6deae2e6665977cce0b4e0
[]
no_license
joslopcan/DT-AcmeBnB
aee67144b34f8f504970257fb214186fbc45e3b7
92168758d28e138bd16f969764edd3d41475d5d5
refs/heads/master
2021-01-12T18:35:30.143193
2017-02-17T11:50:09
2017-02-17T11:50:09
81,348,177
0
0
null
null
null
null
UTF-8
Java
false
false
1,200
java
package services; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import repositories.AuditorRepository; import domain.Auditor; @Service @Transactional public class AuditorService { @Autowired private AuditorRepository auditorRepository; public AuditorService() { super(); } // Simple CRUD methods ---------------------------------------------------- public Auditor create() { Auditor result; result = new Auditor(); return result; } public Collection<Auditor> findAll() { Collection<Auditor> result; result = auditorRepository.findAll(); Assert.notNull(result); return result; } public Auditor findOne(int auditorId) { Auditor result; result = auditorRepository.findOne(auditorId); return result; } public void save(Auditor auditor) { Assert.notNull(auditor); auditorRepository.save(auditor); } public void delete(Auditor auditor) { Assert.notNull(auditor); Assert.isTrue(auditor.getId() != 0); auditorRepository.delete(auditor); } }
[ "joslopcan@alum.us.es" ]
joslopcan@alum.us.es
8286b2ee24e6c6f1446ffc42bf535941bd104b0e
5ee062b1fe1fcfd1b356c7e193314798284be16e
/app/src/main/java/com/zhanghao/gankio/ui/adapter/SearchResultAdapter.java
f5d7c5580c4b9ccd8c1a8f037ba0cdb46b35f896
[]
no_license
mask-hao/MyGank
2ffc1099805396979ebc278ce2abae37fed8fb9a
e6714bb3c49307626948be885fdac64aed63733b
refs/heads/master
2021-01-20T16:17:13.089629
2017-07-03T12:52:55
2017-07-03T12:52:55
90,830,111
103
16
null
null
null
null
UTF-8
Java
false
false
936
java
package com.zhanghao.gankio.ui.adapter; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.zhanghao.gankio.R; import com.zhanghao.gankio.entity.GankSearchItem; import java.util.List; /** * Created by zhanghao on 2017/5/5. */ public class SearchResultAdapter extends BaseQuickAdapter<GankSearchItem,BaseViewHolder>{ private static final String TAG = "SearchResultAdapter"; public SearchResultAdapter(int layoutResId, List<GankSearchItem> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, GankSearchItem item) { String who=item.getWho(); String type=item.getType(); String title=item.getTitle(); helper.setText(R.id.gank_search_title_tv,title); helper.setText(R.id.gank_search_who_tv,who); helper.setText(R.id.gank_search_type_tv,type); } }
[ "281079145@qq.com" ]
281079145@qq.com
30a6a11510a5e8d1c7580db3b7723700b3dfa6f8
e1095749b78bb767a8fe558e46ba0b7010ebd547
/src/main/java/com/robertx22/mine_and_slash/loot/generators/SkillGemLootGen.java
52c2ed1fd3b739bbf3bb1cf18979d6511cbdd00d
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
RobertSkalko/Mine-and-Slash
6d1148fa3e626311c2238d314f8c6c5e30c7c00c
e16832ccd7ffc438b562202ecde39a324732d7f5
refs/heads/1.15
2023-07-03T18:47:05.628869
2020-07-17T21:40:02
2020-07-17T21:40:02
113,667,576
44
41
NOASSERTION
2022-10-28T01:56:01
2017-12-09T12:28:35
Java
UTF-8
Java
false
false
937
java
package com.robertx22.mine_and_slash.loot.generators; import com.robertx22.mine_and_slash.config.forge.ModConfig; import com.robertx22.mine_and_slash.loot.LootInfo; import com.robertx22.mine_and_slash.loot.blueprints.SkillGemBlueprint; import com.robertx22.mine_and_slash.uncommon.enumclasses.LootType; import net.minecraft.item.ItemStack; public class SkillGemLootGen extends BaseLootGen<SkillGemBlueprint> { public SkillGemLootGen(LootInfo info) { super(info); } @Override public float baseDropChance() { return ModConfig.INSTANCE.DropRates.SKILL_GEM_DROPRATE.get() .floatValue(); } @Override public LootType lootType() { return LootType.SkillGem; } @Override public ItemStack generateOne() { SkillGemBlueprint blueprint = new SkillGemBlueprint(info.level); ItemStack stack = blueprint.createStack(); return stack; } }
[ "treborx555@gmail.com" ]
treborx555@gmail.com
a00b5e622fa8fc1685e0ffa68d6e6d8e97dccdf6
dcaf2afa5781a9c9f47cdc6daabfb62581f17765
/src/problem23.java
cec6709778c8ec6790e6b64fb9c0c99dc31fdfbc
[]
no_license
tharindukumara/project-euler-java
e637540a471c9aa54cfb61ab1e7587f2abe8255c
bcd482ffd4903eb32c3e093427494a4ee90292f3
refs/heads/master
2021-05-28T23:16:28.618038
2015-05-30T10:00:30
2015-05-30T10:00:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,343
java
import java.math.BigInteger; import java.util.Vector; public class problem23{ public static void main(String[] args) { tree tob = new tree(); long begin = System.currentTimeMillis(); int[] abNum = new int[7000]; int a=0; for(int i=1;i<28123;i++){ if(i<divisors(i)){ abNum[a] = i; a++; } } System.out.println(abNum[10]); long sum=0; for(int i=0;i<abNum.length;i++){ for(int j=i;j<abNum.length;j++){ if(abNum[i]+abNum[j] <28123) tob.insert(Integer.toString(abNum[i]+abNum[j])); } } System.out.println(sum); int b=0; long sum2=0; while(b<28123){ sum2 += b; b++; } System.out.println(sum2); long end = System.currentTimeMillis(); System.out.println(end-begin+"ms"); } public static long divisors(int n){ long sum=0; for(int i=1;i<n;i++){ if(n%i==0) sum += i; } return sum; } } class nodee{ public String element; public nodee left; public nodee right; public nodee(){ element = null; left = null; right = null; } public nodee(String s){ element = s; left = null; right = null; } public nodee(String s , nodee l){ element = s; left = l; right = null; } public nodee(String s , nodee l , nodee r){ element = s; left = l; right = r; } } class treee{ int i=0; int j=0; long sum=0; nodee root; nodee cur; public treee(){ root = new nodee(); } public boolean isEmpty(nodee t){ return t==null; } public void insert(nodee b , String s){ if(s.compareTo(b.element)==0){ } else if(s.compareTo(b.element)<0){ if(b.left != null){ insert(b.left , s); } else{ b.left = new nodee(s); } } else if(s.compareTo(b.element)>0){ if(b.right != null) insert(b.right , s); else{ b.right = new nodee(s); } } } public void insert(String s){ if(root.left!=null){ insert(root.left , s); } else{ root.left = new nodee(s); } } public void printInOrder(nodee t){ if(t.left != null){ printInOrder(t.left); } sum += Long.parseLong(t.element); if(t.right != null){ printInOrder(t.right); } } public void printInOrder(){ printInOrder(root.left); } }
[ "zonik.hatkumara@gmail.com" ]
zonik.hatkumara@gmail.com
a3dfe21ba58a268660547af3f76796e6752e51b1
033c04a6b631ee9e3409ae4d4f2944da3f169d98
/sph/physical/equation/math/VecTool.java
db7f0f46de5923af906bafbb195a476c6c4cd83c
[]
no_license
JustLikeSprite/MySPH
230afd417713d1bef5cd9542c12b7a0d1df45025
6c5234ce6e82316410e0a69c34b33fa66e70eefb
refs/heads/master
2023-03-25T19:57:54.399816
2021-03-28T04:14:09
2021-03-28T04:14:09
352,226,597
0
0
null
null
null
null
UTF-8
Java
false
false
1,920
java
package physical.equation.math; public class VecTool { public static double[] vecAdd(double[] vec1, double[] vec2) { double[] ans = new double[2]; ans[0] = vec1[0] + vec2[0]; ans[1] = vec1[1] + vec2[1]; return ans; } public static double[] vecSub(double[] vec1, double[] vec2) { double[] ans = new double[2]; ans[0] = vec1[0] - vec2[0]; ans[1] = vec1[1] - vec2[1]; return ans; } public static double[] vecMul(double[] vec1, double x) { double[] ans = new double[2]; ans[0] = vec1[0] * x; ans[1] = vec1[1] * x; return ans; } public static double calcDist2(double[] vec) { double a = vec[0] * vec[0]; double b = vec[1] * vec[1]; return a + b; } public static double vecDot(double[] vec1, double[] vec2) { double a = vec1[0] * vec2[0]; double b = vec1[1] * vec2[1]; return a + b; } public static double calcDist(double[] vec) { double a = vec[0] * vec[0]; double b = vec[1] * vec[1]; return Math.sqrt(a + b); } public static double[][] deviatoric(double[][] matrix) { matrix[0][0]=0.5*(matrix[0][0]-matrix[1][1]); matrix[1][1]=0.5*(matrix[1][1]-matrix[0][0]); return matrix; } public static double[] scalarMul(double k,double[] vec) { double[] ans=new double[2]; ans[0]=k*vec[0]; ans[1]=k*vec[1]; return ans; } public static double[][] transpose(double[][] matrix) { double[][] ans=new double[2][2]; ans[1][0]=matrix[0][1]; ans[0][1]=matrix[1][0]; ans[1][1]=matrix[1][1]; ans[0][0]=matrix[0][0]; return ans; } public static double[][] matrixproduct(double[][] a, double[][] b) { int y = a.length; int x = b[0].length; double c[][] = new double[y][x]; for (int i = 0; i < y; i++) { for (int j = 0; j < x; j++) { for (int k = 0; k < b.length; k++) { c[i][j] += a[i][k] * b[k][j]; } } } return c; } }
[ "mingyi137@qq.com" ]
mingyi137@qq.com
b05db640e62409cf6119389d850a54de86295fc1
f3d3c009823a9a40e68f219df08131e6edf3b560
/Java_0427单例模式/ThreadDemo18.java
7c7567c384cf2c189f502206353e04b4e0b6f11a
[]
no_license
upupoo00/Project
5706fd46f6523f189d59d358b60a18c22ba23976
9a08fb4fd4cc79ad1d8592f0b53041fcd623ffb4
refs/heads/master
2023-06-23T16:11:49.640527
2021-07-13T09:25:04
2021-07-13T09:25:11
350,588,831
1
0
null
null
null
null
UTF-8
Java
false
false
1,685
java
package Java_0427单例模式; public class ThreadDemo18 { //懒汉模式来实现,Singleton类被加载的时候,不会立刻实例化 //等到第一次使用这个实例的时候再实例化 static class Singleton{ private Singleton(){ } //加volatile保持内存可见性 private volatile static Singleton instance = null; /** * 类加载的时候,没有立即实例化 * 第一次调用getInstance的时候,才真的实例化。 * 如果要是代码一整场都没有调用getInstance * 此时实例化的过程也就被省略掉了 * * "延时加载" * * 我们一般认为"懒汉模式"比"饿汉模式"效率更高 * 懒汉模式有很大的可能是"实例用不到",此时就节省了实例化的开销 * */ public static Singleton getInstance(){ //懒汉模式是线程不安全的,这样加锁可以保证线程安全,或者加在当前方法之前 //虽然两种写法都ok,认为写在里面的写法,粒度更小,写在方法之前,锁粒度更大 //粒度:锁中包含的代码越多,就认为粒度越大 //一般写代码的时候,都希望锁粒度小一点比较好 //锁的粒度越大,说明这段代码的并发能力就越受限 if (instance == null) { synchronized (Singleton.class) { if(instance == null){ instance = new Singleton(); } } } return instance; } } }
[ "upupoo0@163.com" ]
upupoo0@163.com
2cc81410550b6d40413b9c8a36fde23eb715be59
f705ebdebebbfa681292e2d6b38c896503a255bb
/src/main/java/com/demo/bookstore/service/daoservice/OrderDAOService.java
7df34a8e5aafa2d44967c729e3b6e50698d67a38
[]
no_license
Deepongpat/Bookstore
e8ed99ce80cf31f56c1ec83556949e557bb2bda2
344fd94c90994a7673d94853549f4a007a17c489
refs/heads/master
2020-08-08T04:05:10.480231
2019-10-15T00:22:32
2019-10-15T00:22:32
213,706,608
0
0
null
null
null
null
UTF-8
Java
false
false
1,243
java
package com.demo.bookstore.service.daoservice; import java.util.Collection; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.demo.bookstore.model.Book; import com.demo.bookstore.model.order.OrderBook; import com.demo.bookstore.model.order.OrderRequest; import com.demo.bookstore.repo.OrderRepository; @Repository @Transactional public class OrderDAOService { @PersistenceContext private EntityManager entityManager; @Autowired private OrderRepository orderRepository; public void insert(String username, int bookId) { OrderBook order = new OrderBook(); order.setBookid(bookId); order.setUsername(username); entityManager.persist(order); } public List<OrderBook> findByUsername(String username) { List<OrderBook> listOrder = orderRepository.findByUsername(username); return listOrder; } public void removeByUsername(String username) { List<OrderBook> listOrder = orderRepository.findByUsername(username); orderRepository.deleteAll(listOrder); } }
[ "whpongpat@gmail.com" ]
whpongpat@gmail.com
831eeec0d7f6c3a8fa08b53b88d860a01c87ffe4
af35a2ef1c2d051e2ce133f751511109b4b67b5d
/Assignment8.java
37b8b12830ed35d0d1dbeb4d5d93697c3eed1913
[]
no_license
Karthiga-web/Selenium
b5e3371c1b0a4d6386b96704ce5e3335d1071607
d64f586d27db8227ae376cb901f5325c7351177c
refs/heads/master
2023-05-05T06:48:57.346435
2021-05-21T16:47:22
2021-05-21T16:47:22
365,335,988
0
0
null
null
null
null
UTF-8
Java
false
false
1,029
java
package Edureka; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Assignment8 { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\grkar\\OneDrive\\Documents\\Selenium\\chromedriver_win32\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.navigate().to("https://www.rahulshettyacademy.com/AutomationPractice/"); driver.findElement(By.id("autocomplete")).sendKeys("Uni"); Thread.sleep(2000); List<WebElement> list = driver.findElements(By.className("ui-menu-item")); list.forEach(text->{ if(text.getText().toLowerCase().equalsIgnoreCase("United States (USA)")) { text.click(); System.out.println(text.getText()); } }); } }
[ "kar07091995@gmail.com" ]
kar07091995@gmail.com
3dcee075c5652e7440d793fc8997a16f0b5b8087
96094412219913aafb26a5bbbae7885c54bfe617
/app/src/androidTest/java/com/lomaikai/moreuielements/ExampleInstrumentedTest.java
4678c25109abad9a22f089add95e6df6f3701032
[]
no_license
ianchai/ListViewExample
b2a4cd93132b7d8ccf872401518a13cdc6089984
be1dc9ad5e079c022348b044fa0d1d7493d8becd
refs/heads/master
2023-03-07T15:37:34.778849
2021-02-18T04:30:20
2021-02-18T04:30:20
339,934,352
0
0
null
null
null
null
UTF-8
Java
false
false
768
java
package com.lomaikai.moreuielements; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.lomaikai.moreuielements", appContext.getPackageName()); } }
[ "ianchai@mmu.edu.my" ]
ianchai@mmu.edu.my
98dc36d525e81603219b3a125496120bec330159
26b14da13b52f669b93335c377f7821900e64812
/src/main/java/com/ai/design/AbstractFactory/IProduct.java
aa57eaeff1c38af815601eb6c86d893399479bc8
[]
no_license
Johnwxg/design
ef32135288cc16ab167b4d228dc9623d4a1f06d2
e36bf459ee0d1d95bf68ae7fc413690496ba8712
refs/heads/master
2022-07-10T22:10:12.105347
2019-08-01T01:29:08
2019-08-01T01:29:08
199,422,496
0
0
null
2022-06-17T02:20:30
2019-07-29T09:32:26
Java
UTF-8
Java
false
false
264
java
package com.ai.design.AbstractFactory; /** * @Auther: wxg * @Date: 2019/7/25 15:44 * @Description: 产品接口 */ public interface IProduct { /** * 产品类型的公共方法 * @return 返回产品信息 */ String getInformation(); }
[ "wangxg5@asiainfo.com" ]
wangxg5@asiainfo.com
a77807766c7535cd9522a60a6b4a1b05ad37554b
037f5ac44b36921ab2cb7c1927cf38de608b67a8
/src/test/java/io/crazy88/beatrix/e2e/bonus/dto/Amount.java
86becd0fa6286eaab7c5d908e8bd9b5e0d6e7222
[]
no_license
jerlosam/b-cms-integration
4168c800b6104ca4045232d3665d3aa3e01713d9
02318ac6d9eff56c5b84bc0b4c0b603536e9302c
refs/heads/master
2020-03-30T23:00:36.879550
2018-10-05T07:55:13
2018-10-05T07:55:13
151,687,307
0
0
null
null
null
null
UTF-8
Java
false
false
197
java
package io.crazy88.beatrix.e2e.bonus.dto; import lombok.Builder; import lombok.Value; import java.math.BigDecimal; @Value @Builder public class Amount { String type; BigDecimal value; }
[ "jerlosam@gmail.com" ]
jerlosam@gmail.com
4ffb7d6925f6fbd0df672a15ae20e8e5e85a15db
dbfee90cb3646b4eaecd32d5ff5956d84c61c3ce
/FONTS/Presentacio/package-info.java
19d6386330a0c33edf54e4c8af56257cfc76ee5c
[]
no_license
omarkass/Program-to-solve-chess-problems-programed-in-JAVA
808ad508350a582ab47d7b5f351299f2147e9a7b
0e695815c498618cbe548ed69467902d1cf8faa3
refs/heads/master
2020-07-08T08:37:00.272086
2019-08-21T16:24:04
2019-08-21T16:24:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
61
java
/** * */ /** * @author albert * */ package Presentacio;
[ "omarelkassar8@gmail.com" ]
omarelkassar8@gmail.com
ec46ffa714d8edb2a9bc22e7be5e9f7624b0acf7
bf6f529837021223112bf0279b036f23cdca28a1
/src/main/java/net/mcreator/wolfforceegraddons/WOLFforceIgniteaddons.java
4539f91ce85b3f60f485de355f4b4df2b0a5da88
[]
no_license
enderman945/WOLFforce-Ignite-Addons
85d9b226200c5216c3f26a3e6abd0b3f342ae10a
8ca79e561d23d2e23681dc25b34554d5d2b5d06d
refs/heads/master
2023-04-08T13:02:29.623327
2021-04-05T07:27:45
2021-04-05T07:27:45
353,810,899
0
0
null
null
null
null
UTF-8
Java
false
false
4,979
java
/* * MCreator note: * * If you lock base mod element files, you can edit this file and the proxy files * and they won't get overwritten. If you change your mod package or modid, you * need to apply these changes to this file MANUALLY. * * Settings in @Mod annotation WON'T be changed in case of the base mod element * files lock too, so you need to set them manually here in such case. * * Keep the ElementsWOLFforceIgniteaddons object in this class and all calls to this object * INTACT in order to preserve functionality of mod elements generated by MCreator. * * If you do not lock base mod element files in Workspace settings, this file * will be REGENERATED on each build. * */ package net.mcreator.wolfforceegraddons; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.EntityEntry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraft.world.biome.Biome; import net.minecraft.potion.Potion; import net.minecraft.item.Item; import net.minecraft.block.Block; import java.util.function.Supplier; @Mod(modid = WOLFforceIgniteaddons.MODID, version = WOLFforceIgniteaddons.VERSION) public class WOLFforceIgniteaddons { public static final String MODID = "wolfforceigniteaddons"; public static final String VERSION = "v 1.0"; public static final SimpleNetworkWrapper PACKET_HANDLER = NetworkRegistry.INSTANCE.newSimpleChannel("wolfforceigniteadd:a"); @SidedProxy(clientSide = "net.mcreator.wolfforceegraddons.ClientProxyWOLFforceIgniteaddons", serverSide = "net.mcreator.wolfforceegraddons.ServerProxyWOLFforceIgniteaddons") public static IProxyWOLFforceIgniteaddons proxy; @Mod.Instance(MODID) public static WOLFforceIgniteaddons instance; public ElementsWOLFforceIgniteaddons elements = new ElementsWOLFforceIgniteaddons(); @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { MinecraftForge.EVENT_BUS.register(this); GameRegistry.registerWorldGenerator(elements, 5); GameRegistry.registerFuelHandler(elements); NetworkRegistry.INSTANCE.registerGuiHandler(this, new ElementsWOLFforceIgniteaddons.GuiHandler()); elements.preInit(event); MinecraftForge.EVENT_BUS.register(elements); elements.getElements().forEach(element -> element.preInit(event)); proxy.preInit(event); } @Mod.EventHandler public void init(FMLInitializationEvent event) { elements.getElements().forEach(element -> element.init(event)); proxy.init(event); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(event); } @Mod.EventHandler public void serverLoad(FMLServerStartingEvent event) { elements.getElements().forEach(element -> element.serverLoad(event)); proxy.serverLoad(event); } @SubscribeEvent public void registerBlocks(RegistryEvent.Register<Block> event) { event.getRegistry().registerAll(elements.getBlocks().stream().map(Supplier::get).toArray(Block[]::new)); } @SubscribeEvent public void registerItems(RegistryEvent.Register<Item> event) { event.getRegistry().registerAll(elements.getItems().stream().map(Supplier::get).toArray(Item[]::new)); } @SubscribeEvent public void registerBiomes(RegistryEvent.Register<Biome> event) { event.getRegistry().registerAll(elements.getBiomes().stream().map(Supplier::get).toArray(Biome[]::new)); } @SubscribeEvent public void registerEntities(RegistryEvent.Register<EntityEntry> event) { event.getRegistry().registerAll(elements.getEntities().stream().map(Supplier::get).toArray(EntityEntry[]::new)); } @SubscribeEvent public void registerPotions(RegistryEvent.Register<Potion> event) { event.getRegistry().registerAll(elements.getPotions().stream().map(Supplier::get).toArray(Potion[]::new)); } @SubscribeEvent public void registerSounds(RegistryEvent.Register<net.minecraft.util.SoundEvent> event) { elements.registerSounds(event); } @SubscribeEvent @SideOnly(Side.CLIENT) public void registerModels(ModelRegistryEvent event) { elements.getElements().forEach(element -> element.registerModels(event)); } static { FluidRegistry.enableUniversalBucket(); } }
[ "guillem@XPC-BUREAU" ]
guillem@XPC-BUREAU
60cad71d41bfb4f84095e11fda199ba359a9345a
97c95a5d8e1281a5f839d4ae83bf1f250092f45e
/build-tmp/source/OriginalFractal.java
b23203f925e0ce67f16b1090ab6ba36f4565f711
[]
no_license
goliathUros/OriginalFractal
dfbae4cd5a2307ab9d32baab00b224a236e47a80
e5f0cdb659b355eafbae2f3a1a18099442abc78b
refs/heads/gh-pages
2020-04-01T14:25:21.816002
2015-02-03T22:47:28
2015-02-03T22:47:28
29,981,172
0
0
null
2015-01-28T18:16:00
2015-01-28T18:15:59
JavaScript
UTF-8
Java
false
false
1,306
java
import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class OriginalFractal extends PApplet { public void setup() { size(600, 600); frameRate(5); } public void draw() { background(0); noFill(); recurse(width/2, height/2, 550); recurse(width/4, height/4, 200); recurse(width/4, 3*height/4, 200); recurse(3*width/4, height/4, 200); recurse(3*width/4, 3*height/4, 200); recurse(width/2, height/4, 200); recurse(width/2, 3*height/4, 200); recurse(width/4, height/2, 200); recurse(3*width/4, height/2, 200); } public void recurse(int x, int y, double rads) { stroke((int)(Math.random()*255)+100, (int)(Math.random()*255)+100, (int)(Math.random()*255)+100); ellipse(x, y, (float)rads, (float)rads); if(rads > 10) { recurse(x, y, rads/1.3f); } } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "OriginalFractal" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
[ "dayi@697-334-Lorien.sf.k12.internal" ]
dayi@697-334-Lorien.sf.k12.internal
a58c75c2631f794cdc4eae3229c27c1219b26f7f
c24500d8058cf7591203f3aaa045179de5290f21
/src/persistencia/DAOFormulario.java
36d8911ddd8a20a81f7f0e2a9adf996f581b7148
[]
no_license
sdsuy/IAgro
7c169ab8d16c6437b640f34b8c7cdf52aa81514a
756e936c834243cf6ab376d643b16154e648faad
refs/heads/master
2023-01-04T18:39:19.836670
2020-10-24T23:17:37
2020-10-24T23:17:37
293,594,272
0
0
null
null
null
null
UTF-8
Java
false
false
5,514
java
package persistencia; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import entidades.Formulario; import entidades.Usuario; public class DAOFormulario { private static Connection conexion = DatabaseManager.getConexion(); private static final String INSERT_FORMULARIO = "INSERT INTO FORMULARIO (ID_FORMULARIO,ID_USUARIO,MET_MUESTREO,EQUIPAMIENTO,NOM_FORMULARIO," + "RESUMEN,DEPARTAMENTO,FECHA,ZONA,TIP_MUESTREO,GEOPUNTO,LOCALIDAD,EST_MUESTREO) VALUES (SEQ_ID_FORMULARIO.NEXTVAL,?,?,?,?,?,?,?,?,?,?,?,?)"; private static final String DELETE_FORMULARIO = "DELETE FROM FORMULARIO SET ID_FORMULARIO=?"; private static final String UPDATE_FORMULARIO = "UPDATE FORMULARIO SET MET_MUESTREO = ?,EQUIPAMIENTO = ?,NOM_FORMULARIO = ?,\"\n" + " + \"RESUMEN = ?,DEPARTAMENTO = ?,FECHA = ?,ZONA = ?,TIP_MUESTREO = ?,GEOPUNTO = ?,LOCALIDAD = ?,EST_MUESTREO = ? WHERE ID_FORMULARIO = ?"; private static final String ALL_FORMULARIO = "SELECT * FROM FORMULARIO"; private static final String FIND_FORMULARIO = "SELECT * FROM FORMULARIO WHERE ID_FORMULARIO = ?"; //Insertar un formulario public static boolean nuevoFormulario(Formulario formulario) { try { PreparedStatement insertForm = conexion.prepareStatement(INSERT_FORMULARIO); insertForm.setInt(1, formulario.getUser().getId()); insertForm.setString(2, formulario.getMet_muestreo()); insertForm.setString(3, formulario.getEquipamiento()); insertForm.setString(4, formulario.getNom_formulario()); insertForm.setString(5, formulario.getResumen()); insertForm.setString(6, formulario.getDepartamento()); insertForm.setDate(7, formulario.getFecha()); insertForm.setString(8, formulario.getZona()); insertForm.setString(9, formulario.getTip_muestreo()); insertForm.setLong(10, formulario.getGeopunto()); insertForm.setString(11, formulario.getLocalidad()); insertForm.setString(12, formulario.getEst_muestreo()); int filasAgregadas = insertForm.executeUpdate(); return filasAgregadas>0; } catch (SQLException e) { e.printStackTrace(); } return false; } public static boolean deleteFormulario(int id) { try { PreparedStatement elimForm = conexion.prepareStatement(DELETE_FORMULARIO); elimForm.setInt(1, id); int retorno = elimForm.executeUpdate(); return retorno > 0; } catch (SQLException e) { e.printStackTrace(); } return false; } public static boolean updateForm(Formulario formulario) { try { PreparedStatement update = conexion.prepareStatement(UPDATE_FORMULARIO); update.setString(1, formulario.getMet_muestreo()); update.setString(2, formulario.getEquipamiento()); update.setString(3, formulario.getNom_formulario()); update.setString(4, formulario.getResumen()); update.setString(5, formulario.getDepartamento()); update.setDate(6, formulario.getFecha()); update.setString(7, formulario.getZona()); update.setString(8, formulario.getTip_muestreo()); update.setLong(9, formulario.getGeopunto()); update.setString(10, formulario.getLocalidad()); update.setString(11, formulario.getEst_muestreo()); int filasAgregadas = update.executeUpdate(); return filasAgregadas>0; } catch (SQLException e) { e.printStackTrace(); } return false; } public static Formulario findForm(int id) { Formulario form = new Formulario(); Usuario user = null; try { PreparedStatement find = conexion.prepareStatement(FIND_FORMULARIO); find.setInt(1, id); ResultSet rs = find.executeQuery(); if(rs.next()) { form.setId_formulario(rs.getInt("ID_FORMULARIO")); form.setMet_muestreo(rs.getString("MET_MUESTREO")); form.setEquipamiento(rs.getString("EQUIPAMIENTO")); form.setResumen(rs.getString("RESUMEN")); form.setDepartamento(rs.getString("DEPARTAMENTO")); form.setFecha(rs.getDate("FECHA")); form.setZona(rs.getString("ZONA")); form.setTip_muestreo(rs.getString("TIP_MUESTREO")); form.setGeopunto(rs.getLong("GEOPUNTO")); form.setLocalidad(rs.getString("LOCALIDAD")); form.setEst_muestreo(rs.getString("EST_MUESTREO")); //user.setId(rs.getInt("ID_USUARIO")); //form.setUser(user); } return form ; } catch (SQLException e) { e.printStackTrace(); } return null; } public static LinkedList<Formulario> allFormularios(){ LinkedList<Formulario> formularios = new LinkedList<>(); try { Statement st = conexion.createStatement(); ResultSet rs = st.executeQuery(ALL_FORMULARIO); while(rs.next()) { Usuario user = null; Formulario form = new Formulario(); form.setId_formulario(rs.getInt("ID_FORMULARIO")); form.setMet_muestreo(rs.getString("MET_MUESTREO")); form.setEquipamiento(rs.getString("EQUIPAMIENTO")); form.setResumen(rs.getString("RESUMEN")); form.setDepartamento(rs.getString("DEPARTAMENTO")); form.setFecha(rs.getDate("FECHA")); form.setZona(rs.getString("ZONA")); form.setTip_muestreo(rs.getString("TIP_MUESTREO")); form.setGeopunto(rs.getLong("GEOPUNTO")); form.setLocalidad(rs.getString("LOCALIDAD")); form.setEst_muestreo(rs.getString("EST_MUESTREO")); user.setId(rs.getInt("ID_USUARIO")); form.setUser(user); formularios.add(form); } } catch (SQLException e) { e.printStackTrace(); } return null; } }
[ "jose.madrid@estudiantes.utec.edu.uy" ]
jose.madrid@estudiantes.utec.edu.uy
51fc1a741fb1215f048e1fb0bc8eb193567d1a28
d00f3bb675c3f61423368ca681f86c332cb6811a
/src/main/java/com/example/javabasic/thread/exception_thread/CaptureUncaughtException.java
0db4ddde953c2862e8d0c6705675c01edf09812d
[]
no_license
Garcia111/javabasic
6a4a641089930dd3e2bafa0f734b9c09b12201a8
9a257cf1d22913aab0a2e245f0ee25914c652454
refs/heads/master
2022-06-25T12:44:46.307459
2020-09-14T15:00:25
2020-09-14T15:00:25
206,282,875
0
0
null
2022-06-21T02:15:30
2019-09-04T09:30:53
Java
UTF-8
Java
false
false
1,967
java
package com.example.javabasic.thread.exception_thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** * 此任务在执行的时候,会打印当前线程的异常捕获类,并抛出异常 */ class ExceptionThread2 implements Runnable { @Override public void run() { Thread t = Thread.currentThread(); System.out.println("run() by "+t); System.out.println("eh = "+t.getUncaughtExceptionHandler()); throw new RuntimeException(); } } /** * 异常捕获类,实现Thread.UncaughtExceptionHandler接口,覆盖其中的uncaughtExceptin()方法 */ class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{ /** * uncaughtException()方法捕获线程中逃逸的异常 * @param t * @param e */ @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("caught "+e); } } /** * 线程工厂,实现ThreadFacotry接口,在创建线程的时候,指定该线程的异常捕获类 */ class HandlerThreadFactory implements ThreadFactory{ @Override public Thread newThread(Runnable r) { System.out.println(this+" creating new Thread"); Thread t = new Thread(r); System.out.println("created "+t); //设置一个线程的异常捕获类 t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler()); System.out.println("eh="+t.getUncaughtExceptionHandler()); return t; } } public class CaptureUncaughtException{ public static void main(String[] args){ /** * 使用线程池和线程工厂创建线程,创建出的线程每个都有一个异常捕获类MyUncaughtExceptinHandler类 */ ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory()); exec.execute(new ExceptionThread2()); } }
[ "erya0923!" ]
erya0923!
ca8216c1ea3f75429e4c40b1071ca13abf610aed
c1c29016a32b334dbb16a262a7d89b1c4a572a6b
/StoreExample/android/app/src/main/java/com/storeexample/MainApplication.java
f46794778fbf98aeb0466ff245889053b7ad4a91
[]
no_license
lucasnvp/ReactNative-Redux-Store-Example
2688f34f333c8c0d6eb9df9dc2e3ed1700ac6dcb
3389729e469f743986346a39ab71683a722f512e
refs/heads/master
2021-08-23T00:57:14.762550
2017-12-02T01:07:02
2017-12-02T01:07:02
112,487,573
1
0
null
null
null
null
UTF-8
Java
false
false
1,048
java
package com.storeexample; import android.app.Application; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage() ); } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
[ "lucasnvp@gmail.com" ]
lucasnvp@gmail.com
fe7d9e5bc77d9c6bcf37403e953146e3e08fd345
a1edf63b9d2016676105d293081f4ff9a6eec1d1
/taotao_manager/taotao_manager_service/src/main/java/com/taotao/service/impl/ItemParamServiceImpl.java
52a95fa7d92b3858b46b498fadafbc1ecc371967
[]
no_license
lunzilunzi/taotao_parent
01c32ac56ae8ab7a5dd328126dd6f5f2711561db
f6dc33419048dddb64f72b530e28f856353bccbf
refs/heads/master
2021-01-19T22:24:32.043310
2017-05-25T06:56:28
2017-05-25T06:56:34
88,811,563
0
0
null
null
null
null
UTF-8
Java
false
false
2,191
java
package com.taotao.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.taotao.mapper.TbItemParamMapper; import com.taotao.pojo.EasyUIDataGridResult; import com.taotao.pojo.TbItemParam; import com.taotao.pojo.TbItemParamExample; import com.taotao.service.ItemParamService; import com.taotao.pojo.TaotaoResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; /** * 商品规格参数模板管理 */ @Service public class ItemParamServiceImpl implements ItemParamService { @Autowired private TbItemParamMapper itemParamMapper; @Override public TaotaoResult getItemParamByCid(long cid) { System.out.println("cid" + cid); TbItemParamExample example = new TbItemParamExample(); TbItemParamExample.Criteria criteria = example.createCriteria(); criteria.andItemCatIdEqualTo(cid); List<TbItemParam> list = itemParamMapper.selectByExampleWithBLOBs(example); // 判断是否查询到结果 if (list != null && list.size() > 0) { System.out.println("list不为空"); return TaotaoResult.ok(list.get(0)); } System.out.println("list为空"); return TaotaoResult.ok(); } @Override public TaotaoResult insertItemParm(TbItemParam itemParam) { // 补全pojo itemParam.setCreated(new Date()); itemParam.setUpdated(new Date()); // 插入到规格参数模板表 itemParamMapper.insert(itemParam); return TaotaoResult.ok(); } @Override public EasyUIDataGridResult getItemParamList(Integer page, Integer rows) { System.out.println("page :"+page+",rows: "+rows); // 查询商品规格列表 TbItemParamExample example = new TbItemParamExample(); // 分页处理 PageHelper.startPage(page, rows); List<TbItemParam> list = itemParamMapper.selectByExampleWithBLOBs(example); System.out.println("list.size : "+list.size()); // 创建一个返回值对象 EasyUIDataGridResult result = new EasyUIDataGridResult(); result.setRows(list); // 记录总条数 PageInfo<TbItemParam> pageInfo = new PageInfo<>(list); result.setTotal(pageInfo.getTotal()); return result; } }
[ "731978768@qq.com" ]
731978768@qq.com
8046d22d379b55dccebd88b1ae2ab4b0f0525660
fefc4ed7fb337eb2207519a345708d04b4b94385
/src/main/java/com/beverage/factory/model/Order.java
5920e49f24c085aa3f7cffeb4770ee56d915af0c
[]
no_license
sanketdomal/bevarage-factory-assign
d3e65ad73c4ca44b61e06f9d37fd92685d82d34f
e0c0e59b2431046a03d50d09da05428ba7a59d34
refs/heads/master
2021-05-23T01:08:24.822905
2020-04-05T06:07:21
2020-04-05T06:07:21
253,166,438
0
0
null
null
null
null
UTF-8
Java
false
false
643
java
package com.beverage.factory.model; import java.util.ArrayList; import java.util.List; public class Order { private List<String> orderItems; private double totalPrice; public Order() { // TODO Auto-generated constructor stub } public Order(ArrayList<String> orderItems, int price) { super(); this.orderItems = orderItems; this.totalPrice = price; } public List<String> getOrderItems() { return orderItems; } public void setOrderItems(List<String> orderItems) { this.orderItems = orderItems; } public double getPrice() { return totalPrice; } public void setPrice(double price) { this.totalPrice = price; } }
[ "sanketdml@gmail.com" ]
sanketdml@gmail.com
6fab00c8730c3edba8a6a8d63bd5140faf912685
91a33f84c2ef91b27853aa3f097bf1d07f4024f2
/11.x/src/StudentTest.java
b6b59eb9b32b797ec35444f5d61581b3a7adef15
[]
no_license
zyd16888/JavaLearn
8f63798be66f8b01f6b763ed87a4cd8804c40f51
cd372fa1851e0900420600df140bdbfbe19381f0
refs/heads/master
2022-01-17T02:49:54.849146
2019-05-18T04:47:25
2019-05-18T04:47:25
149,879,554
0
0
null
null
null
null
UTF-8
Java
false
false
387
java
/** * 描述: * 学生测试类 * * @author dong * @date 2018-10-09 8:45 */ public class StudentTest { public static void main(String[] args) { Student s1 = new Student("张三",23,74); Student s2 = new Student("张三1",23,74); s1.beSame(s2.getName()); s2.beSame(s1.getName(),s1.getAge()); s1.beSame(s2); s2.beSame(s1); } }
[ "zyd475182659@163.com" ]
zyd475182659@163.com
ae032ce5df8ba26996903820e1617e8b0d7c9acb
153d67bc6384574b00b4b07c2e1ed1bf829b3891
/server/mlb-gm/src/main/java/learn/mlb_gm/data/TeamJdbcTemplateRepository.java
137389874c3b32320cb3c303a74f24160abc1138
[]
no_license
ckusk92/mlb-gm
547678d02cd85fd1cb7b2b718c20e300df5851e6
7766d9e2aa3e69dac2da63f36839ec0eb81bb39e
refs/heads/main
2023-01-15T09:51:48.128403
2020-11-20T03:17:45
2020-11-20T03:17:45
311,378,520
0
0
null
2020-11-19T22:51:29
2020-11-09T15:16:51
Java
UTF-8
Java
false
false
2,004
java
package learn.mlb_gm.data; import learn.mlb_gm.data.mappers.TeamMapper; import learn.mlb_gm.models.Team; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.List; @Repository public class TeamJdbcTemplateRepository implements TeamRepository { private final JdbcTemplate jdbcTemplate; public TeamJdbcTemplateRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public List<Team> findAll() { final String sql = "select team_id, name from team"; return jdbcTemplate.query(sql, new TeamMapper()); } @Override public Team findById(int teamId) { final String sql = "select team_id, name from team where team_id = ?;"; return jdbcTemplate.query(sql, new TeamMapper(), teamId).stream().findFirst().orElse(null); } @Override public Team add(Team team) { final String sql = "insert into team (name) values(?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); int rowsAffected = jdbcTemplate.update(connection -> { PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, team.getName()); return ps; }, keyHolder); if(rowsAffected <= 0) { return null; } team.setTeamId(keyHolder.getKey().intValue()); return team; } @Override public boolean update(Team team) { final String sql = "update team set name = ? where team_id = ?"; return jdbcTemplate.update(sql, team.getName(), team.getTeamId()) > 0; } @Override public boolean deleteById(int teamId) { return jdbcTemplate.update("delete from team where team_id = ?;", teamId) > 0; } }
[ "38874273+charIiemurphy@users.noreply.github.com" ]
38874273+charIiemurphy@users.noreply.github.com
d03218e4745f2e37beb47b4fc591075bd0ee21e3
0854fb606ee4a2e3f2c6330ab079dd5f7bef2446
/WEB-INF/classes/data/TreinoDO.java
1cc51469a185dfa96093fc65e3ed1cdb645a861f
[]
no_license
yuralves/fremo
b2637f0a120f301ae68d5437ae65d38a35bb72d6
e1c70c0a0e5f94b41ca57c5fb9d2d5e577d660bc
refs/heads/master
2021-03-26T08:17:46.862961
2020-03-16T11:49:00
2020-03-16T11:49:00
247,688,345
0
0
null
null
null
null
UTF-8
Java
false
false
473
java
package data; public class TreinoDO { private int _id_TREINO; private int _id_TECNICO; public int getId_TREINO() { return _id_TREINO; } // getId_TREINO public void setId_TREINO(int id_TREINO) { _id_TREINO = id_TREINO; } // setId_TREINO public int getId_TECNICO() { return _id_TECNICO; } // obterId_TECNICO public void setId_TECNICO(int id_TECNICO) { _id_TECNICO = id_TECNICO; } // setId_TECNICO } // TreinoDO
[ "yuriberezinalves@gmail.com" ]
yuriberezinalves@gmail.com
665676e63fc2822660900826ab2d6102013215e0
75e90bd38aed729c201a0a2466a5c306c4bd0cec
/11_collection/src/com/ict/edu/Ex04.java
83f60229dcfc413b9d668261b9004754f1069142
[]
no_license
wjdghkscks/java_basics_2020
85ac279188b1ea10a98b5aa768c6661484074a67
ab56f9c9e65c9e45ba3a14dfc66504a76da9b526
refs/heads/master
2022-10-17T04:36:30.841043
2020-06-12T09:07:03
2020-06-12T09:07:03
261,988,075
0
0
null
null
null
null
UTF-8
Java
false
false
1,186
java
package com.ict.edu; public class Ex04 { // 전역 변수 private String name; // 이름 private int sum; // 총점 private double avg; // 평균 private String hak; // 학점 private int rank = 1; // 순위 // getter & setter public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSum() { return sum; } public void setSum(int sum) { this.sum = sum; } public double getAvg() { return avg; } public void setAvg(double avg) { this.avg = avg; } public String getHak() { return hak; } public void setHak(String hak) { this.hak = hak; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } // 총점 public void s_sum(int kor, int eng, int math) { sum = kor + eng + math; s_avg(); // 평균 호출 } // 평균 public void s_avg() { avg = (int)(sum / 3.0 * 10)/10.0; s_hak(); // 학점 호출 } // 학점 public void s_hak() { if (avg >= 90) { hak = "A 학점"; } else if (avg >= 80) { hak = "B 학점"; } else if (avg >= 70) { hak = "C 학점"; } else { hak = "F 학점"; } } }
[ "hwamchanny@naver.com" ]
hwamchanny@naver.com
25b81f7326982ea4036f0fa81346d36b9317de42
b2d7b0517bc16e6a0cf281b1424178413b55b947
/java-basic/src/main/java/ch21/c/Test02.java
dabbb91d983db89d0e9290f8aa47c679f55aab15
[]
no_license
gwanghosong/bitcamp-java-2018-12
5ea3035c1beb5b9ce7c5348503daf5ed72304dc9
8782553c4505c5943db0009b6a2ebf742c84e38c
refs/heads/master
2021-08-06T20:30:07.181054
2019-06-26T16:18:50
2019-06-26T16:18:50
163,650,672
0
0
null
2020-04-30T06:28:29
2018-12-31T08:00:40
Java
UTF-8
Java
false
false
1,392
java
// 애플리케이션 예외의 종류: Exception 계열의 예외처리 package ch21.c; import java.lang.reflect.Constructor; import java.util.Scanner; public class Test02 { public static void main(String[] args) { // Exception 계열의 예외 방법 // 1) try ~ catch로 예외 받기 // try { // 예외 발생 코드 // } catch (예외 파라미터) { // 예외 처리 코드 // } // 2) 호출자에게 예외 처리를 떠넘기기 // void 메서드() throws 예외 클래스명, 예외 클래스명, ... { // 예외가 발생할 수 있는 코드 // } // // '방법1' 적용 // try ~ catch 로 예외 처리하기 try { Scanner keyboard = new Scanner(System.in); Class<?> clazz = Class.forName("ch21.c.PlusCommand2"); Constructor<?> constructor = clazz.getConstructor(Scanner.class); Command command = (Command) constructor.newInstance(keyboard); command.execute(); } catch (ClassNotFoundException e) { System.out.println("해당 클래스를 찾지 못했습니다."); } catch (NoSuchMethodException e) { System.out.println("해당 생성자를 찾지 못했습니다."); } catch (ReflectiveOperationException e) { System.out.println("기타 예외 발생!"); } System.out.println("종료!"); } }
[ "gwanghosong91@gmail.com" ]
gwanghosong91@gmail.com
926d2b045dae35849e663c9a48877cab7682a70f
4741b4d2702a662c78c7326cfaaa7b12cd663eb4
/src/main/java/gp/adapter/demo/passport/adapterv15/Three/loginForQQAdapterThree.java
4c4a072eadf1925796dfa6c021541fd6f2dadb1e
[]
no_license
Jackinline/Gp-2020-Code
03cbcadb37f187f17dd4bd423f87210814593f79
9340d66338f397c73d8bdcee2f0c598cac7e1d7e
refs/heads/master
2022-07-14T12:03:20.234666
2020-03-27T01:00:50
2020-03-27T01:00:50
242,747,190
0
0
null
2022-06-17T02:58:09
2020-02-24T13:45:30
Java
UTF-8
Java
false
false
909
java
package gp.adapter.demo.passport.adapterv15.Three; import gp.adapter.demo.passport.Member; import gp.adapter.demo.passport.ResultMsg; public class loginForQQAdapterThree implements ILoginAdapterThree { public ResultMsg login(Object[] param, Object object) { if( object instanceof loginForQQAdapterThree){ String openId = (String) param[0]; System.out.println("loginForQQAdapterThree doing....."+openId); return new ResultMsg(200,"login OK",new Member()); } return null; } public ResultMsg login(Object[] param, Class<? extends ILoginAdapterThree> clazz) { if( clazz ==loginForQQAdapterThree.class){ String openId = (String) param[0]; System.out.println("loginForQQAdapterThree doing....."+openId); return new ResultMsg(200,"login OK",new Member()); } return null; } }
[ "779886365@qq.com" ]
779886365@qq.com
a8623132745ff08a4198bd6210e6d0cd8f415a4b
19bfcfef0fcabefe201a80805b12c9a90327cac6
/ThesisProject/src/utils/InMessage.java
5b6a80fc8a5af81ba032f9ad5dd89e210d9a0ba5
[]
no_license
Frekkenbok/thesis_project
c552dab332e121fdfe146f05bf5fc5b140d77250
9acdebc881e1c4c76bffa4d11d2a520e13d53fad
refs/heads/master
2020-05-21T12:06:33.177575
2015-04-13T20:50:50
2015-04-13T20:50:50
26,130,848
0
0
null
null
null
null
UTF-8
Java
false
false
1,135
java
/* * 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 utils; import java.io.File; /** * * @author Евгения */ public class InMessage { private String inid; private String cureID; private File infile; public InMessage () { } public InMessage(String inid, String cureID, File infile) { this.inid = inid; this.cureID = cureID; this.infile = infile; } public String getInid(){ return "id_"+inid+"_id"; } public void setInid(String inid) { this.inid = inid; } public String getCureId() { return cureID; } public void setCureId(String cureID) { this.cureID = cureID; } public File getInfile() { return infile; } public void setInfile(File infile) { this.infile = infile; } // @Override // public String toString() { // return (inid + " " + cureID + " "+ infile.getName()); // } }
[ "eva.minion@yandex.ru" ]
eva.minion@yandex.ru
878bd6590e182bf538a1cec62cbe284602d45c79
4fdde8e86d4b4a7ff2d966d42a2027fb93538281
/admin/src/main/java/com/wiggin/mangersys/service/RolePermissionService.java
1650eac483f68b936a2001bed175621ed203cd0d
[]
no_license
wangjin0821/springboot-vueadmin
8f5823c50e87c7bd216c5ae54a5d8382c28de91e
8ac6df44306bb905bbe03bbd926c1892697491c0
refs/heads/master
2020-04-18T03:26:16.481601
2019-04-07T10:13:43
2019-04-07T10:13:43
167,198,669
0
0
null
null
null
null
UTF-8
Java
false
false
423
java
package com.wiggin.mangersys.service; import java.util.List; import com.wiggin.mangersys.domain.entity.RolePermission; /** * <p> * 角色权限关联表 服务类 * </p> * * @author wiggin123 * @since 2019-01-17 */ public interface RolePermissionService { Integer saveRolePermission(List<RolePermission> rolePermissionList); List<RolePermission> getRolePermissionListByRoleId(Integer roleId); }
[ "309472178@qq.com" ]
309472178@qq.com
0ba5dba4efc0b4e6948212f8399f37805dd7f10f
67660ad226739ec9b13c915372ae659801a6c238
/app/src/main/java/com/example/cexpress_vendedor/EditarNegocioActivity.java
7b9a7dbadd5eed490a91cd8bec9bdd382f59db96
[]
no_license
Luis-Leonardo/Cexpress_Vendedor
95dc1854ed193b83411ae0a53af3792432f82737
607e057d4eacf67c350e23b83788ae85a784a085
refs/heads/master
2023-01-23T13:24:36.311364
2020-12-02T10:02:03
2020-12-02T10:02:03
316,566,318
0
0
null
null
null
null
UTF-8
Java
false
false
21,742
java
package com.example.cexpress_vendedor; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.app.AlertDialog; import android.app.DownloadManager; import android.app.TimePickerDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.StrictMode; import android.provider.MediaStore; import android.util.Base64; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.TimePicker; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.textfield.TextInputLayout; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Map; public class EditarNegocioActivity extends AppCompatActivity implements Response.Listener<JSONObject>, Response.ErrorListener { TextInputLayout impNombreNegocioEditar, impNumeroNegocioEditar, impHoraAperturaEditar, impHoraCierreEditar; EditText editNombreNegocioEditar, editNumeroNegocioEditar, editHoraAperturaEditar, editHoraCierreEditar; Spinner spinnerMercadoNegocioEditar, spinnerCategoriaNegocioEditar; ImageButton imgBtnFotoNegocioEditar, imgBtnRegresar; Button btnModificarNegocio; ArrayList<String> mercados, categorias; ArrayList<Integer> idMercados, idCategorias; Boolean nombre = false, horaApertura = false, horaCierre = false; int idPuesto, idVendedor, idMercado=1, idCategoria=1; String encodedImage, nuevoNombre, nuevoNumero, nuevaHoraApertura, nuevaHoraCierre; RequestQueue request; JsonObjectRequest jsonObjectRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editar_negocio); impNombreNegocioEditar = findViewById(R.id.impNombreNegocioEditar); impNumeroNegocioEditar = findViewById(R.id.impNumeroNegocioEditar); impHoraAperturaEditar = findViewById(R.id.impHoraAperturaEditar); impHoraCierreEditar = findViewById(R.id.impHoraCierreEditar); editNombreNegocioEditar = findViewById(R.id.editNombreNegocioEditar); editNumeroNegocioEditar = findViewById(R.id.editNumeroNegocioEditar); editHoraAperturaEditar = findViewById(R.id.editHoraAperturaEditar); editHoraCierreEditar = findViewById(R.id.editHoraCierreEditar); spinnerMercadoNegocioEditar = findViewById(R.id.spinnerMercadoNegocioEditar); spinnerCategoriaNegocioEditar = findViewById(R.id.spinnerCategoriaNegocioEditar); imgBtnFotoNegocioEditar = findViewById(R.id.imgBtnFotoNegocioEditar); imgBtnRegresar = findViewById(R.id.imgBtnRegresar); btnModificarNegocio = findViewById(R.id.btnModificarNegocio); request = Volley.newRequestQueue(this); mercados = new ArrayList<>(); idMercados = new ArrayList<>(); categorias = new ArrayList<>(); idCategorias = new ArrayList<>(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); Bundle bundle = getIntent().getBundleExtra("datos"); idPuesto = bundle.getInt("idNegocio"); recuperarId(); cargarMercados(); cargarCategorias(); obtenerPuesto(); imgBtnRegresar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); imgBtnFotoNegocioEditar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mostrarOpcionesFoto(); } }); spinnerMercadoNegocioEditar.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { idMercado = idMercados.get(position); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spinnerCategoriaNegocioEditar.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { idCategoria = idCategorias.get(position); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); editHoraAperturaEditar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); TimePickerDialog timePickerDialog; timePickerDialog = new TimePickerDialog(EditarNegocioActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String hora, minutos, periodo; if(hourOfDay < 10) { hora = String.valueOf(0)+hourOfDay; } else { hora = String.valueOf(hourOfDay); } if(minute < 10) { minutos = String.valueOf(0)+minute; } else { minutos = String.valueOf(minute); } nuevaHoraApertura=hora+":"+minutos+":00"; if (hourOfDay>=12&&hourOfDay<24) { periodo = "PM"; if(hourOfDay>12) { hora = String.valueOf(hourOfDay-12); } } else { periodo = "AM"; } editHoraAperturaEditar.setText(hora + ":" + minutos + " " + periodo); } }, hour, minute, false); timePickerDialog.setTitle("Hora de Apertura"); timePickerDialog.setCanceledOnTouchOutside(true); timePickerDialog.show(); } }); editHoraCierreEditar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); TimePickerDialog timePickerDialog; timePickerDialog = new TimePickerDialog(EditarNegocioActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String hora, minutos, periodo; if(hourOfDay < 10) { hora = String.valueOf(0)+hourOfDay; } else { hora = String.valueOf(hourOfDay); } if(minute < 10) { minutos = String.valueOf(0)+minute; } else { minutos = String.valueOf(minute); } nuevaHoraCierre=hora+":"+minutos+":00"; if (hourOfDay>=12&&hourOfDay<24) { periodo = "PM"; if(hourOfDay>12) { hora = String.valueOf(hourOfDay-12); } } else { periodo = "AM"; } editHoraCierreEditar.setText(hora + ":" + minutos + " " + periodo); } }, hour, minute, false); timePickerDialog.setTitle("Hora de Cierre"); timePickerDialog.setCanceledOnTouchOutside(true); timePickerDialog.show(); } }); btnModificarNegocio.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { validarDatos(); } }); } private void mostrarOpcionesFoto() { final CharSequence[] opciones={"Tomar Foto", "Elegir foto de la galería", "Cancelar"}; final AlertDialog.Builder opc= new AlertDialog.Builder(EditarNegocioActivity.this); opc.setTitle("Elige una opción"); opc.setItems(opciones, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { if(opciones[i].equals("Tomar Foto")) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 20); } else if(opciones[i].equals("Elegir foto de la galería")) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setType("image/"); startActivityForResult(intent.createChooser(intent, "Selecciona una opción"), 10); } else { dialog.dismiss(); } } }); opc.show(); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode== Activity.RESULT_OK) { switch (requestCode) { case 10: Uri miPath=data.getData(); try { InputStream inputStream = getContentResolver().openInputStream(miPath); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); imgBtnFotoNegocioEditar.setImageBitmap(bitmap); guardarImagen(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } break; case 20: Bundle bundle = data.getExtras(); Bitmap bitmap = (Bitmap) bundle.get("data"); imgBtnFotoNegocioEditar.setImageBitmap(bitmap); guardarImagen(bitmap); break; } } else { } } void guardarImagen(Bitmap imagen) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); imagen.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] imageBytes = stream.toByteArray(); encodedImage = android.util.Base64.encodeToString(imageBytes, Base64.DEFAULT); } void obtenerPuesto() { String URL = "https://appsmoviles2020.000webhostapp.com/vendedor/getNegocio.php?idPuesto="+idPuesto; jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("Negocio"); JSONObject jsonObject = jsonArray.getJSONObject(0); //Nombre y numero editNombreNegocioEditar.setText(jsonObject.getString("nombre")); if(jsonObject.getString("numero")!="null") { editNumeroNegocioEditar.setText(jsonObject.getString("numero")); } //Horas String hora, minutos, periodo, horaAperturaBD, horaCierreBD; hora = jsonObject.getString("horaApertura").substring(0, 2); minutos = jsonObject.getString("horaApertura").substring(3, 5); nuevaHoraApertura=hora+":"+minutos+":00"; if(Integer.valueOf(hora)>=12) { periodo = "PM"; int horaAdecuada = Integer.valueOf(hora)-12; if(horaAdecuada<10) { hora = 0+String.valueOf(horaAdecuada); } else { hora = String.valueOf(horaAdecuada); } } else { periodo = "AM"; } horaAperturaBD=hora+":"+minutos+" "+periodo; editHoraAperturaEditar.setText(horaAperturaBD); hora = jsonObject.getString("horaCierre").substring(0, 2); minutos = jsonObject.getString("horaCierre").substring(3, 5); nuevaHoraCierre=hora+":"+minutos+":00"; if(Integer.valueOf(hora)>=12) { periodo = "PM"; int horaAdecuada = Integer.valueOf(hora)-12; if(horaAdecuada<10) { hora = 0+String.valueOf(horaAdecuada); } else { hora = String.valueOf(horaAdecuada); } } else { periodo = "AM"; } horaCierreBD=hora+":"+minutos+" "+periodo; editHoraCierreEditar.setText(horaCierreBD); //Foto if(jsonObject.getString("foto")!="null") { String urlFoto = "https://appsmoviles2020.000webhostapp.com/imagenes/"+jsonObject.getString("foto"); java.net.URL url = new URL(urlFoto); Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream()); imgBtnFotoNegocioEditar.setImageBitmap(bitmap); guardarImagen(bitmap); } //Selects spinnerMercadoNegocioEditar.setSelection(idMercados.indexOf(jsonObject.getInt("idMercado"))); spinnerCategoriaNegocioEditar.setSelection(idCategorias.indexOf(jsonObject.getInt("idCategoria"))); } catch (JSONException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(EditarNegocioActivity.this, error.toString(), Toast.LENGTH_SHORT).show(); } }); request.add(jsonObjectRequest); } void recuperarId() { SharedPreferences sharedPreferences = getSharedPreferences("Sesion", MODE_PRIVATE); idVendedor = sharedPreferences.getInt("id", 0); } void cargarMercados() { String URL = "https://appsmoviles2020.000webhostapp.com/vendedor/getMercados.php?"; jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, this, this); request.add(jsonObjectRequest); } @Override public void onErrorResponse(VolleyError error) { Toast.makeText(this, error.toString(), Toast.LENGTH_SHORT).show(); } @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("Mercados"); for (int i=0; i<jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); mercados.add(jsonObject.getString("nombre")); idMercados.add(jsonObject.getInt("idMercado")); ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, mercados); spinnerMercadoNegocioEditar.setAdapter(adapter); } } catch (JSONException e) { e.printStackTrace(); } } void cargarCategorias() { String URL = "https://appsmoviles2020.000webhostapp.com/vendedor/getCategorias.php?"; jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("Categorias"); for (int i=0; i<jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); categorias.add(jsonObject.getString("nombre")); idCategorias.add(jsonObject.getInt("idCategoria")); ArrayAdapter<CharSequence> adapter = new ArrayAdapter(EditarNegocioActivity.this, android.R.layout.simple_spinner_item, categorias); spinnerCategoriaNegocioEditar.setAdapter(adapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(EditarNegocioActivity.this, error.toString(), Toast.LENGTH_SHORT).show(); } }); request.add(jsonObjectRequest); } void validarDatos() { //Validaciones nombre if(editNombreNegocioEditar.getText().toString().isEmpty()) { impNombreNegocioEditar.setError("Campo de Nombre está vacío"); nombre = false; } else { impNombreNegocioEditar.setError(null); nombre = true; } //Validaciones hora if(editHoraAperturaEditar.getText().toString().isEmpty()) { impHoraAperturaEditar.setError("Hora de Apertura no seleccionada"); horaApertura = false; } else { impHoraAperturaEditar.setError(null); horaApertura = true; } if(editHoraCierreEditar.getText().toString().isEmpty()) { impHoraCierreEditar.setError("Hora de Cierre no seleccionada"); horaCierre = false; } else { impHoraCierreEditar.setError(null); horaCierre = true; } if(nombre && horaApertura && horaCierre) { //Llamar funcion registro nuevoNombre = editNombreNegocioEditar.getText().toString(); nuevoNumero = editNumeroNegocioEditar.getText().toString(); actualizarNegocio(nuevoNombre, nuevoNumero, nuevaHoraApertura, nuevaHoraCierre); } } void actualizarNegocio(final String nombre, final String numero, final String horaApertura, final String horaCierre) { String URL = "https://appsmoviles2020.000webhostapp.com/vendedor/actualizarNegocio.php"; StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(EditarNegocioActivity.this, "Cambios Guardados", Toast.LENGTH_SHORT).show(); //Intent intent = new Intent(EditarNegocioActivity.this, NegociosActivity.class); //startActivity(intent); finish(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(EditarNegocioActivity.this, error.toString(), Toast.LENGTH_LONG).show(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("idPuesto", String.valueOf(idPuesto)); params.put("idVendedor", String.valueOf(idVendedor)); params.put("nombre", nombre); params.put("numero", numero); params.put("horaApertura", horaApertura); params.put("horaCierre", horaCierre); params.put("foto", encodedImage); params.put("idMercado", String.valueOf(idMercado)); params.put("idCategoria", String.valueOf(idCategoria)); return params; } }; request.add(stringRequest); } }
[ "47133311+Luis-Leonardo@users.noreply.github.com" ]
47133311+Luis-Leonardo@users.noreply.github.com
9ee5b0f80366cfd778deceef57df179894c1eeb7
b85d0ce8280cff639a80de8bf35e2ad110ac7e16
/com/fossil/dcg.java
7f1f4ec480583605e198b50ed0d4f2ea6f1a632a
[]
no_license
MathiasMonstrey/fosil_decompiled
3d90433663db67efdc93775145afc0f4a3dd150c
667c5eea80c829164220222e8fa64bf7185c9aae
refs/heads/master
2020-03-19T12:18:30.615455
2018-06-07T17:26:09
2018-06-07T17:26:09
136,509,743
1
0
null
null
null
null
UTF-8
Java
false
false
2,060
java
package com.fossil; import com.fossil.wearables.fsl.contact.ContactGroup; import com.portfolio.platform.ui.notifications.domain.model.AppWrapper; import com.portfolio.platform.ui.notifications.domain.model.ContactWrapper; import java.util.List; public class dcg { interface C2646a extends cjs { void mo2295A(int i, boolean z); void mo2296B(int i, boolean z); void mo2297C(int i, boolean z); void mo2298a(int i, ContactWrapper contactWrapper); void mo2299a(ContactWrapper contactWrapper, int i); void mo2300a(ContactWrapper contactWrapper, boolean z, int i); void alA(); void alB(); void alC(); void alz(); void bY(int i, int i2); void bZ(int i, int i2); void ca(int i, int i2); void kt(int i); void ku(int i); void kv(int i); void kw(int i); void kx(int i); void ky(int i); void kz(int i); void onCancel(); void save(); } public interface C2647b extends cjt<C2646a> { void mo2256a(ContactWrapper contactWrapper, int i, int i2, int i3); void mo2257a(String str, int i, int i2, int i3); void mo2258a(List<ContactGroup> list, int i, List<ContactWrapper> list2); void ac(List<Object> list); void alD(); void alE(); void alF(); void alG(); void alH(); void alI(); void alJ(); void alK(); void alL(); void alM(); void alN(); void alO(); void alP(); void mo2273b(int i, Object obj); void cF(boolean z); void cancel(); void cb(int i, int i2); void cc(int i, int i2); void mo2281g(List<AppWrapper> list, int i); void iq(String str); void kA(int i); void kB(int i); void kC(int i); void kD(int i); void kE(int i); void kF(int i); void kG(int i); void kH(int i); } }
[ "me@mathiasmonstrey.be" ]
me@mathiasmonstrey.be
f38a4ad2f4d5e200d2450216df8f51490c9ae78e
993bb3f42fe82248ff8b2319b2b53135ef7aa78f
/sma/src/sma/util/smaSwitch.java
21935417885ce5227219ff870ec0b892fba8d35e
[]
no_license
kelly-cardenas/ProyectoSW
ba6c6161740d98ca3ae6489952388c2468e1912f
0664c0038370f5611934defc9c10e9593156c442
refs/heads/master
2022-07-16T12:27:54.643716
2020-05-13T06:14:36
2020-05-13T06:14:36
262,689,116
0
0
null
null
null
null
UTF-8
Java
false
false
3,266
java
/** */ package sma.util; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; import sma.*; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see sma.smaPackage * @generated */ public class smaSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static smaPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public smaSwitch() { if (modelPackage == null) { modelPackage = smaPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case smaPackage.MODEL_FACTORY: { ModelFactory modelFactory = (ModelFactory)theEObject; T result = caseModelFactory(modelFactory); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Model Factory</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Model Factory</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseModelFactory(ModelFactory object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //smaSwitch
[ "kelly@LAPTOP-E64E6LGJ" ]
kelly@LAPTOP-E64E6LGJ
46edc80f1fae3b49d7aa5008f6be918e0f9a7db8
b9861a0fc815b77551d81010fa890ef44e9ba1cc
/admin/src/main/java/com/baidu/yun/core/filter/RangeRestrictFilter.java
ec3bc20d2889de62e66e61724a35b0705553b4c7
[]
no_license
happyjianguo/hwp
6dbc5223bb19534ac9d61b3eae8009038be4e1aa
6bf80e34f3363f48af039e92931fbf3c22daae50
refs/heads/master
2022-12-01T01:57:04.680195
2020-08-09T00:20:00
2020-08-09T00:20:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
410
java
package com.baidu.yun.core.filter; import java.lang.reflect.Field; import java.util.Map; public class RangeRestrictFilter implements IFieldFilter { @Override public void mapping(Field field, Object obj, Map<String, String> map) { // TODO Auto-generated method stub } @Override public void validate(Field field, Object obj) { // TODO Auto-generated method stub } }
[ "weiliejun@163.com" ]
weiliejun@163.com
7f8b966248a890735a5534d0a13b9ea1e1aa068c
a4a51084cfb715c7076c810520542af38a854868
/src/main/java/com/tencent/liteav/beauty/b/a/b.java
7efc3e692c1d9bf17c888e31a1413969aa52fed1
[]
no_license
BharathPalanivelu/repotest
ddaf56a94eb52867408e0e769f35bef2d815da72
f78ae38738d2ba6c9b9b4049f3092188fabb5b59
refs/heads/master
2020-09-30T18:55:04.802341
2019-12-02T10:52:08
2019-12-02T10:52:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,435
java
package com.tencent.liteav.beauty.b.a; import android.opengl.GLES20; import android.util.Log; import com.tencent.liteav.basic.log.TXCLog; import com.tencent.liteav.beauty.NativeLoad; import com.tencent.liteav.beauty.b.t; public class b extends t { private int r = -1; private int s = -1; private int t = -1; private final String x = "BeautyBlend"; public b() { super("varying lowp vec2 textureCoordinate;\n \nuniform sampler2D inputImageTexture;\n \nvoid main()\n{\n gl_FragColor = texture2D(inputImageTexture, textureCoordinate);\n}"); } public boolean a() { NativeLoad.getInstance(); this.f31313a = NativeLoad.nativeLoadGLProgram(12); if (this.f31313a == 0 || !b()) { this.f31319g = false; } else { this.f31319g = true; } c(); return this.f31319g; } public boolean b() { super.b(); q(); return true; } public void a(float f2) { TXCLog.i("BeautyBlend", "setBrightLevel " + f2); a(this.s, f2); } public void b(float f2) { Log.i("BeautyBlend", "setRuddyLevel level " + f2); a(this.t, f2 / 2.0f); } private void q() { this.s = GLES20.glGetUniformLocation(p(), "whiteDegree"); this.r = GLES20.glGetUniformLocation(p(), "contrast"); this.t = GLES20.glGetUniformLocation(p(), "ruddyDegree"); } }
[ "noiz354@gmail.com" ]
noiz354@gmail.com
434b0b8a6848821e7aff8b6aa97a37b3fbbabb0f
8fcee692fd2d35dd8aa2e9b2617a3b5310c8c461
/src/main/java/hiber/dao/UserDaoImp.java
0d8f86659cc65ec6c6079ea3953bda127fb687c2
[]
no_license
SLEEGit/spring_hibernate
1408cd65f67a0af4672f113bc0977bec7e5ef375
4640344281ce17c4f3408953094eebfbe453f84e
refs/heads/master
2023-02-21T22:43:23.326664
2021-01-27T12:32:34
2021-01-27T12:32:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,302
java
package hiber.dao; import hiber.model.Car; import hiber.model.User; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import javax.persistence.TypedQuery; import java.util.List; @Repository public class UserDaoImp implements UserDao { @Autowired private SessionFactory sessionFactory; @Override public void add(User user) { sessionFactory.getCurrentSession().save(user); } @Override public User getByCar(int series, String model) { // ЗДЕСЬ ! ! ! TypedQuery<User> query = sessionFactory.getCurrentSession().createQuery("from User where car.series = :series AND car.model = :model", User.class); query.setParameter("model", model); query.setParameter("series", series); return query.getSingleResult(); } @Override @SuppressWarnings("unchecked") public List<User> listUsers() { TypedQuery<User> query=sessionFactory.getCurrentSession().createQuery("from User"); return query.getResultList(); } @Override public void deleteAll() { sessionFactory.getCurrentSession().createQuery("DELETE FROM User").executeUpdate(); } }
[ "guagetru.bla@inbox.ru" ]
guagetru.bla@inbox.ru
8e9fef87df64a8f5595d150fac7bd671e7130f8b
f7075d288ccb65218cd701edc34e8f630de2e75b
/day23test/src/com/itheima/service/impl/ServiceProvinceImpl.java
d36c9942eb4ae4bf622fc5f50a62053c16407ed0
[]
no_license
itcastCai/repo1
915925ce977c22645851eeaaec75bab89758771d
56e3a1f142d5906b7ec6ff3fc4911c9fd395bb40
refs/heads/master
2021-07-04T23:00:21.631844
2019-06-14T08:10:09
2019-06-14T08:10:09
191,367,439
1
0
null
2020-10-13T13:53:58
2019-06-11T12:30:19
JavaScript
UTF-8
Java
false
false
1,315
java
package com.itheima.service.impl; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.dao.impl.FindProvinceImpl; import com.itheima.domain.Province; import com.itheima.jedis.JedisPoolUtils; import com.itheima.service.ServiceProvince; import redis.clients.jedis.Jedis; import java.util.List; public class ServiceProvinceImpl implements ServiceProvince { private FindProvinceImpl dao = new FindProvinceImpl(); @Override public List<Province> findAll() { return dao.findAll(); } @Override public String findAllJson() { Jedis jedis = JedisPoolUtils.getjedis(); String province_json = jedis.get("province"); if (province_json == null || province_json.length() == 0) { List<Province> list = dao.findAll(); ObjectMapper mapper = new ObjectMapper(); try { System.out.println("从数据库查询"); province_json = mapper.writeValueAsString(list); } catch (JsonProcessingException e) { e.printStackTrace(); } jedis.set("province", province_json); } else { System.out.println("从缓存查询"); } return province_json; } }
[ "cai349887291@163.com" ]
cai349887291@163.com
2fe1330ab14661edfb872a36eb888f5fda7d907f
318cd1f0b6549b907bd680d20c2af72920275bd2
/Spring 02 - Sur la route/src/main/java/fr/wildcodeschool/SpringDoctor02/SpringDoctor02Application.java
d7fb9f6965800feaea39e376e23ef282691229f2
[]
no_license
jonsoninlaw/Odyssey
42ff48cafb5bede6bab7f15efcbfc98998c03862
93a31cdb138ea1f6e42de0d0c6b7419c208f9b5d
refs/heads/master
2020-09-28T19:52:07.287625
2020-02-06T08:18:28
2020-02-06T08:18:28
226,828,269
0
0
null
null
null
null
UTF-8
Java
false
false
1,420
java
package fr.wildcodeschool.SpringDoctor02; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.server.ResponseStatusException; @Controller @SpringBootApplication public class SpringDoctor02Application { public static void main(String[] args) { SpringApplication.run(SpringDoctor02Application.class, args); } @RequestMapping("/doctor/{doctorId}") @ResponseBody public String doctor1(@PathVariable int doctorId) { String[] doctors = {"Christopher Eccleston", "David Tennant", "Matt Smith", "Peter Capaldi", "Jodie Whittaker"}; if (doctorId >= 9 && doctorId <= 13) { return "Docteur n°" + doctorId + " : " + doctors[doctorId - 9]; } if (doctorId >= 1 && doctorId <= 8) { throw new ResponseStatusException(HttpStatus.SEE_OTHER, "Try another id !"); } else { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "This Doctor may have never existed..."); } } }
[ "jonsoninlaw@gmail.com" ]
jonsoninlaw@gmail.com
b9b59e9ed2fe8169e2de343e3e03fe43ef920c7a
458352666d6642bb2a7e69481996b6731ca4146e
/Problems/src/Fifo.java
259e5e33b3898ace91410dbc610e5687afa97749
[]
no_license
Bhavani94/Leetcode
9ea6edde3a5984120b2b7bbaa509058a0737bb1f
12e20dc253aa343cfc17fd973a0e0c607cc66dde
refs/heads/master
2020-06-21T17:20:27.657077
2019-08-12T21:07:11
2019-08-12T21:07:11
197,513,851
0
0
null
null
null
null
UTF-8
Java
false
false
677
java
import java.util.LinkedList; public class Fifo { private final LinkedList<Integer> queue; public Fifo() { queue = new LinkedList<>(); } public void enqueue(int value) { queue.addLast(value); } public int dequeue() { return queue.isEmpty() ? Integer.MIN_VALUE : queue.removeFirst(); } public static void main(String[] args) { Fifo fifo = new Fifo(); fifo.enqueue(1); fifo.enqueue(2); fifo.enqueue(3); System.out.println(fifo.dequeue()); System.out.println(fifo.dequeue()); System.out.println(fifo.dequeue()); System.out.println(fifo.dequeue()); } }
[ "bhavani.raman@locationlabs.com" ]
bhavani.raman@locationlabs.com
3c58e1b245b4e5a6cd8914f94881cb870d711d41
e2437d2a04fbbda45507eaa315d7c1e462ec60c6
/Automation Project/src/main/java/com/atmecs/atmecsqa/utils/ScreenShot.java
514b72036d136b82d2a4d2bbe68bbed62617d313
[]
no_license
Subhasrinatarajan/Assignment
b274ffb30203bed798854d52565639fc7ce0fe5e
ae3180799e6a39b3e033522971f1d115d65c4bb7
refs/heads/master
2022-07-25T14:11:36.366074
2019-08-27T13:20:56
2019-08-27T13:20:56
191,749,682
1
1
null
2022-05-20T21:02:50
2019-06-13T11:25:03
HTML
UTF-8
Java
false
false
505
java
package com.atmecs.atmecsqa.utils; import java.io.File; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import com.atmecs.atmecsqa.testbase.Base; public class ScreenShot extends Base { /* @Test public static void captureScreenMethod() throws Exception{ File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshotFile, new File("D:\\SoftwareTestingMaterial.png")); driver.close(); driver.quit(); */ }
[ "subinatraj@gmail.com" ]
subinatraj@gmail.com
e4e8be6f698e284011c59a91b6f4a778163206da
69dde294850068912c0ba83fc5c87bda5959d938
/concurrency/src/main/java/io/effective/Allocator.java
7af68eaebd356ae9bab58e12599da894fed10846
[]
no_license
searover/effective-java
9baad5836216eb188bfe70b6a726c8e963622eaf
804ced453369a0304d9bcd365c7e8d0f8b3ac364
refs/heads/master
2022-11-25T23:15:07.541286
2022-11-19T05:16:23
2022-11-19T05:16:23
135,756,097
0
0
null
null
null
null
UTF-8
Java
false
false
564
java
package io.effective; import java.util.List; /** * @author luxz * @date 2020/6/25-4:44 PM */ public class Allocator { private List<Object> als; // 一次性申请所有资源 synchronized void apply(Object from, Object to) throws InterruptedException { //经典写法 while (als.contains(from) || als.contains(to)) { wait(); } als.add(from); als.add(to); } synchronized void free(Object from, Object to) { als.remove(from); als.remove(to); notifyAll(); } }
[ "ibaiguang@gmail.com" ]
ibaiguang@gmail.com
4757edd7f434172d23d53ba1173b8b19085ec39d
97aa6bf8f175cce9f530b9049da19d6fbf66b45b
/sharedstorage/src/test/java/com/github/Sourav242/sharedstorage/ExampleUnitTest.java
2e77b8b37ddac3a1b881660ac5e7cd7c6da8a864
[]
no_license
Sourav242/SharedStorage
b62659be40d2b6be35ee89716f9acb13aed17650
242b4d76d309458129a53406c14ce232ca5ce96d
refs/heads/master
2020-06-28T07:01:26.350979
2020-02-07T11:42:18
2020-02-07T11:42:18
200,170,439
0
0
null
null
null
null
UTF-8
Java
false
false
395
java
package com.github.Sourav242.sharedstorage; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
[ "1994sourav@gmail.com" ]
1994sourav@gmail.com
47ebbf328199025c4879011c9e35b386d68a92a6
66932d551b1928af0ff59e4dc5cd947a1387fc18
/app/src/main/java/xyz/kkt/sunshine/viewHolders/WeatherDataViewHolder.java
81cb92d26534667c9698c0945678aa36b8aa5d98
[ "Apache-2.0" ]
permissive
KaungKhantThu/Sunshine
72cf515c2d6f084443c17980f6df3cc241bfacea
3985612d6950e62b814abfd70c55958032b997c3
refs/heads/master
2021-08-24T06:19:47.804700
2017-12-08T11:12:52
2017-12-08T11:12:52
112,696,367
0
0
null
null
null
null
UTF-8
Java
false
false
853
java
package xyz.kkt.sunshine.viewHolders; import android.annotation.SuppressLint; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.RelativeLayout; import butterknife.BindView; import butterknife.ButterKnife; import xyz.kkt.sunshine.R; /** * Created by Lenovo on 12/1/2017. */ public class WeatherDataViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.rl_container) RelativeLayout rlContainer; public WeatherDataViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); itemView.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View view) { rlContainer.setBackgroundColor(R.color.primary); } }); } }
[ "kaungkhantthukkt2016@gmail.com" ]
kaungkhantthukkt2016@gmail.com
8ef14cb450801981b5a83861487238f5309f6283
1f0be937904dec7b51c6de99a3cc58ab0da35e81
/portlet/catalog/catalog-portlet/src/main/java/org/nterlearning/atom/parser/dao/CatalogFeed.java
04cd3081d2ed806a15b270648587b80d02b71b67
[]
no_license
sbreidba/nter.portal-core-devel
032b5ee0f918e3d662db1e5d2c1e6f412853003b
1900a8e6122d63c1eff81a0bbf1c83d62e603cc7
refs/heads/master
2022-08-20T15:00:13.207226
2014-01-31T20:17:01
2014-01-31T20:17:01
37,631,560
0
0
null
2022-03-21T20:31:16
2015-06-18T01:56:54
Java
UTF-8
Java
false
false
2,303
java
/* * National Training and Education Resource (NTER) * Copyright (C) 2012 SRI International * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.nterlearning.atom.parser.dao; import org.nterlearning.atom.enumerations.NterFeedType; import org.nterlearning.datamodel.catalog.model.CourseRecord; import java.util.List; import java.util.Vector; public class CatalogFeed { private NterFeedType feedType; private List<CatalogCourse> courseList; private List<CatalogComponent> courseComponentsList; private List<CourseRecord> courseRecordsList; public CatalogFeed(List<CatalogCourse> courseList, List<CatalogComponent> courseComponentsList) { this.feedType = NterFeedType.COURSES; this.courseList = courseList; this.courseComponentsList = courseComponentsList; this.courseRecordsList = new Vector<CourseRecord>(); } public CatalogFeed(List<CourseRecord> courseRecords) { this.feedType = NterFeedType.RECORDS; this.courseList = new Vector<CatalogCourse>(); this.courseComponentsList = new Vector<CatalogComponent>(); this.courseRecordsList = courseRecords; } public NterFeedType getFeedType() { return feedType; } public List<CatalogCourse> getCourseList() { return courseList; } public List<CatalogComponent> getCourseComponentsList() { return courseComponentsList; } public List<CourseRecord> getCourseRecordsList() { return courseRecordsList; } }
[ "l.moulder.sri@localhost" ]
l.moulder.sri@localhost
b906f602cbea6d3fb150b344ee5841ca9fc39b66
86b6d1d9f6999809782ddd13909e835c8e1a760e
/src/MatrixSolver.java
c67a1c8de76660880b45e8045a3d3922abc0559f
[]
no_license
kqct/MatrixSolver
59100a840f059d2e333ba72544c745506a88f678
295ed4f04b8929c8c3e6ccdb33af688be0e3e392
refs/heads/master
2022-05-22T05:42:57.358790
2018-01-11T04:06:54
2018-01-11T04:06:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,411
java
import Jama.Matrix; public class MatrixSolver { // String input = "WARIO ONE TRUE GOD"; public static void main(String[] args) { // Define values within encoding matrix // double[][] encodingMatrixVals = {{-1, 6, 15}, {-4, -7, -12}, {11, 6, 4}}; double[][] encodingMatrixVals = new double[][]{{-1, 1, 0}, {1, 3, 2}, {-3, -2, -3}}; String[] inputArray = takeEncodedMatrixInput(); // Make encoding matrix from array of values Matrix encodingMatrix = new Matrix(encodingMatrixVals); Matrix encodedMatrix = makeInputMatrixFromArray(inputArray); // Decode values by multiplying by inverse of encodeing matrix Matrix decodedMatrix = encodedMatrix.times(encodingMatrix.inverse()); String decodedMessage = decodeMessageFromMatrix(decodedMatrix); System.out.println(decodedMessage); } private static String getCharForNumber(int i) { if (i == 0) { return " "; } else { return i > 0 && i < 27 ? String.valueOf((char) (i + 'A' - 1)) : null; } } private static Matrix makeInputMatrixFromArray(String[] inputArray) { // Make 2D array to hold values from user input double[][] encodedMatrixVals = new double[inputArray.length / 3][3]; // Loop over all user values and add them to 2D array int i = 0; for (int row = 0; row < encodedMatrixVals.length; row++) { for (int col = 0; col < encodedMatrixVals[row].length; col++) { encodedMatrixVals[row][col] = Double.parseDouble(inputArray[i]); i++; } } // Make matrix from user values Matrix inputMatrix = new Matrix(encodedMatrixVals); return inputMatrix; } private static String decodeMessageFromMatrix(Matrix decodedMatrix) { // Get the array from the decoded values matrix double[][] decodedMatrixVals = decodedMatrix.getArray(); // Define empty string for decoded message String decodedMessage = ""; // Loop over all values in decoded array and translate them to letters for (double[] d : decodedMatrixVals) { for (double o : d) { decodedMessage += getCharForNumber((int) Math.round(o)); } } return decodedMessage; } private static String[] takeEncodedMatrixInput() { // String input = "146,171,279,-21,-50,-92,-42,97,270,-17,39,114,204,144,151,94,135,233,-19,114,285"; String input = "8,52,30,-64,-32,-58,1,3,2,-32,36,-6,-35,25,-12,-27,46,3"; // Take actual user input here String[] inputArray = input.split("[,][ ]*"); return inputArray; } }
[ "10765599+meow10811@users.noreply.github.com" ]
10765599+meow10811@users.noreply.github.com
b725b6923db2d509d6b46ab1c1f8e9f5e8e5ba51
bf6e1f02ac93df6dd14ae5467b9e5be9a2083fe8
/app/src/main/java/com/frizzle/frizzlehookmaster/HookApplication.java
cf4b8181f293c9dc410270907b1d8ead9946f0d8
[]
no_license
FrizzleLiu/FrizzleHookMaster
a07341b4ba6402cff3a84f6530ba59c7d471e576
a0c55ba4f1b7a3c2655cc8b0640981691a6542a6
refs/heads/master
2022-12-09T01:37:07.744019
2020-09-11T12:41:19
2020-09-11T12:41:19
294,692,329
0
0
null
null
null
null
UTF-8
Java
false
false
2,234
java
package com.frizzle.frizzlehookmaster; import android.app.Application; import android.content.res.Resources; import java.lang.reflect.InvocationTargetException; /** * Time: 2019-08-10 * Author: LWJ * Description: 宿主的Application */ public class HookApplication extends Application { public static String pluginPath; DexElementFuse dexElementFuse; @Override public void onCreate() { super.onCreate(); // TODO 只需要知道,下面这行代码,可以拿到 插件的路径 pluginPath = ApkCopyAssetsToDir.copyAssetToCache(this, Parameter.PLUGIN_FILE_NAME); // TODO 第一个HOOK 具体作用,看里面的方法描述哦 try { AMSCheckEngine.mHookAMS(this); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // TODO 第二个HOOK 具体作用,看里面的方法描述哦 try { ActivityThreadmHRestore.mActivityThreadmHAction(this); } catch (Exception e) { e.printStackTrace(); } // TODO 进行融合 dexElementFuse = new DexElementFuse(); try { dexElementFuse.mainPluginFuse(this); } catch (Exception e) { e.printStackTrace(); } } /** * 重写这个资源管理器 * 为什么要去重写资源管理器呢? * 答:是为了提供资源的加载工作 * 那么为什么要在Application里面重写资源管理器呢? * 答:虽然每一个Activity都有资源管理器,但是不可能每一个Activity都去重写,所以只需要在Application里面重写就好了 * Application的getResources 是所有Activity共用的 * @return */ @Override public Resources getResources() { return dexElementFuse.getResources() == null ? super.getResources() : dexElementFuse.getResources(); } }
[ "15888897624@163.com" ]
15888897624@163.com
55bb4210098dbf4749bcd6625a7f014d1f51f3de
1d14e5edeaf932f02ef5c7c5333dffe5bfac2a16
/pos-microservice-restful-trip-agencia/src/main/java/br/edu/ifpb/ads/pos/microservice/restful/trip/agencia/service/consumer/HotelReservaConsumer.java
d6c28d2b2ed2f1f32fb8598efa83cb32dfe76140
[]
no_license
wensttay/pos-microservice-trip
7c6648fd98bcd22e047fdb1dba28d60e742aaa91
ae3aa2ada79603c5dd35bc8170d8331464e90390
refs/heads/master
2021-07-19T02:28:45.532797
2017-10-23T20:41:59
2017-10-23T20:41:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,254
java
package br.edu.ifpb.ads.pos.microservice.restful.trip.agencia.service.consumer; import br.edu.ifpb.ads.pos.microservice.restful.trip.agencia.mapper.Mapper; import static br.edu.ifpb.ads.pos.microservice.restful.trip.agencia.service.consumer.HotelConsumer.HOTEL_REST_RESOURCE; import static br.edu.ifpb.ads.pos.microservice.restful.trip.agencia.service.consumer.HotelConsumer.REAL_HOTEL_HOST; import static br.edu.ifpb.ads.pos.microservice.restful.trip.agencia.service.consumer.HotelConsumer.REAL_HOTEL_PORT; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; /** * * @author Wensttay de Sousa Alencar <yattsnew@gmail.com> * @date 23/10/2017, 13:30:04 */ @RequestScoped public class HotelReservaConsumer { public static final String HOTEL_HOST = "restful-trip-hotel-api"; public static final String HOTEL_PORT = "8080"; public static final String HOTEL_REST_RESOURCE = "pos-microservice-restful-trip-hotel/api/reservas"; public static final String REAL_HOTEL_HOST = "localhost"; public static final String REAL_HOTEL_PORT = "8082"; private Client client = ClientBuilder.newClient(); private WebTarget target = client.target("http://" + HOTEL_HOST + ":" + HOTEL_PORT + "/" + HOTEL_REST_RESOURCE); @Inject private Mapper mapper; public String getUri(int reservaId, UriInfo uriInfo) { return "http://" + REAL_HOTEL_HOST + ":" + REAL_HOTEL_PORT + "/" + HOTEL_REST_RESOURCE + "/" + reservaId; } public String makeAHotelReserva(HotelReservaRequestEntity requestEntity) { String requestEntityJson = mapper.toString(requestEntity); Response postResponse = target .request() .post(Entity.json(requestEntityJson)); return getIdFromUri(postResponse.getHeaderString("Location")); } public String makeAHotelReserva(String clientCpf, int hotel_id, String quarto_id, String inicio, String termino) { HotelReservaRequestEntity requestEntity = new HotelReservaRequestEntity(); requestEntity.setClienteCpf(clientCpf); requestEntity.setHotel_id(hotel_id); requestEntity.setQuarto_id(hotel_id); requestEntity.setInicio(inicio); requestEntity.setTermino(termino); String requestEntityJson = mapper.toString(requestEntity); Response postResponse = target .request() .post(Entity.json(requestEntityJson)); return getIdFromUri(postResponse.getHeaderString("Location")); } public void destroyAHotelReserva(int hotelReservaId) { WebTarget delTarget = client.target("http://" + HOTEL_HOST + ":" + HOTEL_PORT + "/" + HOTEL_REST_RESOURCE + "/" + hotelReservaId); delTarget.request().delete(); } public String getIdFromUri(String uri) { int lastIndexOf = uri.lastIndexOf("/"); return uri.substring(lastIndexOf + 1, uri.length()); } }
[ "yattsnew@gmail.com" ]
yattsnew@gmail.com
8956c678d27d4f036585106f143b08a28e479862
41281f06c5afae0a228d8db85ea6eb105901a6f1
/AdapterBridge/src/test/TestClass.java
1ae577b40c8017c7ea5211bdf15f06af000b22c8
[]
no_license
xilemi/2021-Design-pattern
2eae0aef2efa0186421dcb7c4fc7121c131e0585
a61022b4928b132fd7fb7dedd4a466a760c723f2
refs/heads/master
2023-06-08T01:49:58.965023
2021-06-19T06:46:38
2021-06-19T06:46:38
345,996,121
0
0
null
null
null
null
UTF-8
Java
false
false
645
java
package test; import birdge.BirtShowImpl1; import birdge.BirtShowImpl2; import birdge.BirtShowJdbcData; import birdge.BirtShowTextData; public class TestClass { public static void main(String[] args){ BirtShowTextData showText=new BirtShowTextData(new BirtShowImpl1()); showText.showBirt(); BirtShowJdbcData showJdbc =new BirtShowJdbcData(new BirtShowImpl1()); showJdbc.showBirt(); BirtShowTextData showText1 =new BirtShowTextData(new BirtShowImpl2()); showText1.showBirt(); BirtShowTextData showJdbc1=new BirtShowTextData(new BirtShowImpl2()); showJdbc1.showBirt(); } }
[ "xilemifan" ]
xilemifan
27dd8fc5157f61e4f8b208ea836745dc862f1073
a1406a5542ec1e07fca4a8bf51960892a250cc1a
/Sistema_Java/StorePhoneDoctor/src/modelo/SqlUsuarios.java
3e6cb81ec9ea6e3d421fd3865bbdfbdab6831871
[]
no_license
PatyLuPrz/ProyectoFinal
606a2e4debc14a548e17b5cf213f5fa6c058defe
84155eb50b1ea52b93a60d31b7f831de02725090
refs/heads/master
2018-11-10T00:05:57.764040
2018-08-22T19:39:57
2018-08-22T19:39:57
134,033,691
1
0
null
null
null
null
UTF-8
Java
false
false
5,020
java
package modelo; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; /** * * @author beto */ public class SqlUsuarios extends Conexion { public boolean registrarUsers(usuarios usr) { //Metodo para registrar un usuario PreparedStatement ps = null; //variable de Statement Connection con = (Connection) getConexion(); //Se obtiene la conexion para la clase String sqlPro = "INSERT INTO usuarios (USERNAME_US, EMAIL_US, CONTRASENA_US, NOMBRE_US, AP_US, AM_US, TIPO_US) VALUES(?,?,?,?,?,?,?)"; try { ps = (PreparedStatement) con.prepareStatement(sqlPro); ps.setString(1, usr.getUsername()); ps.setString(2, usr.getEmail_user()); ps.setString(3, usr.getContrasena_user()); ps.setString(4, usr.getNombre_user()); ps.setString(5, usr.getAp_user()); ps.setString(6, usr.getAm_user()); ps.setString(7, usr.getTipo_user()); ps.execute(); return true; } catch (SQLException ex) { Logger.getLogger(SqlUsuarios.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Error" + ex); return false; } } public boolean modificarUsers(usuarios usr) { //Metodo para registrar un usuario PreparedStatement ps = null; //variable de Statement Connection con = (Connection) getConexion(); //Se obtiene la conexion para la clase String sqlPro = "UPDATE usuarios SET EMAIL_US=?, NOMBRE_US=?, AP_US=?, AM_US=?, TIPO_US=? WHERE USERNAME_US = ?"; try { ps = (PreparedStatement) con.prepareStatement(sqlPro); ps.setString(6, usr.getUsername()); ps.setString(1, usr.getEmail_user()); ps.setString(2, usr.getNombre_user()); ps.setString(3, usr.getAp_user()); ps.setString(4, usr.getAm_user()); ps.setString(5, usr.getTipo_user()); ps.execute(); return true; } catch (SQLException ex) { Logger.getLogger(SqlUsuarios.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Error" + ex); return false; } } public boolean login(usuarios usr) { //Se valida si un Usuario existe para negar el registro PreparedStatement ps = null; //variable de Statement ResultSet rs = null; Connection con = (Connection) getConexion(); //Se obtiene la conexion para la clase String sql = "SELECT USERNAME_US, EMAIL_US, CONTRASENA_US, NOMBRE_US, TIPO_US FROM usuarios WHERE USERNAME_US = ?"; try { ps = (PreparedStatement) con.prepareStatement(sql); ps.setString(1, usr.getUsername()); rs = ps.executeQuery(); if (rs.next()) { if (usr.getContrasena_user().equals(rs.getString(3))) { usr.setUsername(rs.getString(1)); usr.setNombre_user(rs.getString(4)); usr.setTipo_user(rs.getString(5)); return true; } else { return false; } } return false; } catch (SQLException ex) { Logger.getLogger(SqlUsuarios.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Error" + ex); return false; } } public int existeUsuario(String usuario) { //Se valida si un Usuario existe para negar el registro PreparedStatement ps = null; //variable de Statement ResultSet rs = null; Connection con = (Connection) getConexion(); //Se obtiene la conexion para la clase String sql = "SELECT count(USERNAME_US) FROM usuarios WHERE USERNAME_US = ?"; try { ps = (PreparedStatement) con.prepareStatement(sql); ps.setString(1, usuario); rs = ps.executeQuery(); if (rs.next()) { return rs.getInt(1); } return 1; } catch (SQLException ex) { Logger.getLogger(SqlUsuarios.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Error" + ex); return 1; } } public boolean esEmail(String correo) { // Patrón para validar el email Pattern pattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"); //Se indica con que caracteres debe iniciar el String o la Cadena Matcher mather = pattern.matcher(correo); return mather.find();//Regresa el valor final si con los parametros que se le indican } }
[ "37199801+LuisNorberto1998@users.noreply.github.com" ]
37199801+LuisNorberto1998@users.noreply.github.com
347eea674c1db2414ee4774b789edd28efe425a5
e8c09a9b108855cdecb474af007feccd5e803d06
/src/main/java/java1702/javase/exam5/E3.java
87fc30e73a5f615d2f7274df1ee18683f4205b9e
[]
no_license
qq666888/java
2809ca1a94380315a06f9516af2e03f12b511afd
23c5364a6ceaa9fdacd17dc299b51a3b05a866a1
refs/heads/master
2021-01-17T11:33:52.733042
2017-05-12T08:24:58
2017-05-12T08:24:58
84,040,057
0
0
null
null
null
null
UTF-8
Java
false
false
1,210
java
package java1702.javase.exam5; import java.util.Arrays; /** * Created by $qiqi * on 2017/4/15. * java */ public class E3 { public static void main(String[] args){ String s0 = "123,45,25,85"; S1.S2(s0); } } class S1{ public static String s11(String s0){ String[] arr = s0.split(","); for(int i =0; i<arr.length-1;i++){ int a = Integer.parseInt(arr[i]); for(int j=i+1;j<arr.length;j++){ int b = Integer.parseInt(arr[j]); String aa; if(a>b){ aa = arr[i]; arr[i] = arr[j]; arr[j] = aa; a = Integer.parseInt(arr[i]); } } } String c =""; for(String i: arr){ c +=i +" "; } return c; } public static void S2(String str) { String[] arr = str.split(","); int[] num = new int[arr.length]; for (int i = 0; i < arr.length; i++) { num[i] = Integer.parseInt(arr[i]); } Arrays.sort(num); for (int i : num) { System.out.print(i + " "); } } }
[ "1096161287@qq.com" ]
1096161287@qq.com
40f140c89c6fb4e814897e5e28e4a2350b94a408
570b13244e63d7d84f0a473676c9d33f43e90dff
/src/com/javarush/test/level07/lesson12/home02/Solution.java
62872eedfb68ee0f6cab7354abb399ba9de46fce
[]
no_license
madman61rus/JavaRush
e510c00bfbf3e96f9c41510fe86b0f3a5c76cbdc
307223de903d4c9f33f801025323e263d1d9d555
refs/heads/master
2020-07-29T01:12:27.685696
2017-02-06T21:24:09
2017-02-06T21:24:09
73,687,644
0
0
null
null
null
null
UTF-8
Java
false
false
1,283
java
package com.javarush.test.level07.lesson12.home02; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /* Переставить M первых строк в конец списка Ввести с клавиатуры 2 числа N и M. Ввести N строк и заполнить ими список. Переставить M первых строк в конец списка. Вывести список на экран, каждое значение с новой строки. */ public class Solution { public static void main(String[] args) throws IOException { ArrayList<String> list = new ArrayList<String>(); String tmp; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(reader.readLine()); int M = Integer.parseInt(reader.readLine()); for (int i=0; i <=N -1 ; i++) { list.add(reader.readLine()); } for (int i=0; i <= M-1; i++) { tmp = list.get(0); list.add(tmp); list.remove(0); } for (String str: list) { System.out.println(str); } } }
[ "vkompaniec@gmail.com" ]
vkompaniec@gmail.com
4e8d01f8431106abbb2c026008ed8d4f62b2b56b
49780a6ce2ac7c2ae658ce148ce7dffe402e9930
/build/generated/source/proto/main/javalite/com/heroiclabs/nakama/api/ChannelMessageOrBuilder.java
9497805332402df64a2f529e64565f74d9463117
[ "Apache-2.0" ]
permissive
rieseted/nakama-java
e2c2b6382d6d8f8b296882194b6d8f6e0748304b
3814e6e63a083e6e455891c6ee9b032c96c9c7d2
refs/heads/master
2020-06-19T19:32:32.462113
2019-06-19T11:13:42
2019-06-19T11:13:42
null
0
0
null
null
null
null
UTF-8
Java
false
true
3,723
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: github.com/heroiclabs/nakama/api/api.proto package com.heroiclabs.nakama.api; public interface ChannelMessageOrBuilder extends // @@protoc_insertion_point(interface_extends:nakama.api.ChannelMessage) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * The channel this message belongs to. * </pre> * * <code>optional string channel_id = 1;</code> */ java.lang.String getChannelId(); /** * <pre> * The channel this message belongs to. * </pre> * * <code>optional string channel_id = 1;</code> */ com.google.protobuf.ByteString getChannelIdBytes(); /** * <pre> * The unique ID of this message. * </pre> * * <code>optional string message_id = 2;</code> */ java.lang.String getMessageId(); /** * <pre> * The unique ID of this message. * </pre> * * <code>optional string message_id = 2;</code> */ com.google.protobuf.ByteString getMessageIdBytes(); /** * <pre> * The code representing a message type or category. * </pre> * * <code>optional .google.protobuf.Int32Value code = 3;</code> */ boolean hasCode(); /** * <pre> * The code representing a message type or category. * </pre> * * <code>optional .google.protobuf.Int32Value code = 3;</code> */ com.google.protobuf.Int32Value getCode(); /** * <pre> * Message sender, usually a user ID. * </pre> * * <code>optional string sender_id = 4;</code> */ java.lang.String getSenderId(); /** * <pre> * Message sender, usually a user ID. * </pre> * * <code>optional string sender_id = 4;</code> */ com.google.protobuf.ByteString getSenderIdBytes(); /** * <pre> * The username of the message sender, if any. * </pre> * * <code>optional string username = 5;</code> */ java.lang.String getUsername(); /** * <pre> * The username of the message sender, if any. * </pre> * * <code>optional string username = 5;</code> */ com.google.protobuf.ByteString getUsernameBytes(); /** * <pre> * The content payload. * </pre> * * <code>optional string content = 6;</code> */ java.lang.String getContent(); /** * <pre> * The content payload. * </pre> * * <code>optional string content = 6;</code> */ com.google.protobuf.ByteString getContentBytes(); /** * <pre> * The UNIX time when the message was created. * </pre> * * <code>optional .google.protobuf.Timestamp create_time = 7;</code> */ boolean hasCreateTime(); /** * <pre> * The UNIX time when the message was created. * </pre> * * <code>optional .google.protobuf.Timestamp create_time = 7;</code> */ com.google.protobuf.Timestamp getCreateTime(); /** * <pre> * The UNIX time when the message was last updated. * </pre> * * <code>optional .google.protobuf.Timestamp update_time = 8;</code> */ boolean hasUpdateTime(); /** * <pre> * The UNIX time when the message was last updated. * </pre> * * <code>optional .google.protobuf.Timestamp update_time = 8;</code> */ com.google.protobuf.Timestamp getUpdateTime(); /** * <pre> * True if the message was persisted to the channel's history, false otherwise. * </pre> * * <code>optional .google.protobuf.BoolValue persistent = 9;</code> */ boolean hasPersistent(); /** * <pre> * True if the message was persisted to the channel's history, false otherwise. * </pre> * * <code>optional .google.protobuf.BoolValue persistent = 9;</code> */ com.google.protobuf.BoolValue getPersistent(); }
[ "mo@heroiclabs.com" ]
mo@heroiclabs.com
31360ce4fd2d1a33d18614b270caff8c278468c8
e7230d5c3278a27964b3f41994120a9f0bc20ca7
/src/main/java/com/tzy/meta/UIDMeta.java
846c752f09118123534c15d804eef2c173af912b
[]
no_license
scapegoat1630/tzy-tsdb
8e2024aec2394f6d2c8d214afdcade1454da1731
7101571aa374df8cc75895f974db5c51512919c8
refs/heads/master
2021-09-09T10:03:31.540051
2018-03-14T11:38:46
2018-03-14T11:38:46
125,203,261
0
0
null
null
null
null
UTF-8
Java
false
false
22,201
java
// This file is part of OpenTSDB. // Copyright (C) 2013 The OpenTSDB Authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 2.1 of the License, or (at your // option) any later version. This program is distributed in the hope that it // will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser // General Public License for more details. You should have received a copy // of the GNU Lesser General Public License along with this program. If not, // see <http://www.gnu.org/licenses/>. package com.tzy.meta; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.hbase.async.DeleteRequest; import org.hbase.async.GetRequest; import org.hbase.async.HBaseException; import org.hbase.async.KeyValue; import org.hbase.async.PutRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import com.tzy.core.TSDB; import com.tzy.uid.UniqueId; import com.tzy.uid.UniqueId.UniqueIdType; import com.tzy.utils.JSON; import com.tzy.utils.JSONException; /** * UIDMeta objects are associated with the UniqueId of metrics, tag names * or tag values. When a new metric, tagk or tagv is generated, a UIDMeta object * will also be written to storage with only the uid, type and name filled out. * <p> * Users are allowed to edit the following fields: * <ul><li>display_name</li> * <li>description</li> * <li>notes</li> * <li>custom</li></ul> * The {@code name}, {@code uid}, {@code type} and {@code created} fields can * only be modified by the system and are usually done so on object creation. * <p> * When you call {@link #syncToStorage} on this object, it will verify that the * UID object this meta data is linked with still exists. Then it will fetch the * existing data and copy changes, overwriting the user fields if specific * (e.g. via a PUT command). If overwriting is not called for (e.g. a POST was * issued), then only the fields provided by the user will be saved, preserving * all of the other fields in storage. Hence the need for the {@code changed} * hash map and the {@link #syncMeta} method. * <p> * Note that the HBase specific storage code will be removed once we have a DAL * @since 2.0 */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = Visibility.PUBLIC_ONLY) public class UIDMeta { private static final Logger LOG = LoggerFactory.getLogger(UIDMeta.class); /** Charset used to convert Strings to byte arrays and back. */ private static final Charset CHARSET = Charset.forName("ISO-8859-1"); /** The single column family used by this class. */ private static final byte[] FAMILY = "name".getBytes(CHARSET); /** A hexadecimal representation of the UID this metadata is associated with */ private String uid = ""; /** The type of UID this metadata represents */ @JsonDeserialize(using = JSON.UniqueIdTypeDeserializer.class) private UniqueIdType type = null; /** * This is the identical name of what is stored in the UID table * It cannot be overridden */ private String name = ""; /** * An optional, user supplied name used for display purposes only * If this field is empty, the {@link name} field should be used */ private String display_name = ""; /** A short description of what this object represents */ private String description = ""; /** Optional, detailed notes about what the object represents */ private String notes = ""; /** A timestamp of when this UID was first recorded by OpenTSDB in seconds */ private long created = 0; /** Optional user supplied key/values */ private HashMap<String, String> custom = null; /** Tracks fields that have changed by the user to avoid overwrites */ private final HashMap<String, Boolean> changed = new HashMap<String, Boolean>(); /** * Default constructor * Initializes the the changed map */ public UIDMeta() { initializeChangedMap(); } /** * Constructor used for overwriting. Will not reset the name or created values * in storage. * @param type Type of UID object * @param uid UID of the object */ public UIDMeta(final UniqueIdType type, final String uid) { this.type = type; this.uid = uid; initializeChangedMap(); } /** * Constructor used by TSD only to create a new UID with the given data and * the current system time for {@code createdd} * @param type Type of UID object * @param uid UID of the object * @param name Name of the UID */ public UIDMeta(final UniqueIdType type, final byte[] uid, final String name) { this.type = type; this.uid = UniqueId.uidToString(uid); this.name = name; created = System.currentTimeMillis() / 1000; initializeChangedMap(); changed.put("created", true); } /** @return a string with details about this object */ @Override public String toString() { return "'" + type.toString() + ":" + uid + "'"; } /** * Attempts a CompareAndSet storage call, loading the object from storage, * synchronizing changes, and attempting a put. * <b>Note:</b> If the local object didn't have any fields set by the caller * then the data will not be written. * @param tsdb The TSDB to use for storage access * @param overwrite When the RPC method is PUT, will overwrite all user * accessible fields * @return True if the storage call was successful, false if the object was * modified in storage during the CAS call. If false, retry the call. Other * failures will result in an exception being thrown. * @throws HBaseException if there was an issue fetching * @throws IllegalArgumentException if parsing failed * @throws NoSuchUniqueId If the UID does not exist * @throws IllegalStateException if the data hasn't changed. This is OK! * @throws JSONException if the object could not be serialized */ public Deferred<Boolean> syncToStorage(final TSDB tsdb, final boolean overwrite) { if (uid == null || uid.isEmpty()) { throw new IllegalArgumentException("Missing UID"); } if (type == null) { throw new IllegalArgumentException("Missing type"); } boolean has_changes = false; for (Map.Entry<String, Boolean> entry : changed.entrySet()) { if (entry.getValue()) { has_changes = true; break; } } if (!has_changes) { LOG.debug(this + " does not have changes, skipping sync to storage"); throw new IllegalStateException("No changes detected in UID meta data"); } /** * Callback used to verify that the UID to name mapping exists. Uses the TSD * for verification so the name may be cached. If the name does not exist * it will throw a NoSuchUniqueId and the meta data will not be saved to * storage */ final class NameCB implements Callback<Deferred<Boolean>, String> { private final UIDMeta local_meta; public NameCB(final UIDMeta meta) { local_meta = meta; } /** * Nested callback used to merge and store the meta data after verifying * that the UID mapping exists. It has to access the {@code local_meta} * object so that's why it's nested within the NameCB class */ final class StoreUIDMeta implements Callback<Deferred<Boolean>, ArrayList<KeyValue>> { /** * Executes the CompareAndSet after merging changes * @return True if the CAS was successful, false if the stored data * was modified during flight. */ @Override public Deferred<Boolean> call(final ArrayList<KeyValue> row) throws Exception { final UIDMeta stored_meta; if (row == null || row.isEmpty()) { stored_meta = null; } else { stored_meta = JSON.parseToObject(row.get(0).value(), UIDMeta.class); stored_meta.initializeChangedMap(); } final byte[] original_meta = row == null || row.isEmpty() ? new byte[0] : row.get(0).value(); if (stored_meta != null) { local_meta.syncMeta(stored_meta, overwrite); } // verify the name is set locally just to be safe if (name == null || name.isEmpty()) { local_meta.name = name; } final PutRequest put = new PutRequest(tsdb.uidTable(), UniqueId.stringToUid(uid), FAMILY, (type.toString().toLowerCase() + "_meta").getBytes(CHARSET), local_meta.getStorageJSON()); return tsdb.getClient().compareAndSet(put, original_meta); } } /** * NameCB method that fetches the object from storage for merging and * use in the CAS call * @return The results of the {@link #StoreUIDMeta} callback */ @Override public Deferred<Boolean> call(final String name) throws Exception { final GetRequest get = new GetRequest(tsdb.uidTable(), UniqueId.stringToUid(uid)); get.family(FAMILY); get.qualifier((type.toString().toLowerCase() + "_meta").getBytes(CHARSET)); // #2 deferred return tsdb.getClient().get(get) .addCallbackDeferring(new StoreUIDMeta()); } } // start the callback chain by veryfing that the UID name mapping exists return tsdb.getUidName(type, UniqueId.stringToUid(uid)) .addCallbackDeferring(new NameCB(this)); } /** * Attempts to store a blank, new UID meta object in the proper location. * <b>Warning:</b> This should not be called by user accessible methods as it * will overwrite any data already in the column. This method does not use * a CAS, instead it uses a PUT to overwrite anything in the column. * @param tsdb The TSDB to use for calls * @return A deferred without meaning. The response may be null and should * only be used to track completion. * @throws HBaseException if there was an issue writing to storage * @throws IllegalArgumentException if data was missing * @throws JSONException if the object could not be serialized */ public Deferred<Object> storeNew(final TSDB tsdb) { if (uid == null || uid.isEmpty()) { throw new IllegalArgumentException("Missing UID"); } if (type == null) { throw new IllegalArgumentException("Missing type"); } if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Missing name"); } final PutRequest put = new PutRequest(tsdb.uidTable(), UniqueId.stringToUid(uid), FAMILY, (type.toString().toLowerCase() + "_meta").getBytes(CHARSET), UIDMeta.this.getStorageJSON()); return tsdb.getClient().put(put); } /** * Attempts to delete the meta object from storage * @param tsdb The TSDB to use for access to storage * @return A deferred without meaning. The response may be null and should * only be used to track completion. * @throws HBaseException if there was an issue * @throws IllegalArgumentException if data was missing (uid and type) */ public Deferred<Object> delete(final TSDB tsdb) { if (uid == null || uid.isEmpty()) { throw new IllegalArgumentException("Missing UID"); } if (type == null) { throw new IllegalArgumentException("Missing type"); } final DeleteRequest delete = new DeleteRequest(tsdb.uidTable(), UniqueId.stringToUid(uid), FAMILY, (type.toString().toLowerCase() + "_meta").getBytes(CHARSET)); return tsdb.getClient().delete(delete); } /** * Convenience overload of {@code getUIDMeta(TSDB, UniqueIdType, byte[])} * @param tsdb The TSDB to use for storage access * @param type The type of UID to fetch * @param uid The ID of the meta to fetch * @return A UIDMeta from storage or a default * @throws HBaseException if there was an issue fetching * @throws NoSuchUniqueId If the UID does not exist */ public static Deferred<UIDMeta> getUIDMeta(final TSDB tsdb, final UniqueIdType type, final String uid) { return getUIDMeta(tsdb, type, UniqueId.stringToUid(uid)); } /** * Verifies the UID object exists, then attempts to fetch the meta from * storage and if not found, returns a default object. * <p> * The reason for returning a default object (with the type, uid and name set) * is due to users who may have just enabled meta data or have upgraded; we * want to return valid data. If they modify the entry, it will write to * storage. You can tell it's a default if the {@code created} value is 0. If * the meta was generated at UID assignment or updated by the meta sync CLI * command, it will have a valid created timestamp. * @param tsdb The TSDB to use for storage access * @param type The type of UID to fetch * @param uid The ID of the meta to fetch * @return A UIDMeta from storage or a default * @throws HBaseException if there was an issue fetching * @throws NoSuchUniqueId If the UID does not exist */ public static Deferred<UIDMeta> getUIDMeta(final TSDB tsdb, final UniqueIdType type, final byte[] uid) { /** * Callback used to verify that the UID to name mapping exists. Uses the TSD * for verification so the name may be cached. If the name does not exist * it will throw a NoSuchUniqueId and the meta data will not be returned. * This helps in case the user deletes a UID but the meta data is still * stored. The fsck utility can be used later to cleanup orphaned objects. */ class NameCB implements Callback<Deferred<UIDMeta>, String> { /** * Called after verifying that the name mapping exists * @return The results of {@link #FetchMetaCB} */ @Override public Deferred<UIDMeta> call(final String name) throws Exception { /** * Inner class called to retrieve the meta data after verifying that the * name mapping exists. It requires the name to set the default, hence * the reason it's nested. */ class FetchMetaCB implements Callback<Deferred<UIDMeta>, ArrayList<KeyValue>> { /** * Called to parse the response of our storage GET call after * verification * @return The stored UIDMeta or a default object if the meta data * did not exist */ @Override public Deferred<UIDMeta> call(ArrayList<KeyValue> row) throws Exception { if (row == null || row.isEmpty()) { // return the default final UIDMeta meta = new UIDMeta(); meta.uid = UniqueId.uidToString(uid); meta.type = type; meta.name = name; return Deferred.fromResult(meta); } final UIDMeta meta = JSON.parseToObject(row.get(0).value(), UIDMeta.class); // overwrite the name and UID meta.name = name; meta.uid = UniqueId.uidToString(uid); // fix missing types if (meta.type == null) { final String qualifier = new String(row.get(0).qualifier(), CHARSET); meta.type = UniqueId.stringToUniqueIdType(qualifier.substring(0, qualifier.indexOf("_meta"))); } meta.initializeChangedMap(); return Deferred.fromResult(meta); } } final GetRequest get = new GetRequest(tsdb.uidTable(), uid); get.family(FAMILY); get.qualifier((type.toString().toLowerCase() + "_meta").getBytes(CHARSET)); return tsdb.getClient().get(get).addCallbackDeferring(new FetchMetaCB()); } } // verify that the UID is still in the map before fetching from storage return tsdb.getUidName(type, uid).addCallbackDeferring(new NameCB()); } /** * Syncs the local object with the stored object for atomic writes, * overwriting the stored data if the user issued a PUT request * <b>Note:</b> This method also resets the {@code changed} map to false * for every field * @param meta The stored object to sync from * @param overwrite Whether or not all user mutable data in storage should be * replaced by the local object */ private void syncMeta(final UIDMeta meta, final boolean overwrite) { // copy non-user-accessible data first if (meta.uid != null && !meta.uid.isEmpty()) { uid = meta.uid; } if (meta.name != null && !meta.name.isEmpty()) { name = meta.name; } if (meta.type != null) { type = meta.type; } if (meta.created > 0 && (meta.created < created || created == 0)) { created = meta.created; } // handle user-accessible stuff if (!overwrite && !changed.get("display_name")) { display_name = meta.display_name; } if (!overwrite && !changed.get("description")) { description = meta.description; } if (!overwrite && !changed.get("notes")) { notes = meta.notes; } if (!overwrite && !changed.get("custom")) { custom = meta.custom; } // reset changed flags initializeChangedMap(); } /** * Sets or resets the changed map flags */ private void initializeChangedMap() { // set changed flags changed.put("display_name", false); changed.put("description", false); changed.put("notes", false); changed.put("custom", false); changed.put("created", false); } /** * Formats the JSON output for writing to storage. It drops objects we don't * need or want to store (such as the UIDMeta objects or the total dps) to * save space. It also serializes in order so that we can make a proper CAS * call. Otherwise the POJO serializer may place the fields in any order * and CAS calls would fail all the time. * @return A byte array to write to storage */ private byte[] getStorageJSON() { // 256 bytes is a good starting value, assumes default info final ByteArrayOutputStream output = new ByteArrayOutputStream(256); try { final JsonGenerator json = JSON.getFactory().createGenerator(output); json.writeStartObject(); json.writeStringField("type", type.toString()); json.writeStringField("displayName", display_name); json.writeStringField("description", description); json.writeStringField("notes", notes); json.writeNumberField("created", created); if (custom == null) { json.writeNullField("custom"); } else { json.writeObjectFieldStart("custom"); for (Map.Entry<String, String> entry : custom.entrySet()) { json.writeStringField(entry.getKey(), entry.getValue()); } json.writeEndObject(); } json.writeEndObject(); json.close(); return output.toByteArray(); } catch (IOException e) { throw new RuntimeException("Unable to serialize UIDMeta", e); } } // Getters and Setters -------------- /** @return the uid as a hex encoded string */ public String getUID() { return uid; } /** @return the type of UID represented */ public UniqueIdType getType() { return type; } /** @return the name of the UID object */ public String getName() { return name; } /** @return optional display name, use {@code name} if empty */ public String getDisplayName() { return display_name; } /** @return optional description */ public String getDescription() { return description; } /** @return optional notes */ public String getNotes() { return notes; } /** @return when the UID was first assigned, may be 0 if unknown */ public long getCreated() { return created; } /** @return optional map of custom values from the user */ public Map<String, String> getCustom() { return custom; } /** @param display_name an optional descriptive name for the UID */ public void setDisplayName(final String display_name) { if (!this.display_name.equals(display_name)) { changed.put("display_name", true); this.display_name = display_name; } } /** @param description an optional description of the UID */ public void setDescription(final String description) { if (!this.description.equals(description)) { changed.put("description", true); this.description = description; } } /** @param notes optional notes */ public void setNotes(final String notes) { if (!this.notes.equals(notes)) { changed.put("notes", true); this.notes = notes; } } /** @param custom the custom to set */ public void setCustom(final Map<String, String> custom) { // equivalency of maps is a pain, users have to submit the whole map // anyway so we'll just mark it as changed every time we have a non-null // value if (this.custom != null || custom != null) { changed.put("custom", true); this.custom = new HashMap<String, String>(custom); } } /** @param created the created timestamp Unix epoch in seconds */ public final void setCreated(final long created) { if (this.created != created) { changed.put("created", true); this.created = created; } } }
[ "zhangpeng12@jd.com" ]
zhangpeng12@jd.com
9a8ebf0ee8de3258e56a09fd0b26ac3aa696db6d
995f73d30450a6dce6bc7145d89344b4ad6e0622
/MATE-20_EMUI_11.0.0/src/main/java/android/bluetooth/UidTraffic.java
25fe375cb51ce0d067fbaeadf4af7c0e0b921836
[]
no_license
morningblu/HWFramework
0ceb02cbe42585d0169d9b6c4964a41b436039f5
672bb34094b8780806a10ba9b1d21036fd808b8e
refs/heads/master
2023-07-29T05:26:14.603817
2021-09-03T05:23:34
2021-09-03T05:23:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,272
java
package android.bluetooth; import android.os.Parcel; import android.os.Parcelable; public class UidTraffic implements Cloneable, Parcelable { public static final Parcelable.Creator<UidTraffic> CREATOR = new Parcelable.Creator<UidTraffic>() { /* class android.bluetooth.UidTraffic.AnonymousClass1 */ @Override // android.os.Parcelable.Creator public UidTraffic createFromParcel(Parcel source) { return new UidTraffic(source); } @Override // android.os.Parcelable.Creator public UidTraffic[] newArray(int size) { return new UidTraffic[size]; } }; private final int mAppUid; private long mRxBytes; private long mTxBytes; public UidTraffic(int appUid) { this.mAppUid = appUid; } public UidTraffic(int appUid, long rx, long tx) { this.mAppUid = appUid; this.mRxBytes = rx; this.mTxBytes = tx; } UidTraffic(Parcel in) { this.mAppUid = in.readInt(); this.mRxBytes = in.readLong(); this.mTxBytes = in.readLong(); } @Override // android.os.Parcelable public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.mAppUid); dest.writeLong(this.mRxBytes); dest.writeLong(this.mTxBytes); } public void setRxBytes(long bytes) { this.mRxBytes = bytes; } public void setTxBytes(long bytes) { this.mTxBytes = bytes; } public void addRxBytes(long bytes) { this.mRxBytes += bytes; } public void addTxBytes(long bytes) { this.mTxBytes += bytes; } public int getUid() { return this.mAppUid; } public long getRxBytes() { return this.mRxBytes; } public long getTxBytes() { return this.mTxBytes; } @Override // android.os.Parcelable public int describeContents() { return 0; } @Override // java.lang.Object public UidTraffic clone() { return new UidTraffic(this.mAppUid, this.mRxBytes, this.mTxBytes); } @Override // java.lang.Object public String toString() { return "UidTraffic{mAppUid=" + this.mAppUid + ", mRxBytes=" + this.mRxBytes + ", mTxBytes=" + this.mTxBytes + '}'; } }
[ "dstmath@163.com" ]
dstmath@163.com
75ceea267b8e97c1526f5d9bebf4f3a78e52a782
07d99d83e82b82fc3d8ed1c53633d0fe52b78486
/tools/totem.trm/src/MM_uncertainty/DataType.java
a3396dd97f0c75c06ffe221be5637f2249cc624e
[]
no_license
MDEGroup/MDEProfiler
25ccdd38725014b9d912aa91520dd7ef227e5dab
96222e86dfb393cd0c86882606902c230da1f831
refs/heads/master
2020-04-12T22:59:37.989363
2018-12-24T09:41:47
2018-12-24T09:41:47
162,804,855
0
0
null
null
null
null
UTF-8
Java
false
false
364
java
/** */ package MM_uncertainty; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Data Type</b></em>'. * <!-- end-user-doc --> * * * @see MM_uncertainty.MM_uncertaintyPackage#getDataType() * @model abstract="true" * @generated */ public interface DataType extends EObject { } // DataType
[ "juri.di.rocco@gmail.com" ]
juri.di.rocco@gmail.com
64a72fa00a744ad86add5281535e4a44f1d035d5
872095f6ca1d7f252a1a3cb90ad73e84f01345a2
/mediatek/proprietary/packages/apps/RCSe/RcsStack/src/com/orangelabs/rcs/core/ims/security/cert/KeyStoreManager.java
2a9ba7108ded99e0540bc927a5bd80236aa31a01
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
colinovski/mt8163-vendor
724c49a47e1fa64540efe210d26e72c883ee591d
2006b5183be2fac6a82eff7d9ed09c2633acafcc
refs/heads/master
2020-07-04T12:39:09.679221
2018-01-20T09:11:52
2018-01-20T09:11:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
25,070
java
/******************************************************************************* * Software Name : RCS IMS Stack * * Copyright (C) 2010 France Telecom S.A. * * 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.orangelabs.rcs.core.ims.security.cert; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.sql.Date; import java.math.BigInteger; import com.android.org.bouncycastle.x509.X509V3CertificateGenerator; import com.android.org.bouncycastle.jce.X509Principal; import com.orangelabs.rcs.platform.AndroidFactory; import com.orangelabs.rcs.provider.settings.RcsSettings; import com.orangelabs.rcs.provider.settings.RcsSettingsData; import java.security.KeyPair; import java.security.KeyPairGenerator; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManagerFactory; import com.orangelabs.rcs.utils.logger.Logger; import android.content.Context; /** * Keystore manager for certificates * * @author B. JOGUET * @author Deutsche Telekom AG */ public class KeyStoreManager { /** * M: Modified and added for achieving MSRPoTLS related feature. @{ */ /** * Client self signed keystore */ public final static String CLIENT_KEYSTORE = "client.bks"; /** * Keystore name */ private final static String KEYSTORE_NAME = "server.bks"; /** * Keystore password */ public final static String KEYSTORE_PASSWORD = "1234567"; /** * M: Added to achieve the SDPoTLS and MSRPoTLS implementation. @{ */ /** * Certificate name in asset */ public static final String CERTIFICATE_NAME = "cmcc_reg_server"; public static final String CERTIFICATE_SUFFIXE = ".cer"; public static final int CERTIFICATE_NUM = 2; /** * Keystore type */ public final static String KEYSTORE_TYPE = KeyStore.getDefaultType(); /** * @} */ /** * Private key alias */ public final static String PRIVATE_KEY_ALIAS = "MyPrivateKey"; private static Logger logger = Logger.getLogger(KeyStoreManager.class.getName()); private static final String X509_NAME = "CN=Mediatek, OU=None, O=None, L=None, C=None"; private static final String SIGNATURE_ALGORITHM = "MD5WithRSAEncryption"; private static final String DIGEST_ALGORITHM = "SHA1"; private static final String GENERATOR_RSA = "RSA"; private static final String AlGORITHM_SHA = "SHA-1 "; private static String sFingerPrint = null; private static char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** * Get finger print. * * @return The finger print. */ public static String getFingerPrint() { logger.debug("getFingerPrint" + sFingerPrint); return sFingerPrint; } /** * returns self-signed keystore path. * * @return keystore path */ public static String getSelfSignedKeystorePath() { return AndroidFactory.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + CLIENT_KEYSTORE; } /** * @} */ /** * Load the keystore manager * * @throws KeyStoreManagerException * @throws IOException * @throws KeyStoreException */ public static void loadKeyStore() throws KeyStoreManagerException, IOException, KeyStoreException { // Create the keystore if not present if (!KeyStoreManager.isKeystoreExists(KeyStoreManager.getKeystorePath())) { KeyStoreManager.createKeyStore(); } // Add certificates if not present String certRoot = RcsSettings.getInstance().getTlsCertificateRoot(); if ((certRoot != null) && (certRoot.length() > 0)) { if (!KeyStoreManager.isCertificateEntry(certRoot)) { KeyStoreManager.addCertificates(certRoot); } } String certIntermediate = RcsSettings.getInstance().getTlsCertificateIntermediate(); if ((certIntermediate != null) && (certIntermediate.length() > 0)) { if (!KeyStoreManager.isCertificateEntry(certIntermediate)) { KeyStoreManager.addCertificates(certIntermediate); } } /** * M: Modified to achieve the TLS related implementation-Get * vodafone's self-signed certificate and do sip register over * TLS. @{ */ Context context = AndroidFactory.getApplicationContext(); if (context != null) { //Add all custom certificate to keystore for(int i=0 ; i < CERTIFICATE_NUM; ++i){ InputStream is = null; try{ is = context.getAssets().open( CERTIFICATE_NAME + i + CERTIFICATE_SUFFIXE); if (!KeyStoreManager.isCertificateEntry(is,CERTIFICATE_NAME + i + CERTIFICATE_SUFFIXE)) { KeyStoreManager.addCertificate(is,CERTIFICATE_NAME + i + CERTIFICATE_SUFFIXE); } }catch (IOException e) { }finally{ if(is != null){ is.close(); } } } } /** * @} */ } /** * Create the RCS client self signed keystore. * * @throws KeyStoreManagerException The key store manager exception. */ public static void createClientKeyStore() throws KeyStoreManagerException { if (logger.isActivated()) { logger.debug("createClientKeyStore entry"); } File file = new File(getSelfSignedKeystorePath()); if ((file == null) || (!file.exists())) { FileOutputStream fos = null; try { fos = new FileOutputStream(getSelfSignedKeystorePath()); // Build empty keystore KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE); ks.load(null, KEYSTORE_PASSWORD.toCharArray()); // Export keystore in a file ks.store(fos, KEYSTORE_PASSWORD.toCharArray()); } catch (Exception e) { throw new KeyStoreManagerException(e.getMessage()); } finally { try { if (fos != null) { fos.close(); } } catch (IOException e) { if (logger.isActivated()) { logger.debug("createClientKeyStore IOException"); } e.printStackTrace(); } } } if (logger.isActivated()) { logger.debug("createClientKeyStore exit"); } } /** * Check if a certificate is in the keystore. * * @param inputStream certificate stream * @param name certificate name * @return true if available * @throws KeyStoreException * @throws Exception */ public static boolean isCertificateEntry(InputStream inputStream, String name) throws KeyStoreManagerException, KeyStoreException { FileInputStream fis = null; boolean result = false; if (KeyStoreManager.isKeystoreExists(getKeystorePath())) { try { fis = new FileInputStream(getKeystorePath()); // Open the existing keystore KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE); ks.load(fis, KEYSTORE_PASSWORD.toCharArray()); // isCertificateEntry result = ks.isCertificateEntry(buildCertificateAlias(name)); } catch (IOException e) { throw new KeyStoreManagerException(e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new KeyStoreManagerException(e.getMessage()); } catch (CertificateException e) { throw new KeyStoreManagerException(e.getMessage()); } finally { try { if (fis != null) fis.close(); } catch (IOException e) { // Intentionally blank } } } return result; } /** * Add a certificate in the keystore * * @param inputStream certificate stream * @param name certificate name * @throws KeyStoreException * @throws Exception */ public static void addCertificate(InputStream inputStream, String name) throws KeyStoreManagerException, KeyStoreException { if (KeyStoreManager.isKeystoreExists(getKeystorePath())) { FileInputStream fis = null; FileOutputStream fos = null; try { // Open the existing keystore fis = new FileInputStream(getKeystorePath()); KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE); ks.load(fis, KEYSTORE_PASSWORD.toCharArray()); // Get certificate and add in keystore CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream); ks.setCertificateEntry(buildCertificateAlias(name), cert); // save the keystore fos = new FileOutputStream(getKeystorePath()); ks.store(fos, KEYSTORE_PASSWORD.toCharArray()); } catch (IOException e) { throw new KeyStoreManagerException(e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new KeyStoreManagerException(e.getMessage()); } catch (CertificateException e) { throw new KeyStoreManagerException(e.getMessage()); } finally { try { if (fis != null) fis.close(); } catch (IOException e) { // Intentionally blank } try { if (fos != null) fos.close(); } catch (IOException e) { // Intentionally blank } } } } /** * Returns the keystore type * * @return Type */ public static String getKeystoreType() { return KeyStore.getDefaultType(); } /** * Returns the keystore password * * @return Password */ public static String getKeystorePassword() { return KEYSTORE_PASSWORD; } /** * Returns the keystore path * * @return Keystore path */ public static String getKeystorePath() { return AndroidFactory.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + KEYSTORE_NAME; } /** * Test if a keystore is created * * @return True if already created * @throws KeyStoreManagerException */ private static boolean isKeystoreExists(String path) throws KeyStoreManagerException { // Test file File file = new File(path); if ((file == null) || (!file.exists())) return false; // Test keystore FileInputStream fis = null; boolean result = false; try { // Try to open the keystore fis = new FileInputStream(path); KeyStore ks = KeyStore.getInstance(getKeystoreType()); ks.load(fis, KEYSTORE_PASSWORD.toCharArray()); result = true; } catch (FileNotFoundException e) { throw new KeyStoreManagerException(e.getMessage()); } catch (Exception e) { result = false; } finally { try { if (fis != null) fis.close(); } catch (IOException e) { // Intentionally blank } } return result; } /** * Create the RCS keystore * * @throws KeyStoreManagerException */ private static void createKeyStore() throws KeyStoreManagerException { File file = new File(getKeystorePath()); if ((file == null) || (!file.exists())) { FileOutputStream fos = null; try { fos = new FileOutputStream(getKeystorePath()); // Build empty keystore KeyStore ks = KeyStore.getInstance(getKeystoreType()); ks.load(null, KEYSTORE_PASSWORD.toCharArray()); // Export keystore in a file ks.store(fos, KEYSTORE_PASSWORD.toCharArray()); } catch (Exception e) { throw new KeyStoreManagerException(e.getMessage()); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // Intentionally blank } } } } /** * M: Added to generate fingerprint for MSRPoTLS @{ */ private static String dumpHex(byte[] data) { int n = data.length; StringBuffer sb = new StringBuffer(n * 3 - 1); for (int i = 0; i < n; i++) { if (i > 0) { sb.append(':'); } sb.append(HEX_CHARS[(data[i] >> 4) & 0x0F]); sb.append(HEX_CHARS[data[i] & 0x0F]); } return sb.toString(); } /** * Check if a certificate is in the keystore * * @param path Certificate path * @return True if available * @throws KeyStoreManagerException */ private static boolean isCertificateEntry(String path) throws KeyStoreManagerException { FileInputStream fis = null; boolean result = false; if (KeyStoreManager.isKeystoreExists(getKeystorePath())) { try { fis = new FileInputStream(getKeystorePath()); // Open the existing keystore KeyStore ks = KeyStore.getInstance(getKeystoreType()); ks.load(fis, KEYSTORE_PASSWORD.toCharArray()); result = ks.isCertificateEntry(buildCertificateAlias(path)); } catch (Exception e) { throw new KeyStoreManagerException(e.getMessage()); } finally { try { if (fis != null) fis.close(); } catch (IOException e) { // Intentionally blank } } } return result; } /** * Add a certificate or all certificates in folder in the keystore * * @param path certificates path * @throws KeyStoreManagerException */ private static void addCertificates(String path) throws KeyStoreManagerException { if (KeyStoreManager.isKeystoreExists(getKeystorePath())) { FileInputStream fis = null; FileOutputStream fos = null; try { // Open the existing keystore fis = new FileInputStream(getKeystorePath()); KeyStore ks = KeyStore.getInstance(getKeystoreType()); ks.load(fis, KEYSTORE_PASSWORD.toCharArray()); // Open certificates path File pathFile = new File(path); if (pathFile.isDirectory()) { // The path is a folder, add all certificates File[] certificates = pathFile.listFiles(new FilenameFilter() { public boolean accept(File dir, String filename) { return filename.endsWith(RcsSettingsData.CERTIFICATE_FILE_TYPE); } }); if (certificates != null) { for (File file : certificates) { // Get certificate and add in keystore CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream inStream = new FileInputStream(file); X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); ks.setCertificateEntry(buildCertificateAlias(path), cert); // Save the keystore fos = new FileOutputStream(getKeystorePath()); ks.store(fos, KEYSTORE_PASSWORD.toCharArray()); fos.close(); fos = null; } } } else { // The path is a file, add certificate if (path.endsWith(RcsSettingsData.CERTIFICATE_FILE_TYPE)) { // Get certificate and add in keystore CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream inStream = new FileInputStream(path); X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); ks.setCertificateEntry(buildCertificateAlias(path), cert); // Save the keystore fos = new FileOutputStream(getKeystorePath()); ks.store(fos, KEYSTORE_PASSWORD.toCharArray()); } } } catch (Exception e) { throw new KeyStoreManagerException(e.getMessage()); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { // Intentionally blank } try { if (fos != null) { fos.close(); } } catch (IOException e) { // Intentionally blank } } } } /** * Build alias from path * * @param path File path * @return Alias */ private static String buildCertificateAlias(String path) { String alias = ""; File file = new File(path); String filename = file.getName(); long lastModified = file.lastModified(); int lastDotPosition = filename.lastIndexOf('.'); if (lastDotPosition > 0) alias = filename.substring(0, lastDotPosition) + lastModified; else alias = filename + lastModified; return alias; } /** * Returns the fingerprint of a certificate * * @param cert Certificate * @return String as xx:yy:zz */ public static String getCertFingerprint(Certificate cert) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] der = cert.getEncoded(); md.update(der); byte[] digest = md.digest(); return hexify(digest); } catch(Exception e) { return null; } } /** * Hexify a byte array * * @param bytes Byte array * @return String */ private static String hexify(byte bytes[]) { char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; StringBuffer buf = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; ++i) { if (i != 0) { buf.append(":"); } buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]); buf.append(hexDigits[bytes[i] & 0x0f]); } return buf.toString(); } /** * M: Modified for MSRPoTLS @{ */ /** * Initialize a private key with self signed certificate. * * @throws Exception */ @SuppressWarnings("deprecation") public static void initPrivateKeyAndSelfsignedCertificate() throws Exception { if (logger.isActivated()) { logger.debug("initPrivateKeyAndSelfsignedCertificate entry"); } createClientKeyStore(); if (KeyStoreManager.isKeystoreExists(getSelfSignedKeystorePath())) { if (logger.isActivated()) { logger.error("initPrivateKeyAndSelfsignedCertificate key store exist"); } // Open the existing keystore KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE); ks.load(new FileInputStream(getSelfSignedKeystorePath()), KEYSTORE_PASSWORD.toCharArray()); logger.debug("initPrivateKeyAndSelfsignedCertificate 0"); // Generate Key KeyPairGenerator kpg = KeyPairGenerator.getInstance(GENERATOR_RSA); kpg.initialize(1024); KeyPair kp = kpg.generateKeyPair(); // Generate certificate long currentTime = System.currentTimeMillis(); X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(new BigInteger(Long.toString(currentTime))); v3CertGen.setIssuerDN(new X509Principal(X509_NAME)); logger.debug("initPrivateKeyAndSelfsignedCertificate 1"); v3CertGen.setNotBefore(new Date(currentTime - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(currentTime + (1000L * 60 * 60 * 24 * 365 * 10))); v3CertGen.setSubjectDN(new X509Principal(X509_NAME)); v3CertGen.setPublicKey(kp.getPublic()); v3CertGen.setSignatureAlgorithm(SIGNATURE_ALGORITHM); X509Certificate cert = v3CertGen.generateX509Certificate(kp.getPrivate()); logger.debug("initPrivateKeyAndSelfsignedCertificate 2"); try { MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM); md.update(cert.getEncoded()); sFingerPrint = AlGORITHM_SHA; logger.debug("initPrivateKeyAndSelfsignedCertificate 3"); sFingerPrint = sFingerPrint + dumpHex(md.digest()); if (logger.isActivated()) { logger.debug("initPrivateKeyAndSelfsignedCertificate exit, with sFingerPrint: " + sFingerPrint); } } catch (Exception e) { e.printStackTrace(); if (logger.isActivated()) { logger.debug("initPrivateKeyAndSelfsignedCertificate exception"); } } logger.debug("initPrivateKeyAndSelfsignedCertificate 4"); // Add the private key with cert in keystore ks.setKeyEntry(PRIVATE_KEY_ALIAS, kp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), new Certificate[] { cert }); // save the keystore logger.debug("initPrivateKeyAndSelfsignedCertificate 5"); ks.store(new FileOutputStream(getSelfSignedKeystorePath()), KEYSTORE_PASSWORD.toCharArray()); } else { if (logger.isActivated()) { logger.error("initPrivateKeyAndSelfsignedCertificate key store not exist"); } } if (logger.isActivated()) { logger.debug("initPrivateKeyAndSelfsignedCertificate exit"); } } /** * @} */ }
[ "peishengguo@yydrobot.com" ]
peishengguo@yydrobot.com
9352289791875d4b38ec6d4ff0b05bd6cfbe1c88
9c3b25c7694ac3e7087e205bd843cf09709a9fab
/src/main/java/main/CompanyRest.java
52f93072830ca9998515edd314b7c6a227cefe37
[]
no_license
GagoM/Coupon-System
9154c8c280ea6803048e6ecffcd88abc393a8d73
583e2f2b7a29ed47d6049321a8fc6e9a87d0163c
refs/heads/master
2021-05-12T18:48:59.596555
2018-02-04T09:16:07
2018-02-04T09:16:07
117,073,607
3
0
null
null
null
null
UTF-8
Java
false
false
7,792
java
package main; import java.io.FileNotFoundException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import core.Exceptions.CouponSystemException; import core.Exceptions.UniqueNameException; import core.facades.CompanyFacade; import core.javaBeans.Company; import core.javaBeans.Coupon; import core.javaBeans.CouponType; import webBeans.CompanyService; import webBeans.CouponService; @CrossOrigin(origins = "*") @RestController @RequestMapping("/company") public class CompanyRest { public CompanyFacade getCompanyFacade(HttpServletRequest request) { String userName = (String) request.getSession().getAttribute("username"); CompanyFacade companyFacade = (CompanyFacade) request.getSession().getAttribute(userName + "facade"); return companyFacade; } @RequestMapping(value = "getcompanyusername", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public CompanyService getCompanyName(HttpServletRequest request) throws CouponSystemException { CompanyFacade facade = getCompanyFacade(request); if (facade != null) { Company company = new Company(); String compName = (String) request.getSession().getAttribute("username"); company.setCompName(compName); CompanyService companyService = new CompanyService(company); System.out.println(companyService.toString()); return companyService; } return null; } @RequestMapping(value = "/createcoupon", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public void createCoupon(@RequestBody CouponService c, HttpServletRequest request) throws CouponSystemException, UniqueNameException { CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { Coupon coupon = c.convertToCoupon(); companyFacade.createCoupon(coupon); } } @RequestMapping(value = "/removecoupon", method = RequestMethod.DELETE, consumes = MediaType.APPLICATION_JSON_VALUE) public void removeCoupon(@RequestBody CouponService c, HttpServletRequest request) throws CouponSystemException { CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { Coupon coupon = c.convertToCoupon(); companyFacade.removeCoupon(coupon); } } @RequestMapping(value = "/updatecoupon", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public void updateCoupon(@RequestBody CouponService c, HttpServletRequest request) throws CouponSystemException { CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { Coupon coupon = c.convertToCoupon(); companyFacade.updateCoupon(coupon); } } @RequestMapping(value = "readcoupon/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public CouponService readCoupon(@PathVariable("id") long id, HttpServletRequest request) throws CouponSystemException { CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { Coupon coupon = companyFacade.readCoupon(id); CouponService couponService = new CouponService(coupon); return couponService; } return null; } @RequestMapping(value = "getallcoupon", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public Collection<CouponService> getAllCoupon(HttpServletRequest request) throws CouponSystemException { CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { CouponService couponService = new CouponService(); Collection<Coupon> list = new ArrayList<>(); list = companyFacade.getAllCoupon(); Collection<CouponService> list2 = new ArrayList<>(); list2 = couponService.convertToCouponsService(list); return list2; } return null; } @RequestMapping(value = "getcouponsbytype/{type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public Collection<CouponService> getCouponsByType(@PathVariable("type") CouponType c, HttpServletRequest request) throws CouponSystemException { CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { CouponService couponService = new CouponService(); Collection<Coupon> list = new ArrayList<>(); list = companyFacade.getCouponsByType(c); Collection<CouponService> list2 = new ArrayList<>(); list2 = couponService.convertToCouponsService(list); return list2; } return null; } @RequestMapping(value = "getcouponsbyprice/{price}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public Collection<CouponService> getCouponsByPrice(@PathVariable("price") double price, HttpServletRequest request) throws CouponSystemException { CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { CouponService couponService = new CouponService(); Collection<Coupon> list = new ArrayList<>(); list = companyFacade.getCouponsByPrice(price); Collection<CouponService> list2 = new ArrayList<>(); list2 = couponService.convertToCouponsService(list); return list2; } return null; } @RequestMapping(value = "getcouponsbydate/{date}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public Collection<CouponService> getCouponsByDate(@PathVariable("date") String date, HttpServletRequest request) throws CouponSystemException, ParseException { SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); Date newDate = newFormat.parse(date); CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { CouponService couponService = new CouponService(); Collection<Coupon> list = new ArrayList<>(); list = companyFacade.getCouponsByDate(newDate); Collection<CouponService> list2 = new ArrayList<>(); list2 = couponService.convertToCouponsService(list); return list2; } return null; } @RequestMapping(value = "getallexistingcoupons", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public Collection<CouponService> getAllExistingCoupons(HttpServletRequest request) throws CouponSystemException { CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { Collection<Coupon> coupons = new ArrayList<>(); coupons = companyFacade.getAllExistingCoupons(); Collection<CouponService> couponsToReturn = new ArrayList<>(); CouponService couponService = new CouponService(); couponsToReturn = couponService.convertToCouponsService(coupons); return couponsToReturn; } return null; } @RequestMapping(value = "companylogout", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public void logout(HttpServletRequest request) throws CouponSystemException, FileNotFoundException { CompanyFacade companyFacade = getCompanyFacade(request); if (companyFacade != null) { String username = (String) request.getSession().getAttribute("username"); LoggerRest logger = new LoggerRest(); String logMessage = "company: '" + username + "' has logged out from the system"; logger.logToFile(logMessage); request.getSession().removeAttribute(username); request.getSession().removeAttribute(username + "facade"); request.getSession().removeAttribute("authenticated"); } } }
[ "34302679+GagoM@users.noreply.github.com" ]
34302679+GagoM@users.noreply.github.com
cd76d64d613f692094e0790ce3e28893264334f9
f6b0ce9d53f03da80adb2cc027018b458faa9d8f
/core/src/main/java/org/apache/brooklyn/core/workflow/WorkflowExpressionResolution.java
dd1603880bc21868b14b0556ebc52e3f23629678
[ "Apache-2.0", "OFL-1.1", "LicenseRef-scancode-public-domain", "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
apache/brooklyn-server
3c4b3ba2f494447ac90e118e7bbfe3fcb4c4862e
1ae135db034ee5b749f853322a10ce2401cc3d76
refs/heads/master
2023-08-30T20:35:47.050041
2023-08-30T08:00:41
2023-08-30T08:00:41
47,246,081
49
84
Apache-2.0
2023-09-14T17:06:34
2015-12-02T08:00:06
Java
UTF-8
Java
false
false
38,879
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.brooklyn.core.workflow; import com.google.common.annotations.Beta; import com.google.common.reflect.TypeToken; import freemarker.template.TemplateHashModel; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import org.apache.brooklyn.api.entity.Entity; import org.apache.brooklyn.config.ConfigKey; import org.apache.brooklyn.core.config.ConfigKeys; import org.apache.brooklyn.core.entity.Entities; import org.apache.brooklyn.core.mgmt.BrooklynTaskTags; import org.apache.brooklyn.core.resolve.jackson.BeanWithTypeUtils; import org.apache.brooklyn.core.resolve.jackson.BrooklynJacksonSerializationUtils; import org.apache.brooklyn.core.typereg.RegisteredTypes; import org.apache.brooklyn.util.collections.Jsonya; import org.apache.brooklyn.util.collections.MutableList; import org.apache.brooklyn.util.collections.MutableMap; import org.apache.brooklyn.util.collections.ThreadLocalStack; import org.apache.brooklyn.util.core.flags.TypeCoercions; import org.apache.brooklyn.util.core.predicates.ResolutionFailureTreatedAsAbsent; import org.apache.brooklyn.util.core.task.DeferredSupplier; import org.apache.brooklyn.util.core.task.Tasks; import org.apache.brooklyn.util.core.text.TemplateProcessor; import org.apache.brooklyn.util.exceptions.Exceptions; import org.apache.brooklyn.util.guava.Maybe; import org.apache.brooklyn.util.javalang.Boxing; import org.apache.brooklyn.util.time.Time; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Instant; import java.util.*; import java.util.function.BiFunction; import java.util.function.Supplier; import java.util.stream.Collectors; public class WorkflowExpressionResolution { public static ConfigKey<BiFunction<String,WorkflowExpressionResolution,Object>> WORKFLOW_CUSTOM_INTERPOLATION_FUNCTION = ConfigKeys.newConfigKey(new TypeToken<BiFunction<String,WorkflowExpressionResolution,Object>>() {}, "workflow.custom_interpolation_function"); public enum WorkflowExpressionStage implements Comparable<WorkflowExpressionStage> { WORKFLOW_INPUT, WORKFLOW_STARTING_POST_INPUT, STEP_PRE_INPUT, STEP_INPUT, STEP_RUNNING, STEP_OUTPUT, STEP_FINISHING_POST_OUTPUT, WORKFLOW_OUTPUT; public boolean after(WorkflowExpressionStage other) { return compareTo(other) > 0; } } private static final Logger log = LoggerFactory.getLogger(WorkflowExpressionResolution.class); private final WorkflowExecutionContext context; private final boolean allowWaiting; private final WorkflowExpressionStage stage; private final TemplateProcessor.InterpolationErrorMode errorMode; private final WrappingMode wrappingMode; public static class WrappingMode { public final boolean wrapResolvedStrings; public final boolean deferThrowingError; public final boolean deferAndRetryErroneousExpressions; public final boolean deferBrooklynDsl; public final boolean deferInterpolation; protected WrappingMode(boolean wrapResolvedStrings, boolean deferThrowingError, boolean deferAndRetryErroneousExpressions, boolean deferBrooklynDsl, boolean deferInterpolation) { this.wrapResolvedStrings = wrapResolvedStrings; this.deferThrowingError = deferThrowingError; this.deferAndRetryErroneousExpressions = deferAndRetryErroneousExpressions; this.deferBrooklynDsl = deferBrooklynDsl; this.deferInterpolation = deferInterpolation; } /** do not re-evaluate anything, but if there is an error don't throw it until accessed; useful for conditions that should be evaluated immediately */ public final static WrappingMode WRAPPED_RESULT_DEFER_THROWING_ERROR_BUT_NO_RETRY = new WrappingMode(true, true, false, false, false); /** no wrapping; everything evaluated immediately, errors thrown immediately */ public final static WrappingMode NONE = new WrappingMode(false, false, false, false, false); /** this was the old default when wrapping was requested, but was an odd one - wraps error throwing and DSL resolution but not interpolation */ @Deprecated @Beta // might re-introduce but for now needs to cache workflow context so discouraged final static WrappingMode OLD_DEFAULT_DEFER_THROWING_ERROR_AND_DSL = new WrappingMode(true, true, false, true, false); /** allow subsequent re-evaluation for things that are not recognized, but evaluate everything else now; cf InterpolationErrorMode.IGNORE */ @Deprecated @Beta // might re-introduce but for now needs to cache workflow context so discouraged public final static WrappingMode DEFER_RETRY_ON_ERROR_ONLY = new WrappingMode(false, false, true, false, false); /** defer the evaluation of all vars (but evaluate now so if string is static it can be returned as a static) */ @Deprecated @Beta // might re-introduce but for now needs to cache workflow context so discouraged public final static WrappingMode ALL_NON_STATIC = new WrappingMode(true /* no effect here */, true /* no effect here */, true, true, true); public WrappingMode wrappingModeWhenResolving() { // this works for our current use cases, which is conditions; other uses might want it not to throw something deferred however return WRAPPED_RESULT_DEFER_THROWING_ERROR_BUT_NO_RETRY; } } public WorkflowExpressionResolution(WorkflowExecutionContext context, WorkflowExpressionStage stage, boolean allowWaiting, WrappingMode wrapExpressionValues) { this(context, stage, allowWaiting, wrapExpressionValues, TemplateProcessor.InterpolationErrorMode.FAIL); } public WorkflowExpressionResolution(WorkflowExecutionContext context, WorkflowExpressionStage stage, boolean allowWaiting, WrappingMode wrapExpressionValues, TemplateProcessor.InterpolationErrorMode errorMode) { this.context = context; this.stage = stage; this.allowWaiting = allowWaiting; this.wrappingMode = wrapExpressionValues == null ? WrappingMode.NONE : wrapExpressionValues; this.errorMode = errorMode; } TemplateModel ifNoMatches() { // fail here - any other behaviour is hard with freemarker (exceptions intercepted etc). // error handling is done by 'process' method below, and by ?? notation handling in let, // or if needed freemarker attempts/escapes to recover could be used (not currently used much) return null; } public class WorkflowFreemarkerModel implements TemplateHashModel, TemplateProcessor.UnwrappableTemplateModel { @Override public Maybe<Object> unwrap() { return Maybe.of(context); } @Override public TemplateModel get(String key) throws TemplateModelException { List<Throwable> errors = MutableList.of(); if ("workflow".equals(key)) { return new WorkflowExplicitModel(); } if ("entity".equals(key)) { Entity entity = context.getEntity(); if (entity!=null) { return TemplateProcessor.EntityAndMapTemplateModel.forEntity(entity, null); } } if ("output".equals(key)) { if (context.getOutput()!=null) return TemplateProcessor.wrapAsTemplateModel(context.getOutput()); if (context.currentStepInstance!=null && context.currentStepInstance.getOutput() !=null) return TemplateProcessor.wrapAsTemplateModel(context.currentStepInstance.getOutput()); Object previousStepOutput = context.getPreviousStepOutput(); if (previousStepOutput!=null) return TemplateProcessor.wrapAsTemplateModel(previousStepOutput); return ifNoMatches(); } Object candidate = null; if (stage.after(WorkflowExpressionStage.STEP_PRE_INPUT)) { //somevar -> workflow.current_step.output.somevar WorkflowStepInstanceExecutionContext currentStep = context.currentStepInstance; if (currentStep != null && stage.after(WorkflowExpressionStage.STEP_OUTPUT)) { if (currentStep.getOutput() instanceof Map) { candidate = ((Map) currentStep.getOutput()).get(key); if (candidate != null) return TemplateProcessor.wrapAsTemplateModel(candidate); } } //somevar -> workflow.current_step.input.somevar try { if (currentStep!=null) { candidate = currentStep.getInput(key, Object.class); } } catch (Throwable t) { Exceptions.propagateIfFatal(t); if (stage==WorkflowExpressionStage.STEP_INPUT && WorkflowVariableResolutionStackEntry.isStackForSettingVariable(RESOLVE_STACK.getAll(true), key) && Exceptions.getFirstThrowableOfType(t, WorkflowVariableRecursiveReference.class)!=null) { // input evaluation can look at local input, and will gracefully handle some recursive references. // this is needed so we can handle things like env:=${env} in input, and also {message:="Hi ${name}", name:="Bob"}. // but there are // if we have a chain input1:=input2, and input input2:=input1 with both defined on step and on workflow // // (a) eval of either will give recursive reference error and allow retry immediately; // then it's a bit weird, inconsistent, step input1 will resolve to local input2 which resolves as global input1; // but step input2 will resolve to local input1 which this time will resolve as global input2. // and whichever is invoked first will cause both to be stored as resolved, so if input2 resolved first then // step input1 subsequently returns global input2. // // (b) recursive reference error only recoverable at the outermost stage, // so step input1 = global input2, step input2 = global input1, // prevents inconsistency but blocks useful things, eg log ${message} wrapped with message:="Hi ${name}", // then invoked with name: "person who says ${message}" to refer to a previous step's message, // or even name:="Mr ${name}" to refer to an outer variable. // in this case if name is resolved first then message resolves as Hi Mr X, but if message resolved first // it only recovers when resolving message which would become "Hi X", and if message:="${greeting} ${name}" // then it fails to find a local ${greeting}. (with strategy (a) these both do what is expected.) // // (to handle this we include stage in the stack, needed in both cases above) // // ideally we would know which vars are from a wrapper, but that info is lost when we build up the step // // (c) we could just fail fast, disallow the nice things we wanted, require explicit // // (d) we could fail in edge cases, so the obvious cases above work as expected, but anything more sophisticated, eg A calling B calling A, will fail // // settled on (d) effectively; we allow local references, and fail on recursive references, with exceptions. // the main exception, handled here, is if we are setting an input candidate = null; errors.add(t); } else { throw Exceptions.propagate(t); } } if (candidate != null) return TemplateProcessor.wrapAsTemplateModel(candidate); } //workflow.previous_step.output.somevar if (stage.after(WorkflowExpressionStage.WORKFLOW_INPUT)) { Object prevStepOutput = context.getPreviousStepOutput(); if (prevStepOutput instanceof Map) { candidate = ((Map) prevStepOutput).get(key); if (candidate != null) return TemplateProcessor.wrapAsTemplateModel(candidate); } } //workflow.scratch.somevar if (stage.after(WorkflowExpressionStage.WORKFLOW_INPUT)) { candidate = context.getWorkflowScratchVariables().get(key); if (candidate != null) return TemplateProcessor.wrapAsTemplateModel(candidate); } //workflow.input.somevar if (context.input.containsKey(key)) { candidate = context.getInput(key); // the subtlety around step input above doesn't apply here as workflow inputs are not resolved with freemarker if (candidate != null) return TemplateProcessor.wrapAsTemplateModel(candidate); } if (!errors.isEmpty()) Exceptions.propagate("Errors resolving "+key, errors); return ifNoMatches(); } @Override public boolean isEmpty() throws TemplateModelException { return false; } } class WorkflowExplicitModel implements TemplateHashModel, TemplateProcessor.UnwrappableTemplateModel { @Override public Maybe<Object> unwrap() { return Maybe.of(context); } @Override public TemplateModel get(String key) throws TemplateModelException { //id (a token representing an item uniquely within its root instance) if ("name".equals(key)) return TemplateProcessor.wrapAsTemplateModel(context.getName()); if ("id".equals(key)) return TemplateProcessor.wrapAsTemplateModel(context.getWorkflowId()); if ("task_id".equals(key)) return TemplateProcessor.wrapAsTemplateModel(context.getTaskId()); // TODO variable reference for link //link (a link in the UI to this instance of workflow or step) //error (if there is an error in scope) WorkflowStepInstanceExecutionContext currentStepInstance = context.currentStepInstance; WorkflowStepInstanceExecutionContext errorHandlerContext = context.errorHandlerContext; if ("error".equals(key)) return TemplateProcessor.wrapAsTemplateModel(errorHandlerContext!=null ? errorHandlerContext.getError() : null); if ("input".equals(key)) return TemplateProcessor.wrapAsTemplateModel(context.input); if ("output".equals(key)) return TemplateProcessor.wrapAsTemplateModel(context.getOutput()); //current_step.yyy and previous_step.yyy (where yyy is any of the above) //step.xxx.yyy ? - where yyy is any of the above and xxx any step id if ("error_handler".equals(key)) return new WorkflowStepModel(errorHandlerContext); if ("current_step".equals(key)) return new WorkflowStepModel(currentStepInstance); if ("previous_step".equals(key)) return newWorkflowStepModelForStepIndex(context.previousStepIndex); if ("step".equals(key)) return new WorkflowStepModel(); if ("util".equals(key)) return new WorkflowUtilModel(); if ("var".equals(key)) return TemplateProcessor.wrapAsTemplateModel(context.getWorkflowScratchVariables()); return ifNoMatches(); } @Override public boolean isEmpty() throws TemplateModelException { return false; } } TemplateModel newWorkflowStepModelForStepIndex(Integer step) { WorkflowExecutionContext.OldStepRecord stepI = context.oldStepInfo.get(step); if (stepI==null || stepI.context==null) return ifNoMatches(); return new WorkflowStepModel(stepI.context); } TemplateModel newWorkflowStepModelForStepId(String id) { for (WorkflowExecutionContext.OldStepRecord s: context.oldStepInfo.values()) { if (s.context!=null && id.equals(s.context.stepDefinitionDeclaredId)) return new WorkflowStepModel(s.context); } return ifNoMatches(); } class WorkflowStepModel implements TemplateHashModel { private WorkflowStepInstanceExecutionContext step; WorkflowStepModel() {} WorkflowStepModel(WorkflowStepInstanceExecutionContext step) { this.step = step; } @Override public TemplateModel get(String key) throws TemplateModelException { if (step==null) { return newWorkflowStepModelForStepId(key); } //id (a token representing an item uniquely within its root instance) if ("name".equals(key)) { return TemplateProcessor.wrapAsTemplateModel(step.name != null ? step.name : step.getWorkflowStepReference()); } if ("task_id".equals(key)) return TemplateProcessor.wrapAsTemplateModel(step.taskId); if ("step_id".equals(key)) return TemplateProcessor.wrapAsTemplateModel(step.stepDefinitionDeclaredId); if ("step_index".equals(key)) return TemplateProcessor.wrapAsTemplateModel(step.stepIndex); // TODO link and error, as above //link (a link in the UI to this instance of workflow or step) //error (if there is an error in scope) if ("input".equals(key)) return TemplateProcessor.wrapAsTemplateModel(step.input); if ("output".equals(key)) { Pair<Object, Set<Integer>> outputOfStep = context.getStepOutputAndBacktrackedSteps(step.stepIndex); Object output = (outputOfStep != null && outputOfStep.getLeft() != null) ? outputOfStep.getLeft() : MutableMap.of(); return TemplateProcessor.wrapAsTemplateModel(output); } return ifNoMatches(); } @Override public boolean isEmpty() throws TemplateModelException { return false; } } class WorkflowUtilModel implements TemplateHashModel { WorkflowUtilModel() {} @Override public TemplateModel get(String key) throws TemplateModelException { //id (a token representing an item uniquely within its root instance) if ("now".equals(key)) return TemplateProcessor.wrapAsTemplateModel(System.currentTimeMillis()); if ("now_utc".equals(key)) return TemplateProcessor.wrapAsTemplateModel(System.currentTimeMillis()); if ("now_instant".equals(key)) return TemplateProcessor.wrapAsTemplateModel(Instant.now()); if ("now_iso".equals(key)) return TemplateProcessor.wrapAsTemplateModel(Time.makeIso8601DateStringZ(Instant.now())); if ("now_stamp".equals(key)) return TemplateProcessor.wrapAsTemplateModel(Time.makeDateStampString()); if ("now_nice".equals(key)) return TemplateProcessor.wrapAsTemplateModel(Time.makeDateString(Instant.now())); if ("random".equals(key)) return TemplateProcessor.wrapAsTemplateModel(Math.random()); return ifNoMatches(); } @Override public boolean isEmpty() throws TemplateModelException { return false; } } AllowBrooklynDslMode defaultAllowBrooklynDsl = AllowBrooklynDslMode.ALL; public void setDefaultAllowBrooklynDsl(AllowBrooklynDslMode defaultAllowBrooklynDsl) { this.defaultAllowBrooklynDsl = defaultAllowBrooklynDsl; } public AllowBrooklynDslMode getDefaultAllowBrooklynDsl() { return defaultAllowBrooklynDsl; } public <T> T resolveWithTemplates(Object expression, TypeToken<T> type) { expression = processTemplateExpression(expression, getDefaultAllowBrooklynDsl()); return resolveCoercingOnly(expression, type); } /** does not use templates */ public <T> T resolveCoercingOnly(Object expression, TypeToken<T> type) { if (expression==null) return null; boolean triedCoercion = false; List<Exception> exceptions = MutableList.of(); if (expression instanceof String) { try { // prefer simple coercion if it's a string coming in return TypeCoercions.coerce(expression, type); } catch (Exception e) { Exceptions.propagateIfFatal(e); exceptions.add(e); triedCoercion = true; } } if (Jsonya.isJsonPrimitiveDeep(expression) && !(expression instanceof Set)) { try { // next try yaml coercion for anything complex, as values are normally set from yaml and will be raw at this stage (but not if they are from a DSL) return BeanWithTypeUtils.convert(context.getManagementContext(), expression, type, true, RegisteredTypes.getClassLoadingContext(context.getEntity()), true /* needed for wrapped resolved holders */); } catch (Exception e) { Exceptions.propagateIfFatal(e); exceptions.add(e); } } if (!triedCoercion) { try { // fallback to simple coercion return TypeCoercions.coerce(expression, type); } catch (Exception e) { Exceptions.propagateIfFatal(e); exceptions.add(e); triedCoercion = true; } } throw Exceptions.propagate(exceptions.iterator().next()); } static class WorkflowVariableResolutionStackEntry { WorkflowExecutionContext context; WorkflowExpressionStage stage; Object object; String settingVariable; public static WorkflowVariableResolutionStackEntry of(WorkflowExecutionContext context, WorkflowExpressionStage stage, Object expression) { WorkflowVariableResolutionStackEntry result = new WorkflowVariableResolutionStackEntry(); result.context = context; result.stage = stage; result.object = expression; return result; } public static WorkflowVariableResolutionStackEntry setting(WorkflowExecutionContext context, WorkflowExpressionStage stage, String settingVariable) { WorkflowVariableResolutionStackEntry result = new WorkflowVariableResolutionStackEntry(); result.context = context; result.stage = stage; result.settingVariable = settingVariable; return result; } public static boolean isStackForSettingVariable(Collection<WorkflowVariableResolutionStackEntry> stack, String key) { if (stack==null) return true; MutableList<WorkflowVariableResolutionStackEntry> s2 = MutableList.copyOf(stack); Collections.reverse(s2); Optional<WorkflowVariableResolutionStackEntry> s = s2.stream().filter(si -> si.settingVariable != null).findFirst(); if (!s.isPresent()) return false; return s.get().settingVariable.equals(key); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WorkflowVariableResolutionStackEntry that = (WorkflowVariableResolutionStackEntry) o; if (context != null && that.context != null ? !Objects.equals(context.getWorkflowId(), that.context.getWorkflowId()) : !Objects.equals(context, that.context)) return false; if (stage != that.stage) return false; if (object != null ? !object.equals(that.object) : that.object != null) return false; if (settingVariable != null ? !settingVariable.equals(that.settingVariable) : that.settingVariable != null) return false; return true; } @Override public int hashCode() { int result = context != null && context.getWorkflowId()!=null ? context.getWorkflowId().hashCode() : 0; result = 31 * result + (stage != null ? stage.hashCode() : 0); result = 31 * result + (object != null ? object.hashCode() : 0); result = 31 * result + (settingVariable != null ? settingVariable.hashCode() : 0); return result; } } /** method which can be used to indicate that a reference to the variable, if it is recursive, is recoverable, because we are in the process of setting that variable. * see discussion on usages of WorkflowVariableResolutionStackEntry.isStackForSettingVariable */ public static <T> T allowingRecursionWhenSetting(WorkflowExecutionContext context, WorkflowExpressionStage stage, String variable, Supplier<T> callable) { WorkflowVariableResolutionStackEntry entry = null; try { entry = WorkflowVariableResolutionStackEntry.setting(context, stage, variable); if (!RESOLVE_STACK.push(entry)) { entry = null; throw new WorkflowVariableRecursiveReference("Recursive reference setting "+variable+": "+RESOLVE_STACK.getAll(false).stream().map(p -> p.object!=null ? p.object.toString() : p.settingVariable).collect(Collectors.joining("->"))); } return callable.get(); } finally { if (entry!=null) { RESOLVE_STACK.pop(entry); } } } static ThreadLocalStack<WorkflowVariableResolutionStackEntry> RESOLVE_STACK = new ThreadLocalStack<>(false); WorkflowExpressionStage previousStage() { return RESOLVE_STACK.peekPenultimate().map(s -> s.stage).orNull(); } public static class WorkflowVariableRecursiveReference extends IllegalArgumentException { public WorkflowVariableRecursiveReference(String msg) { super(msg); } } public static class AllowBrooklynDslMode { public static AllowBrooklynDslMode ALL = new AllowBrooklynDslMode(true, null); static { ALL.next = Maybe.of(ALL); } public static AllowBrooklynDslMode NONE = new AllowBrooklynDslMode(false, null); static { NONE.next = Maybe.of(NONE); } public static AllowBrooklynDslMode CHILDREN_BUT_NOT_HERE = new AllowBrooklynDslMode(false, Maybe.of(ALL)); //public static AllowBrooklynDslMode HERE_BUT_NOT_CHILDREN = new AllowBrooklynDslMode(true, Maybe.of(NONE)); private Supplier<AllowBrooklynDslMode> next; private boolean allowedHere; public AllowBrooklynDslMode(boolean allowedHere, Supplier<AllowBrooklynDslMode> next) { this.allowedHere = allowedHere; this.next = next; } public boolean isAllowedHere() { return allowedHere; } public AllowBrooklynDslMode next() { return next.get(); } } public Object processTemplateExpression(Object expression, AllowBrooklynDslMode allowBrooklynDsl) { WorkflowVariableResolutionStackEntry entry = null; try { entry = WorkflowVariableResolutionStackEntry.of(context, stage, expression); if (!RESOLVE_STACK.push(entry)) { entry = null; throw new WorkflowVariableRecursiveReference("Recursive reference: " + RESOLVE_STACK.getAll(false).stream().map(p -> "" + p.object).collect(Collectors.joining("->"))); } if (RESOLVE_STACK.size() > 100) { throw new WorkflowVariableRecursiveReference("Reference exceeded max depth 100: " + RESOLVE_STACK.getAll(false).stream().map(p -> "" + p.object).collect(Collectors.joining("->"))); } if (expression instanceof String) return processTemplateExpressionString((String) expression, allowBrooklynDsl); if (expression instanceof Map) return processTemplateExpressionMap((Map) expression, allowBrooklynDsl); if (expression instanceof Collection) return processTemplateExpressionCollection((Collection) expression, allowBrooklynDsl); if (expression == null || Boxing.isPrimitiveOrBoxedObject(expression)) return expression; // otherwise resolve DSL return allowBrooklynDsl.isAllowedHere() ? resolveDsl(expression) : expression; } finally { if (entry != null) RESOLVE_STACK.pop(entry); } } private Object resolveDsl(Object expression) { boolean DEFINITELY_DSL = false; if (expression instanceof String || expression instanceof Map || expression instanceof Collection) { if (expression instanceof String) { if (!((String)expression).startsWith("$brooklyn:")) { // not DSL return expression; } else { DEFINITELY_DSL = true; } } if (BrooklynJacksonSerializationUtils.JsonDeserializerForCommonBrooklynThings.BROOKLYN_PARSE_DSL_FUNCTION==null) { if (DEFINITELY_DSL) { log.warn("BROOKLYN_PARSE_DSL_FUNCTION not set when processing DSL expression "+expression+"; will not be resolved"); } } else { expression = BrooklynJacksonSerializationUtils.JsonDeserializerForCommonBrooklynThings.BROOKLYN_PARSE_DSL_FUNCTION.apply(context.getManagementContext(), expression); } } return processDslComponents(expression); } private Object processDslComponents(Object expression) { return Tasks.resolving(expression).as(Object.class).deep().context(context.getEntity()).get(); } public WorkflowFreemarkerModel newWorkflowFreemarkerModel() { return new WorkflowFreemarkerModel(); } public WorkflowExecutionContext getWorkflowExecutionContext() { return context; } public TemplateProcessor.InterpolationErrorMode getErrorMode() { return errorMode; } public Object processTemplateExpressionString(String expression, AllowBrooklynDslMode allowBrooklynDsl) { if (expression==null) return null; if (expression.startsWith("$brooklyn:") && allowBrooklynDsl.isAllowedHere()) { if (wrappingMode.deferBrooklynDsl) { return WrappedUnresolvedExpression.ofExpression(expression, this, allowBrooklynDsl); } Object expressionTemplateResolved = processTemplateExpressionString(expression, AllowBrooklynDslMode.NONE); // resolve interpolation before brooklyn DSL, so brooklyn DSL can be passed interpolated vars like workflow scratch; // this means $brooklyn bits that return interpolated strings do not have their interpolation evaluated, which is probably sensible; // and $brooklyn cannot be used inside an interpolated string, which is okay. Object expressionTemplateAndDslResolved = resolveDsl(expressionTemplateResolved); return expressionTemplateAndDslResolved; } Object result; boolean ourWait = interruptSetIfNeededToPreventWaiting(); try { BiFunction<String, WorkflowExpressionResolution, Object> fn = context.getManagementContext().getScratchpad().get(WORKFLOW_CUSTOM_INTERPOLATION_FUNCTION); if (fn!=null) result = fn.apply(expression, this); else result = TemplateProcessor.processTemplateContentsForWorkflow("workflow", expression, newWorkflowFreemarkerModel(), true, false, errorMode); } catch (Exception e) { Exception e2 = e; if (wrappingMode.deferAndRetryErroneousExpressions) { return WrappedUnresolvedExpression.ofExpression(expression, this, allowBrooklynDsl); } if (!allowWaiting && Exceptions.isCausedByInterruptInAnyThread(e)) { e2 = new IllegalArgumentException("Expression value '"+expression+"' unavailable and not permitted to wait: "+ Exceptions.collapseText(e), e); } if (wrappingMode.deferThrowingError) { // in wrapped value mode, errors don't throw until accessed, and when used in conditions they can be tested as absent return WrappedResolvedExpression.ofError(expression, new ResolutionFailureTreatedAsAbsent.ResolutionFailureTreatedAsAbsentDefaultException(e2)); } else { throw Exceptions.propagate(e2); } } finally { if (ourWait) interruptClear(); } if (!expression.equals(result)) { // not a static string if (wrappingMode.deferInterpolation) { return WrappedUnresolvedExpression.ofExpression(expression, this, allowBrooklynDsl); } if (wrappingMode.deferBrooklynDsl) { return new WrappedResolvedExpression<Object>(expression, result); } // we try, but don't guarantee, that DSL expressions aren't re-resolved, ie $brooklyn:literal("$brooklyn:literal(\"x\")") won't return x; // this block will return a supplier result = processDslComponents(result); if (wrappingMode.wrapResolvedStrings) { return new WrappedResolvedExpression<Object>(expression, result); } } return result; } private static ThreadLocal<Boolean> interruptSetIfNeededToPreventWaiting = new ThreadLocal<>(); public static boolean isInterruptSetToPreventWaiting() { Entity entity = BrooklynTaskTags.getContextEntity(Tasks.current()); if (entity!=null && Entities.isUnmanagingOrNoLongerManaged(entity)) return false; return Boolean.TRUE.equals(interruptSetIfNeededToPreventWaiting.get()); } private boolean interruptSetIfNeededToPreventWaiting() { if (!allowWaiting && !Thread.currentThread().isInterrupted() && !isInterruptSetToPreventWaiting()) { interruptSetIfNeededToPreventWaiting.set(true); Thread.currentThread().interrupt(); return true; } return false; } private void interruptClear() { // clear interrupt status Thread.interrupted(); interruptSetIfNeededToPreventWaiting.remove(); } public Object processTemplateExpressionMap(Map<?,?> object, AllowBrooklynDslMode allowBrooklynDsl) { if (allowBrooklynDsl.isAllowedHere() && object.size()==1) { Object key = object.keySet().iterator().next(); if (key instanceof String && ((String)key).startsWith("$brooklyn:")) { Object expressionTemplateValueResolved = processTemplateExpression(object.values().iterator().next(), allowBrooklynDsl.next()); Object expressionTemplateAndDslResolved = resolveDsl(MutableMap.of(key, expressionTemplateValueResolved)); return expressionTemplateAndDslResolved; } } Map<Object,Object> result = MutableMap.of(); object.forEach((k,v) -> result.put(processTemplateExpression(k, allowBrooklynDsl.next()), processTemplateExpression(v, allowBrooklynDsl.next()))); return result; } protected Collection<?> processTemplateExpressionCollection(Collection<?> object, AllowBrooklynDslMode allowBrooklynDsl) { return object.stream().map(x -> processTemplateExpression(x, allowBrooklynDsl.next())).collect(Collectors.toList()); } public static class WrappedResolvedExpression<T> implements DeferredSupplier<T> { String expression; T value; Throwable error; public WrappedResolvedExpression() {} public WrappedResolvedExpression(String expression, T value) { this.expression = expression; this.value = value; } public static WrappedResolvedExpression ofError(String expression, Throwable error) { WrappedResolvedExpression result = new WrappedResolvedExpression(expression, null); result.error = error; return result; } @Override public T get() { if (error!=null) { throw Exceptions.propagate(error); } return value; } public String getExpression() { return expression; } public Throwable getError() { return error; } } public static class WrappedUnresolvedExpression implements DeferredSupplier<Object> { @Deprecated @Beta // might re-introduce but for now needs to cache workflow context -- via resolver -- so discouraged public static WrappedUnresolvedExpression ofExpression(String expression, WorkflowExpressionResolution resolver, AllowBrooklynDslMode dslMode) { return new WrappedUnresolvedExpression(expression, resolver, dslMode); } protected WrappedUnresolvedExpression(String expression, WorkflowExpressionResolution resolver, AllowBrooklynDslMode dslMode) { this.expression = expression; this.resolver = resolver; this.dslMode = dslMode; } String expression; WorkflowExpressionResolution resolver; AllowBrooklynDslMode dslMode; public Object get() { WorkflowExpressionResolution resolverNow = new WorkflowExpressionResolution(resolver.context, resolver.stage, resolver.allowWaiting, resolver.wrappingMode.wrappingModeWhenResolving(), resolver.errorMode); return resolverNow.processTemplateExpression(expression, dslMode); } } }
[ "alex@cloudsoft.io" ]
alex@cloudsoft.io
9cec3fb84fa22902b186bd67691f7ea5e66f2806
2bd25c9534f8ac097fa50afb7a3770714c321af9
/teseWorkspace/org.itlingo.rsl/xtend-gen/org/rslingo/rsl/generator/Angular5andASP/NET_Core/DAL/AppDbContext.java
e68d15ae41a787180359746d71aff9a020ee5767
[]
no_license
gon10/EclipseRepoTese
563ad3b84fe5223eb4ce108b1a63acd85e2b924e
488e4f5e988bd662cbdfd976d97c01dd157db954
refs/heads/master
2020-03-26T12:11:12.357566
2018-09-14T22:28:46
2018-09-14T22:28:46
144,704,328
0
0
null
null
null
null
UTF-8
Java
false
false
13,358
java
package org.rslingo.rsl.generator.Angular5andASP.NET_Core.DAL; import java.util.ArrayList; import org.eclipse.xtend2.lib.StringConcatenation; import org.rslingo.rsl.rsl.DataEntity; @SuppressWarnings("all") public class AppDbContext { private ArrayList<DataEntity> entities = new ArrayList<DataEntity>(); private ArrayList<String> oneToMany1 = new ArrayList<String>(); private ArrayList<String> oneToMany2 = new ArrayList<String>(); private ArrayList<String> oneToOne1 = new ArrayList<String>(); private ArrayList<String> oneToOne2 = new ArrayList<String>(); private ArrayList<String> ManyToMany1 = new ArrayList<String>(); private ArrayList<String> ManyToMany2 = new ArrayList<String>(); public AppDbContext(final ArrayList<DataEntity> entities, final ArrayList<String> onetoone1, final ArrayList<String> onetoone2, final ArrayList<String> onetomany1, final ArrayList<String> onetomany2) { this.entities = entities; this.oneToMany1 = onetomany1; this.oneToMany2 = onetomany2; this.oneToOne1 = onetoone1; this.oneToOne2 = onetoone2; this.ManyToMany1 = this.ManyToMany1; this.ManyToMany2 = this.ManyToMany2; } public CharSequence genAppDbContext() { CharSequence _xblockexpression = null; { int ind = 0; StringConcatenation _builder = new StringConcatenation(); _builder.append("// ===================================================="); _builder.newLine(); _builder.append("// More Templates: https://www.ebenmonney.com/templates"); _builder.newLine(); _builder.append("// Email: support@ebenmonney.com"); _builder.newLine(); _builder.append("// ===================================================="); _builder.newLine(); _builder.newLine(); _builder.append("using DAL.Models;"); _builder.newLine(); _builder.append("using Microsoft.AspNetCore.Identity.EntityFrameworkCore;"); _builder.newLine(); _builder.append("using Microsoft.EntityFrameworkCore;"); _builder.newLine(); _builder.append("using System;"); _builder.newLine(); _builder.append("using System.Collections.Generic;"); _builder.newLine(); _builder.append("using System.Linq;"); _builder.newLine(); _builder.append("using System.Text;"); _builder.newLine(); _builder.append("using System.Threading.Tasks;"); _builder.newLine(); _builder.append("using System.Threading;"); _builder.newLine(); _builder.append("using DAL.Models.Interfaces;"); _builder.newLine(); _builder.newLine(); _builder.append("namespace DAL"); _builder.newLine(); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("public string CurrentUserId { get; set; }"); _builder.newLine(); _builder.append(" "); _builder.newLine(); _builder.append(" "); ArrayList<String> entitiesTreated = new ArrayList<String>(); _builder.newLineIfNotEmpty(); { for(final DataEntity entity : this.entities) { { String _name = entity.getName(); boolean _contains = entitiesTreated.contains(_name); boolean _not = (!_contains); if (_not) { _builder.append(" "); _builder.append("public DbSet<"); String _name_1 = entity.getName(); _builder.append(_name_1, " "); _builder.append("> "); String _name_2 = entity.getName(); _builder.append(_name_2, " "); _builder.append("s { get; set; }"); _builder.newLineIfNotEmpty(); _builder.append(" "); String _xblockexpression_1 = null; { String _name_3 = entity.getName(); entitiesTreated.add(_name_3); _xblockexpression_1 = ""; } _builder.append(_xblockexpression_1, " "); _builder.newLineIfNotEmpty(); } } } } _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("public ApplicationDbContext(DbContextOptions options) : base(options)"); _builder.newLine(); _builder.append(" "); _builder.append("{ }"); _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("protected override void OnModelCreating(ModelBuilder builder)"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("base.OnModelCreating(builder);"); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("builder.Entity<ApplicationUser>().HasMany(u => u.Claims).WithOne().HasForeignKey(c => c.UserId).IsRequired().OnDelete(DeleteBehavior.Cascade);"); _builder.newLine(); _builder.append(" "); _builder.append("builder.Entity<ApplicationUser>().HasMany(u => u.Roles).WithOne().HasForeignKey(r => r.UserId).IsRequired().OnDelete(DeleteBehavior.Cascade);"); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("builder.Entity<ApplicationRole>().HasMany(r => r.Claims).WithOne().HasForeignKey(c => c.RoleId).IsRequired().OnDelete(DeleteBehavior.Cascade);"); _builder.newLine(); _builder.append(" "); _builder.append("builder.Entity<ApplicationRole>().HasMany(r => r.Users).WithOne().HasForeignKey(r => r.RoleId).IsRequired().OnDelete(DeleteBehavior.Cascade);"); _builder.newLine(); _builder.append(" "); _builder.newLine(); _builder.append("\t\t\t"); ArrayList<String> entitiesTreatedForBuilder = new ArrayList<String>(); _builder.newLineIfNotEmpty(); { for(final DataEntity entity_1 : this.entities) { { String _name_3 = entity_1.getName(); boolean _contains_1 = entitiesTreatedForBuilder.contains(_name_3); boolean _not_1 = (!_contains_1); if (_not_1) { _builder.append(" \t"); _builder.append("builder.Entity<"); String _name_4 = entity_1.getName(); _builder.append(_name_4, " \t"); _builder.append(">().ToTable($\"App{nameof(this."); String _name_5 = entity_1.getName(); _builder.append(_name_5, " \t"); _builder.append("s)}\");"); _builder.newLineIfNotEmpty(); _builder.append(" \t"); String _xblockexpression_2 = null; { String _name_6 = entity_1.getName(); entitiesTreatedForBuilder.add(_name_6); _xblockexpression_2 = ""; } _builder.append(_xblockexpression_2, " \t"); _builder.newLineIfNotEmpty(); } } } } _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("public override int SaveChanges()"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("UpdateAuditEntities();"); _builder.newLine(); _builder.append(" "); _builder.append("return base.SaveChanges();"); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("public override int SaveChanges(bool acceptAllChangesOnSuccess)"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("UpdateAuditEntities();"); _builder.newLine(); _builder.append(" "); _builder.append("return base.SaveChanges(acceptAllChangesOnSuccess);"); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("UpdateAuditEntities();"); _builder.newLine(); _builder.append(" "); _builder.append("return base.SaveChangesAsync(cancellationToken);"); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("UpdateAuditEntities();"); _builder.newLine(); _builder.append(" "); _builder.append("return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);"); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("private void UpdateAuditEntities()"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("var modifiedEntries = ChangeTracker.Entries()"); _builder.newLine(); _builder.append(" "); _builder.append(".Where(x => x.Entity is IAuditableEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));"); _builder.newLine(); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("foreach (var entry in modifiedEntries)"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("var entity = (IAuditableEntity)entry.Entity;"); _builder.newLine(); _builder.append(" "); _builder.append("DateTime now = DateTime.UtcNow;"); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("if (entry.State == EntityState.Added)"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("entity.CreatedDate = now;"); _builder.newLine(); _builder.append(" "); _builder.append("entity.CreatedBy = CurrentUserId;"); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.append(" "); _builder.append("else"); _builder.newLine(); _builder.append(" "); _builder.append("{"); _builder.newLine(); _builder.append(" "); _builder.append("base.Entry(entity).Property(x => x.CreatedBy).IsModified = false;"); _builder.newLine(); _builder.append(" "); _builder.append("base.Entry(entity).Property(x => x.CreatedDate).IsModified = false;"); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.newLine(); _builder.append(" "); _builder.append("entity.UpdatedDate = now;"); _builder.newLine(); _builder.append(" "); _builder.append("entity.UpdatedBy = CurrentUserId;"); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.append("}"); _builder.newLine(); _xblockexpression = _builder; } return _xblockexpression; } }
[ "goncalopereira1515@gmail.com" ]
goncalopereira1515@gmail.com
cf5182e0f06c2bdcd96bcdd6d666b50427c2aee2
3cf5c9735533f5270a2f8d55290a4e8ed6cb1e9c
/ExamenJavaDiciembre2012RedSocial/src/RedSocialException.java
0cec431cd0eb0ad69dd6f4dc7e1627d5d2135b21
[]
no_license
frosamga/Programacion-orientada-a-objetos
9afa23c7281db6250d56f5493fbfbb023c06c819
458b73412ba54c10e6272a0c9dedb123723a2e9f
refs/heads/master
2020-06-08T15:56:44.457390
2015-06-21T15:33:14
2015-06-21T15:33:14
37,814,253
0
0
null
null
null
null
UTF-8
Java
false
false
176
java
public class RedSocialException extends RuntimeException { public RedSocialException(String msn) { super(msn); } public RedSocialException() { super(); } }
[ "frosamga@hotmail.com" ]
frosamga@hotmail.com
99d66d7f9e390e7d8a49f2639e34911f932eedb5
22390d3569ea3b06d43d7e765ce6f11ebf5827ba
/string/date.java
ed10c39fdbc0590cb2d19756c773259c3ef429fb
[]
no_license
cabrelkemfang/Achile_Java
63a4b22f2ca185d89f043ef6d94af29b101b5268
7e79ee41c435adf3250bc5f89ce1f6d620e6ab7f
refs/heads/master
2020-03-21T07:07:05.997060
2018-10-02T08:30:02
2018-10-02T08:30:02
138,261,386
0
1
null
2018-11-16T16:51:33
2018-06-22T06:04:25
HTML
UTF-8
Java
false
false
453
java
//EXO14.19 import java.util.Scanner; public class date{ public static void main(String[] agrs){ Scanner imput=new Scanner(System.in); String[] month={"jan","feb","mar","april","may","jun","jul","aug","sept","oct","nov","dec"}; int m,d,year; System.out.println("plaese enter the date month day year"); m=imput.nextInt(); d=imput.nextInt(); year=imput.nextInt(); System.out.println("you date is : "+month[m-1]+"/"+d+"/"+year); } }
[ "39851246+achilep@users.noreply.github.com" ]
39851246+achilep@users.noreply.github.com
b3b3f2d6cb953d0b7440f95fd3fb832f733f8381
83e2a3d1f7e0934c6d0f631c1674ed0c5fea5143
/src/main/java/com/intplog/mcs/service/impl/McsServiceImpl/McsPlcVariableServiceImpl.java
a570738c24c4bbc84382c4268ba19ffd6d07c067
[]
no_license
hg960954342/hongfaBCRtest_1
e46119dc1994f6e6d9c84cb23e2ad26e2b373475
89af85bf3c6a6c8f4bd411c1056cd60fbcbeacb5
refs/heads/master
2023-07-12T21:01:24.274102
2021-02-05T09:37:07
2021-02-05T09:37:07
336,147,108
0
0
null
null
null
null
UTF-8
Java
false
false
4,812
java
package com.intplog.mcs.service.impl.McsServiceImpl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.intplog.mcs.bean.model.McsModel.McsPlcVariable; import com.intplog.mcs.bean.viewmodel.PageData; import com.intplog.mcs.common.JsonData; import com.intplog.mcs.mapper.McsMapper.McsPlcVariableMapper; import com.intplog.mcs.service.McsService.McsPlcVariableService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.text.MessageFormat; import java.util.List; import java.util.stream.Collectors; /** * @author suizhonghao * @version 1.0 * @date 2019/10/15 13:50 */ @Service @Transactional(rollbackFor = Exception.class) public class McsPlcVariableServiceImpl implements McsPlcVariableService { @Resource private McsPlcVariableMapper mcsPlcVariableMapper; @Override public McsPlcVariable getPlc(String groupNumber, String cooder, int type) { return mcsPlcVariableMapper.getPLcAddress(groupNumber,cooder,type); } @Override public List<McsPlcVariable> getExcelExport(String ip, String name) { return mcsPlcVariableMapper.getList(ip, name); } @Override public JsonData importExcel(List<McsPlcVariable> mcsPlcVariableList) { List<McsPlcVariable> plcVariableList = mcsPlcVariableMapper.getAll(); List<String> idList = plcVariableList.stream().map(a -> a.getId()).collect(Collectors.toList()); List<String> ipList = plcVariableList.stream().map(a -> a.getAddress()).collect(Collectors.toList()); if (mcsPlcVariableList.size() > 0) { for (int i = 0; i < mcsPlcVariableList.size(); i++) { McsPlcVariable mcsPlcVariable=mcsPlcVariableList.get(i); if (idList.contains(mcsPlcVariable.getId())||ipList.contains(mcsPlcVariable.getAddress())){ return JsonData.fail(MessageFormat.format("导入数据第{0}行编号和IP地址已存在",i+1),mcsPlcVariable.id); } } int i=mcsPlcVariableMapper.importList(mcsPlcVariableList); if (i>0){ return JsonData.success(MessageFormat.format("导入数据成功,受影响行数{0}",mcsPlcVariableList.size())); } else { return JsonData.fail("2"); } } else { return JsonData.fail("导入数据为空", "3"); } } @Override public PageData getAll(String name, String groupNumber, int pageNum, int pageSize) { PageData pageData = new PageData(); Page<Object> page = PageHelper.startPage(pageNum, pageSize); List<McsPlcVariable> all = mcsPlcVariableMapper.getList(name, groupNumber); pageData.setMsg(""); pageData.setCount(page.getTotal()); pageData.setCode(0); pageData.setData(all); return pageData; } @Override public List<McsPlcVariable> getAll() { return mcsPlcVariableMapper.getAll(); } @Override public List<McsPlcVariable> getByPlcName(String plcName) { return mcsPlcVariableMapper.getByPlcName(plcName) ; } @Override public McsPlcVariable getMcsPlcVariableById(String id) { return mcsPlcVariableMapper.getMcsPlcVariableById(id); } @Override public McsPlcVariable getByTypeAndCoord(String coord) { return mcsPlcVariableMapper.getByTypeAndCoord(coord); } @Override public McsPlcVariable getByTypeAndName(int type, String name) { return mcsPlcVariableMapper.getByTypeAndName(type,name); } @Override public McsPlcVariable getByCoord(String coord) { return mcsPlcVariableMapper.getByCoord(coord); } @Override public int insertMcsPlcVariable(McsPlcVariable mcsPlcVariable) { return mcsPlcVariableMapper.insertMcsPlcVariable(mcsPlcVariable); } @Override public int updateMcsPlcVariable(McsPlcVariable mcsPlcVariable) { return mcsPlcVariableMapper.updateMcsPlcVariable(mcsPlcVariable); } @Override public int updateMcsPlcVariableByGroupNumber(McsPlcVariable mcsPlcVariable) { return mcsPlcVariableMapper.updateMcsPlcVariableByGroupNumber(mcsPlcVariable); } @Override public McsPlcVariable getCoordAndType(String coord, int type) { return mcsPlcVariableMapper.getByCoordAndType(coord,type); } @Override public PageData deleteMcsPlcVariableById(String id) { PageData pageData = new PageData(); int i = mcsPlcVariableMapper.deleteMcsPlcVariableById(id); pageData.setMsg(""); pageData.setCode(0); if (i < 1) { pageData.setMsg("更新失败"); } return pageData; } }
[ "BIGBIGGANG@live.com" ]
BIGBIGGANG@live.com
e54986cbcb401ed62cefcd12934eea8cc8eb4724
2c975a422f9e276a15ae7fd6f4a53b76ecdbe21a
/src/main/java/ben/study/gas/controller/BillDetailController.java
9c7d6192550aff40c8112c6dfe1ad2453b8345d1
[]
no_license
bengold20/myGas
92ee617aea4497f02dbb166e953134e2eb3c5aab
e7e9dcf630a8bd659b3e94ca30fcc86c4014204c
refs/heads/main
2023-07-27T17:26:57.923740
2021-09-12T12:03:40
2021-09-12T12:03:40
405,608,105
0
0
null
2021-09-12T12:03:40
2021-09-12T10:12:17
Java
UTF-8
Java
false
false
1,974
java
package ben.study.gas.controller; import ben.study.gas.entity.Bill; import ben.study.gas.entity.BillDetail; import ben.study.gas.entity.WarehouseDetail; import ben.study.gas.repository.WarehouseDetailRepository; import ben.study.gas.service.BillDetailService; import ben.study.gas.service.WarehouseDetailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.transaction.Transactional; import java.util.List; @RestController public class BillDetailController { @Autowired private BillDetailService billDetailService; @Autowired private WarehouseDetailRepository warehouseDetailRepository; @Autowired private WarehouseDetailService warehouseDetailService; @PostMapping("/bill-detail") @Transactional public BillDetail addBillDetail(@RequestBody BillDetail billDetail) { WarehouseDetail whdt = warehouseDetailRepository.selectWarehouseDetailById(billDetail.getId_warehoureDetail()); WarehouseDetail whdtupdate = warehouseDetailService.updateWarehouseDetailById(whdt); whdtupdate.setId(whdt.getId()); whdtupdate.setId_warehouse(whdt.getId_warehouse()); whdtupdate.setId_gas(whdt.getId_gas()); whdtupdate.setQuantity(whdt.getQuantity() + billDetail.getQuantity()); return billDetailService.addBillDetail(billDetail); } @PostMapping("/bill-details") public List<BillDetail> addBillDetails(@RequestBody List<BillDetail> billDetails){ return billDetailService.addBillDetails(billDetails); } @DeleteMapping("/bills-details") public String deleteAllBillDetail(@RequestBody BillDetail billDetail){ return billDetailService.deleteAllBillDetail(billDetail); } }
[ "phattrien0222@gmail.com" ]
phattrien0222@gmail.com
0d82b12b87f9829fd8fe9b695846bf43fe0582d5
1d9358bc1e136c7e0014ce42b5183e7553c31dde
/src/actions/add/AddReservation.java
65bce3bdc76617e4a907b24ddeb88e52590ea280
[]
no_license
msaleh2/Hotel-Database-System
44e91289e8512f8b10d6984ca48e4a32e1519f95
326989da9f5ae0cb44d5cef7c995d8bc6d5f10e3
refs/heads/master
2021-08-08T15:24:18.963566
2017-11-10T15:58:07
2017-11-10T15:58:07
105,072,844
0
0
null
null
null
null
UTF-8
Java
false
false
1,094
java
/** * */ package actions.add; import java.sql.SQLException; import models.Reservation; import sql.ReservationDBA; import sql.RoomDBA; /** * Adding a reservation functionality. * * @author Anusha Balaji (abalaji) * */ public class AddReservation { /** * Adds the given room to the database; hotel must already exists or error is thrown * @param r Room to be added to the database * @return message about the result of the action or null if hotel doesn't exist * @throws SQL exception when error adding a room to the database */ public static String addReservation(ReservationDBA dba, Reservation r) { try { dba.addReservation(r); return "Success: Reservation added! " ; } catch(SQLException e) { return "Failed to add reservation"; } } public static String addPresidentialReservation(ReservationDBA dba, Reservation r, int cateringStaff, int roomStaff) { try { dba.addPresidentialReservation(r, cateringStaff, roomStaff); return "Success: Reservation added! " ; } catch(SQLException e) { return "Failed to add reservation"; } } }
[ "msaleh@ncsu.edu" ]
msaleh@ncsu.edu
4516a5679be86defcfd9b02ed68645d3f00bb9fa
f7322c512d51b5482504f77c6df1e6532e5754ee
/app/src/test/java/com/toni/dialogoalerta/ExampleUnitTest.java
69e7f45f6696cf3dbd823ff22ba34868a40baa7e
[]
no_license
AntoniaPuertas/Dialogos
bd60256d9e03f607035a659212af462df0728d80
b93a33616cbc4c7db30420b5a476b0f987b4a7e4
refs/heads/master
2023-05-01T07:07:36.762687
2021-05-18T09:55:29
2021-05-18T09:55:29
368,480,328
0
0
null
null
null
null
UTF-8
Java
false
false
383
java
package com.toni.dialogoalerta; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
[ "tsm.antonia@gmail.com" ]
tsm.antonia@gmail.com
f619a35bd6d6b06d9a9c9c2a80eb86ef129e9155
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/9/9_4b4543a968520223b36e7b641572add2a7566a70/SchoolChoiceReminderBMPBean/9_4b4543a968520223b36e7b641572add2a7566a70_SchoolChoiceReminderBMPBean_t.java
ab7e81781ae893ca44de706da96699605198f52f
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
6,436
java
package se.idega.idegaweb.commune.school.data; import java.util.Calendar; import java.util.Collection; import java.util.Iterator; import javax.ejb.FinderException; import com.idega.block.process.data.AbstractCaseBMPBean; import com.idega.block.process.data.Case; import com.idega.block.process.data.CaseBMPBean; import com.idega.block.process.data.CaseCode; import com.idega.block.process.data.CaseCodeHome; import com.idega.data.IDOLookup; import com.idega.data.IDOQuery; import com.idega.user.data.Group; import com.idega.user.data.User; /** * Last modified: $Date: 2005/02/10 12:00:15 $ by $Author: laddi $ * * @author <a href="http://www.staffannoteberg.com">Staffan Nteberg</a> * @version $Revision: 1.14 $ */ public class SchoolChoiceReminderBMPBean extends AbstractCaseBMPBean implements SchoolChoiceReminder, Case { private static final String ENTITY_NAME = "sch_reminder"; private static final String CASE_CODE_DESCRIPTION = "School Choice Reminder"; private static final String[] CASE_STATUS_DESCRIPTIONS = { }; private static final String[] CASE_STATUS_KEYS = { }; //private static final String COLUMN_ID = ENTITY_NAME + "_id"; private static final String COLUMN_USER_ID = "USER_ID"; private static final String COLUMN_TEXT = "REMINDER_TEXT"; private static final String COLUMN_EVENT_DATE = "EVENT_DATE"; private static final String COLUMN_REMINDER_DATE = "REMINDER_DATE"; public String getEntityName() { return ENTITY_NAME; } public String getCaseCodeKey() { return SchoolChoiceReminder.CASE_CODE_KEY; } public String getCaseCodeDescription() { return CASE_CODE_DESCRIPTION; } public String[] getCaseStatusKeys() { return CASE_STATUS_KEYS; } public String[] getCaseStatusDescriptions() { return CASE_STATUS_DESCRIPTIONS; } public void insertStartData() { insertCaseCode(); } public void initializeAttributes() { addGeneralCaseRelation(); addAttribute(COLUMN_USER_ID, "User", true, true, Integer.class, "many-to-one", User.class); addAttribute(COLUMN_TEXT, "Text", true, true, String.class, 4096); addAttribute(COLUMN_EVENT_DATE, "Event Date", java.sql.Date.class); addAttribute(COLUMN_REMINDER_DATE, "Reminder Date", java.sql.Date.class); } public String getText() { final String text = getStringColumnValue(COLUMN_TEXT); return text != null ? text : ""; } public java.util.Date getEventDate() { final java.util.Date eventDate = (java.util.Date) getColumnValue(COLUMN_EVENT_DATE); return eventDate != null ? eventDate : new java.util.Date(); } public java.util.Date getReminderDate() { final java.util.Date reminderDate = (java.util.Date) getColumnValue(COLUMN_REMINDER_DATE); return reminderDate != null ? reminderDate : new java.util.Date(); } public int getUserId() { final Integer userId = getIntegerColumnValue(COLUMN_USER_ID); return userId != null ? userId.intValue() : -1; } public void setText(final String text) { setColumn(COLUMN_TEXT, text != null ? text : ""); } public void setEventDate(final java.util.Date eventDate) { setColumn(COLUMN_EVENT_DATE, new java.sql.Date(eventDate != null ? eventDate.getTime() : new java.util.Date().getTime())); } public void setReminderDate(final java.util.Date reminderDate) { setColumn(COLUMN_REMINDER_DATE, new java.sql.Date(reminderDate != null ? reminderDate.getTime() : new java.util.Date().getTime())); } public void setUser(final User user) { if (user != null) { setColumn(COLUMN_USER_ID, ((Integer) user.getPrimaryKey()).intValue()); } } public Collection ejbFindAll() throws FinderException { final IDOQuery query = idoQuery(); query.appendSelect().append("scr.*").appendFrom().append(getEntityName()).append(" scr").append(", ").append(CaseBMPBean.TABLE_NAME).append(" pc"); query.appendWhere().append("scr.").append(getIDColumnName()).appendEqualSign().append("pc.").append(CaseBMPBean.TABLE_NAME + "_ID").appendAnd().append("pc.").append(CaseBMPBean.COLUMN_CASE_STATUS).appendEqualSign().appendWithinSingleQuotes("UBEH").appendAnd().append("pc.").append(CaseBMPBean.COLUMN_CASE_CODE).appendEqualSign().appendWithinSingleQuotes(SchoolChoiceReminder.CASE_CODE_KEY); final Collection primaryKeys = idoFindPKsByQuery(query); return primaryKeys; } public Collection ejbFindUnhandled(final Group[] groups) throws FinderException { final IDOQuery query = idoQuery(); final Calendar today = Calendar.getInstance(); final String date = today.get(Calendar.YEAR) + "-" + (today.get(Calendar.MONTH) + 1) + "-" + today.get(Calendar.DATE); query.appendSelect().append("scr.*").appendFrom().append(getEntityName()).append(" scr").append(", ").append(CaseBMPBean.TABLE_NAME).append(" pc"); query.appendWhere().append("scr.").append(getIDColumnName()).appendEqualSign().append("pc.").append(CaseBMPBean.TABLE_NAME + "_ID").appendAnd().append("pc.").append(CaseBMPBean.COLUMN_CASE_STATUS).appendEqualSign().appendWithinSingleQuotes("UBEH").appendAnd().append("pc.").append(CaseBMPBean.COLUMN_CASE_CODE).appendEqualSign().appendWithinSingleQuotes(SchoolChoiceReminder.CASE_CODE_KEY).appendAnd().append(COLUMN_REMINDER_DATE).append(" <= ").appendWithinSingleQuotes(date); for (int i = 0; i < groups.length; i++) { query.append(i == 0 ? " and (" : " or "); final int groupId = ((Integer) groups[i].getPrimaryKey()).intValue(); query.append("pc.handler_group_id = '" + groupId + "'"); // special notice for super admin group, i.e. 1 if (groupId == 1) query.append(" or 1 = 1"); } query.append(")"); final Collection primaryKeys = idoFindPKsByQuery(query); return primaryKeys; } private synchronized void insertCaseCode() { try { final CaseCodeHome home = (CaseCodeHome) IDOLookup.getHome(CaseCode.class); final Collection codes = home.findAllCaseCodes(); boolean codeExists = false; for (Iterator i = codes.iterator(); i.hasNext();) { final CaseCode code = (CaseCode) i.next(); codeExists = code.getCode().equalsIgnoreCase(SchoolChoiceReminder.CASE_CODE_KEY); } if (!codeExists) { final CaseCode code = home.create(); code.setCode(SchoolChoiceReminder.CASE_CODE_KEY); code.setDescription("School choice reminder"); code.store(); } } catch (final Exception e) { //e.printStackTrace (); } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
ab82b021c5529d685116da0ed383d44c52b85681
68df436539222fde39d1d159ecea69fba5801be5
/src/mrl/firebrigade/sterategy/StuckFireBrigadeActionStrategy.java
da9935e0e1541863f2af99945cf5c4737eb594fc
[]
no_license
MRL-RS/agent-simulation
8492353fc87a490aef410769a10fcdef38a979b4
8299b1ba0826b977a6e13a0c8263f282cda51dc1
refs/heads/master
2020-03-20T05:31:14.529241
2018-04-20T18:46:45
2018-04-20T18:46:45
137,217,327
1
1
null
null
null
null
UTF-8
Java
false
false
4,845
java
package mrl.firebrigade.sterategy; import mrl.MrlPersonalData; import mrl.common.CommandException; import mrl.common.TimeOutException; import mrl.firebrigade.FireBrigadeUtilities; import mrl.firebrigade.MrlFireBrigadeDirectionManager; import mrl.firebrigade.MrlFireBrigadeWorld; import mrl.helper.HumanHelper; import mrl.platoon.State; import mrl.world.object.MrlBuilding; import rescuecore2.standard.entities.Building; import rescuecore2.standard.entities.StandardEntity; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * User: MRL * Date: 3/11/13 * Time: 5:39 PM * Author: Mostafa Movahedi */ public class StuckFireBrigadeActionStrategy extends FireBrigadeActionStrategy { public StuckFireBrigadeActionStrategy(MrlFireBrigadeWorld world, FireBrigadeUtilities fireBrigadeUtilities, MrlFireBrigadeDirectionManager directionManager) { super(world, fireBrigadeUtilities, directionManager); } @Override public void execute() throws CommandException, TimeOutException { if (world.getHelper(HumanHelper.class).isBuried(selfHuman.getID())) { self.setAgentState(State.BURIED); return; } moveToRefugeIfDamagedOrTankIsEmpty(); MrlBuilding extinguishTarget = chooseTarget(); if (extinguishTarget != null) { MrlPersonalData.VIEWER_DATA.setFireBrigadeData(world.getSelfHuman().getID(), extinguishTarget); } else { MrlPersonalData.VIEWER_DATA.setFireBrigadeData(world.getSelfHuman().getID(), null); } if (extinguishTarget != null) { self.sendExtinguishAct(world.getTime(), extinguishTarget.getID(), Math.min(world.getMaxPower(), self.getWater())); } } /** * gets type of the action strategy */ @Override public FireBrigadeActionStrategyType getType() { return FireBrigadeActionStrategyType.STUCK_SITUATION; } private MrlBuilding chooseTarget() { MrlBuilding targetBuilding = null; MrlBuilding building; List<MrlBuilding> warmBuildings = new ArrayList<MrlBuilding>(); List<MrlBuilding> fOneBuildings = new ArrayList<MrlBuilding>(); List<MrlBuilding> fTwoBuildings = new ArrayList<MrlBuilding>(); List<MrlBuilding> fThreeBuildings = new ArrayList<MrlBuilding>(); int maxExtinguishDistance = world.getMaxExtinguishDistance(); for (StandardEntity entity : world.getObjectsInRange(world.getSelfLocation().first(), world.getSelfLocation().second(), world.getMaxExtinguishDistance())) { if (entity instanceof Building) { int myDistanceToTarget = world.getDistance(world.getSelfHuman(), entity); if (myDistanceToTarget <= maxExtinguishDistance) { building = world.getMrlBuilding(entity.getID()); if (building.getSelfBuilding().isFierynessDefined()) { switch (building.getSelfBuilding().getFieryness()) { case 1: fOneBuildings.add(building); break; case 2: fTwoBuildings.add(building); break; case 3: fThreeBuildings.add(building); break; case 0: case 4: if (building.getSelfBuilding().isTemperatureDefined() && building.getSelfBuilding().getTemperature() > 0) { warmBuildings.add(building); } } } } } } // TODO @Pooya: check other properties than totalArea if (!fOneBuildings.isEmpty()) { // targetBuilding = fireBrigadeUtilities.findSmallestBuilding(fOneBuildings); targetBuilding = fireBrigadeUtilities.findNewestIgnitedBuilding(fOneBuildings); } else if (!warmBuildings.isEmpty()) { // targetBuilding = fireBrigadeUtilities.findSmallestBuilding(warmBuildings); targetBuilding = fireBrigadeUtilities.findNewestIgnitedBuilding(warmBuildings); } else if (!fTwoBuildings.isEmpty()) { // targetBuilding = fireBrigadeUtilities.findSmallestBuilding(fTwoBuildings); targetBuilding = fireBrigadeUtilities.findNewestIgnitedBuilding(fTwoBuildings); } else if (!fThreeBuildings.isEmpty()) { // targetBuilding = fireBrigadeUtilities.findSmallestBuilding(fThreeBuildings); targetBuilding = fireBrigadeUtilities.findNewestIgnitedBuilding(fThreeBuildings); } return targetBuilding; } }
[ "mahdi.tn@gmail.com" ]
mahdi.tn@gmail.com
4e7b3eab7723e58e3dc4dd30439822720c4706a5
bec329a01ef6608f1ab42d781c64398e7a85b205
/src/main/java/project/rest/field/MessageFieldPopulator.java
bfddd55d84d7defdd00c8244e825931ba295eda4
[]
no_license
jacktri/Mail-System
debb56bdf3cd39df02a2ad83a9c5de8f5daa0630
5391486497ff492836329484bf6a0890c67e59e0
refs/heads/master
2020-04-06T04:07:58.812000
2017-02-28T17:49:36
2017-02-28T17:49:36
83,044,593
0
0
null
null
null
null
UTF-8
Java
false
false
1,696
java
package project.rest.field; import org.springframework.stereotype.Component; import project.common.rest.Field; import project.common.rest.FieldPopulator; import project.common.rest.IFieldName; import project.controller.dto.MessageDto; import project.vo.MessageVo; import java.util.ArrayList; import java.util.List; import static project.rest.field.MessageFieldName.*; @Component public class MessageFieldPopulator extends FieldPopulator<MessageDto.Builder, MessageVo> { @Override public MessageDto.Builder populateField(MessageDto.Builder dtoBuilder, MessageVo vo, Field field) { if (SENDER.equals(field.getFieldName())) { dtoBuilder.sender(vo.getSender().getLogin()); } else if (RECEIVER.equals(field.getFieldName())) { dtoBuilder.receiever(vo.getReciever().getLogin()); } else if (CONTENT.equals(field.getFieldName())) { dtoBuilder.content(vo.getContent()); } else if (SENDDATETIME.equals(field.getFieldName())) { dtoBuilder.sendDateTime(vo.getSendDateTime().toString()); } return dtoBuilder; } @Override public IFieldName[] getAllFieldNames() { return MessageFieldName.values(); } public Field[] getAllChildFields() { List<Field> allChildFields = new ArrayList<>(); for (Field field : allFields.values()) { if (field.getFieldName().getChildFieldNames() == null) { allChildFields.add(field); } } return allChildFields.toArray(new Field[allChildFields.size()]); } }
[ "jack.savory@thomsonreuters.com" ]
jack.savory@thomsonreuters.com
475c73dbf0a36e57491c97b03446a150d6ec3fb9
b4ff6066babcde312d29f559c540bafefe3ee452
/BulkSMS/src/main/java/co/ke/bigfootke/app/security/AuthorizationServer.java
cdfb53ec3bef110763ef98f3ad8ed90db6fb9685
[]
no_license
Kanyi-JavaGuru/Bulk-sms-backend-server
d9c16ce97a29678720aa82b3f63feb7e47458a1a
b98059575d1d71ccbfbc48c38472d81e2f303670
refs/heads/master
2020-03-11T01:17:32.639249
2018-05-16T02:40:21
2018-05-16T02:40:21
129,687,408
0
0
null
null
null
null
UTF-8
Java
false
false
2,193
java
package co.ke.bigfootke.app.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; @Configuration @EnableAuthorizationServer public class AuthorizationServer extends AuthorizationServerConfigurerAdapter{ @Autowired private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager) .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.GET) ; } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.tokenKeyAccess("hasAuthority('ROLE_ADMIN') || hasAuthority('ROLE_USER')") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("test01") .secret("test01") // .authorizedGrantTypes("client_credentials", "password","authorization_code","refresh_token") /**password for first time sign in/login or expiration of refresh token * refresh token after login**/ .authorizedGrantTypes( "password") .authorities("ROLE_ADMIN", "ROLE_USER") .scopes("read", "write", "trust") .resourceIds("oauth2-resource") .accessTokenValiditySeconds(3600)//expires in 1 hour .refreshTokenValiditySeconds(604800);//expires after 7 days } }
[ "mbugua.kevinkanyi@gmail.com" ]
mbugua.kevinkanyi@gmail.com
31b6416bf5ce6683fe43e0f66433b23251f9144e
ab54b7ff82580c4791c4654cf6102f9c75baf50f
/core/src/com/systemphoenix/edenalpha/Actors/ObjectActors/Animal.java
9a536768ef6892573fdfb943a43fe2254036f987
[]
no_license
system-phoenix/EdenAlphaV2
98d17a8d1cc03b6127ebc5ed04bbc6f698a993c2
f25f12a9e8c9bf0b09689010cf6a5834ef46496a
refs/heads/master
2021-03-24T11:54:26.549939
2017-05-04T07:01:36
2017-05-04T07:01:36
76,408,181
0
1
null
null
null
null
UTF-8
Java
false
false
3,051
java
package com.systemphoenix.edenalpha.Actors.ObjectActors; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Disposable; import com.systemphoenix.edenalpha.Codex.AnimalCodex; import com.systemphoenix.edenalpha.Screens.GameScreen; public class Animal extends Actor implements Disposable { private GameScreen gameScreen; private long effectTimer, effectLimit; private boolean disposable = false; private Sprite sprite; private Pulse pulse = null; private Arena arena = null; public Animal (GameScreen gameScreen, Sprite sprite, Sprite arenaSprite, float damage, int animalIndex) { this.gameScreen = gameScreen; this.sprite = new Sprite(sprite); this.effectLimit = AnimalCodex.effectLimit[animalIndex]; this.sprite.setBounds(gameScreen.getSelectedXY().x, gameScreen.getSelectedXY().y, 64, 64); switch(animalIndex) { case 0: Rectangle hitBox = gameScreen.getHitRectangle(); if(gameScreen.getRegion().getLifePercentage() < 40) { damage *= 0.5f; } else if(gameScreen.getRegion().getLifePercentage() < 60) { damage *= 1f; } else { damage *= 2f; } pulse = new Pulse(gameScreen, hitBox, (int)damage, gameScreen.getPulseAnimation()); break; case 1: if(gameScreen.getRegion().getLifePercentage() < 40) { damage *= 2f; } else if(gameScreen.getRegion().getLifePercentage() < 60) { damage *= 1f; } else { damage *= 0.5f; } arena = new Arena(gameScreen, arenaSprite, gameScreen.getSelectedXY().x, gameScreen.getSelectedXY().y, damage, animalIndex, true); break; case 2: arena = new Arena(gameScreen, arenaSprite, gameScreen.getSelectedXY().x, gameScreen.getSelectedXY().y, damage, animalIndex, false); break; } effectTimer = gameScreen.getCentralTimer(); } @Override public void draw(Batch batch, float alpha) { sprite.draw(batch); if(pulse != null) { pulse.render(batch, Gdx.graphics.getDeltaTime()); if(pulse.isDisposable()) { pulse = null; } } else if(arena != null) { arena.render(batch); } if(gameScreen.getCentralTimer() - effectTimer >= effectLimit) { disposable = true; } } @Override public void dispose() { if(pulse != null) { pulse = null; } else if(arena != null) { arena.dispose(); arena = null; } } public boolean isDisposable() { return disposable; } }
[ "dmorias@up.edu.ph" ]
dmorias@up.edu.ph
153bed46e34ec7aede85c53261e6a51e713210d2
722ac9e61dfc04a7bee0c422b0d6ebd9e14271ca
/src/main/java/org/java/service/PatientService.java
9153c9fe92f9cab7f6930b2b20f3afac836af25a
[]
no_license
862171455/hospital
7f7087044150cb6f0c0d2207f37b8c3a883fdac2
1c12c68163d11d8b5ddb8da125f149264a082097
refs/heads/master
2022-06-28T04:14:19.716189
2019-08-31T02:11:56
2019-08-31T02:11:56
201,697,119
0
0
null
2022-06-21T01:38:35
2019-08-11T00:19:00
HTML
UTF-8
Java
false
false
646
java
package org.java.service; import java.util.List; import java.util.Map; /** * Created by GD on 2019/8/11 0011 10:51 */ public interface PatientService { Map<String,Object> findbyUuAndP(Map<String,Object> map);//病人账号密码登录 void updatepwd(Map<String,Object> map);//密码修改 void updateDetails(Map<String,Object> map);//信息修改 void addPatient(Map<String,Object> map);//患者注册 List<Map<String,Object>> findalltel();//查看已注册的手机 List<Map<String,Object>> findalluser();//查看已注册的用户 List<Map<String,Object>> findallbr(Map<String,Object> map);//查看全部病人 int findbrcount(); }
[ "862171455@qq.com" ]
862171455@qq.com
d3283df5d74094a54338a3a80e2a7251166ea2b2
177cd5cb7b9649e8bc0fea1d85c4d76b37692836
/test/test-run/fileHeader/test.java
574eea7ffc1b0fa1c1b9d0e9d412675f53991757
[ "MIT" ]
permissive
OBKoro1/koro1FileHeader
ca221fff25713634dab25d9f1d076c14d5135595
8dad9d0018bc4c6087a5db97efe7e7655adaacdd
refs/heads/master
2023-07-05T08:32:15.068454
2023-01-29T08:06:36
2023-01-29T08:10:11
132,321,714
5,303
290
MIT
2023-04-19T07:14:48
2018-05-06T08:50:53
JavaScript
UTF-8
Java
false
false
811
java
/** * @Author: OBKoro1 * @Date: 2019-09-24 20:25:33 * @LastEditors: OBKoro1 * @LastEditTime: 2020-02-05 10:19:02 * @FilePath: /fileHead/test.java * @Description: * @https://github.com/OBKoro1 */ public class Solution { /* * @param nums: A list of integers.222 * @return: A list of permutations. */ public List<List<Integer>> permute(int[] nums) { // write your code here } } /** 返回两个整型变量数据的较大值 */ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } public class CommandLine { public static void main(String args[]){ for(int i=0; i<args.length; i++){ System.out.println("args[" + i + "]: " + args[i]); } } }
[ "obkoro1@foxmail.com" ]
obkoro1@foxmail.com
55f4c7683180e5cf53ceac25fcb600e714f43bf5
c8f5b07c57fcd8b5504d9d43c6dd11b771b2f1de
/common/src/main/java/net/rajpals/common/pickers/TimePickerFragment.java
cb295ee85e6fdae9da0ea689c5f647124ca78ced
[]
no_license
HeshamElShafei95/3ezooma_app_public
c9c040434de236f15300f4b92556ad412b922386
1ec09ee3d699b1bd94fe12dc413f7ffc36fa1831
refs/heads/master
2021-01-03T03:25:38.093390
2020-02-23T15:41:26
2020-02-23T15:41:26
239,902,107
0
0
null
null
null
null
UTF-8
Java
false
false
1,815
java
package net.rajpals.common.pickers; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import android.widget.TimePicker; import java.util.Calendar; public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { public static final String TAG = TimePickerFragment.class.getSimpleName(); private OnTimeListener mOnTimeListener; @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); if (mOnTimeListener != null) mOnTimeListener.onTimeSelected(calendar); dismiss(); } public static TimePickerFragment newInstance() { Bundle args = new Bundle(); TimePickerFragment fragment = new TimePickerFragment(); fragment.setArguments(args); return fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int min = c.get(Calendar.MINUTE); // Create a new instance of DatePickerDialog and return it TimePickerDialog dialog = new TimePickerDialog(getActivity(),this,hour,min,false); return dialog; } public void setOnTimeListener(OnTimeListener onTimeListener) { mOnTimeListener = onTimeListener; } public interface OnTimeListener { void onTimeSelected(Calendar date); } }
[ "sonal.grover12@gmail.com" ]
sonal.grover12@gmail.com
0577d815a7545615ceb7aa6a91e346f8a0630aa7
8b1a23bff17ee19e8b01789071db7516863e0a2a
/Java/Software1/Assignment8/src/il/ac/tau/cs/sw1/ex8/wordsRank/FileIndex.java
e91c40f56467aca84c3557178978ba216e3ee38c
[]
no_license
felixNan/cs-projects
4e49d14a2016464643167a0cf270faab667df137
faecd807ce94cce2a910ac441ed92a99c14dfbf3
refs/heads/master
2020-04-11T20:02:09.455387
2018-12-15T16:41:48
2018-12-15T16:41:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,063
java
package il.ac.tau.cs.sw1.ex8.wordsRank; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import il.ac.tau.cs.sw1.ex8.histogram.HashMapHistogram; import il.ac.tau.cs.sw1.ex8.wordsRank.RankedWord.rankType; /************************************** * Add your code to this class !!! * **************************************/ public class FileIndex { public static final int UNRANKED_CONST = 20; private HashMap<String, HashMapHistogram<String>> index; private HashMap<String, HashMap<String, Integer>> wordToFilesToRank; private HashMap<String, RankedWord> rankOfWords; private int unranked; public FileIndex() { this.index = new HashMap<>(); this.wordToFilesToRank = new HashMap<>(); this.rankOfWords = new HashMap<>(); this.unranked = 0; } private void rankWordsInFile(String fileName){ Iterator<String> iter = this.index.get(fileName).iterator(); int rank = 0; String word; while (iter.hasNext()){// Build a map between each word to it's rank in the file word = iter.next(); rank++; if (!this.wordToFilesToRank.containsKey(word))// Add new word to mapping this.wordToFilesToRank.put(word, new HashMap<String, Integer>()); this.wordToFilesToRank.get(word).put(fileName, rank);// If word already seen, update it's map } } private void addRanksToWords (){ int diffrentWordCount; for (String word : this.wordToFilesToRank.keySet()) { for (String fileName : this.index.keySet()){ try { if (getCountInFile(fileName, word) == 0){// Fill the files the word didn't appeared in them diffrentWordCount = this.index.get(fileName).getItemsSet().size(); this.wordToFilesToRank.get(word).put(fileName, diffrentWordCount + UNRANKED_CONST); } }catch (FileIndexException e) { e.toString(); } } this.rankOfWords.put(word, new RankedWord(word, this.wordToFilesToRank.get(word)));// Add the word to RankedWords mapping } } /* * @pre: the directory is no empty, and contains only readable text files */ public void indexDirectory(String folderPath) { // This code iterates over all the files in the folder. add your code // wherever is needed File folder = new File(folderPath); File[] listFiles = folder.listFiles(); for (File file : listFiles) { // for every file in the folder if (file.isFile()) { try { if (!this.index.containsKey(file.getName())){// Make sure file wasn't checked before List<String> wordsInFile = FileUtils.readAllTokens(file); HashMapHistogram<String> histogram = new HashMapHistogram<>(); histogram.addAll(wordsInFile); this.index.put(file.getName(), histogram); this.unranked += histogram.getItemsSet().size() + UNRANKED_CONST; rankWordsInFile(file.getName()); } } catch (IOException e) { System.err.println("Folder is empty or contains unreadable files"); } } } addRanksToWords(); } /* * @pre: the index is initialized * * @pre filename is a name of a valid file * * @pre word is not null */ public int getCountInFile(String filename, String word) throws FileIndexException { if (!index.containsKey(filename))// filename doesn't exist in directory throw new FileIndexException("The file doesn't exist in the directory!"); return index.get(filename).getCountForItem(word.toLowerCase()); } /* * @pre: the index is initialized * * @pre filename is a name of a valid file * * @pre word is not null */ public int getRankForWordInFile(String filename, String word) throws FileIndexException { if (!this.index.containsKey(filename)) throw new FileIndexException("The file doesn't exist in the directory!"); String lowerCase = word.toLowerCase(); if (this.wordToFilesToRank.containsKey(lowerCase)) return this.wordToFilesToRank.get(lowerCase).get(filename); return this.index.get(filename).getItemsSet().size() + UNRANKED_CONST; } /* * @pre: the index is initialized * * @pre word is not null */ public int getAverageRankForWord(String word) { String lowerCase = word.toLowerCase(); if (this.rankOfWords.containsKey(lowerCase)) return this.rankOfWords.get(lowerCase).getRankByType(rankType.average); return (int)Math.round(((double)this.unranked) / this.index.size()); } public List<String> aboveK (int k, rankType cType){ List<RankedWord> rankedWordList = new ArrayList<>(this.rankOfWords.values()); Collections.sort(rankedWordList, new RankedWordComparator(cType)); List<String> list = new ArrayList<>(); int i = 0; while (rankedWordList.get(i).getRankByType(cType) <= k) list.add(rankedWordList.get(i++).getWord()); return list; } public List<String> getWordsWithAverageRankLowerThenK(int k) { return aboveK(k, rankType.average); } public List<String> getWordsBelowMinRank(int k) { return aboveK(k, rankType.min); } public List<String> getWordsAboveMaxRank(int k) { return aboveK(k, rankType.max); } }
[ "31568986+Rpsn@users.noreply.github.com" ]
31568986+Rpsn@users.noreply.github.com
9ab87a951e549f8ce286bc71be5eeb50caa74ddf
6556cbbffe85267562ab0db5123b2ffd7b4e3249
/src/main/java/com/bhst/wq/service/impl/WqPunchManagementServiceImpl.java
8596d0e7170e1c5f69893783d9b9070f20100c30
[]
no_license
suhaihao/wq
30ee2e584223a9c8f4440fa4be70b61a8fce4e68
239c5c6ae8bb711a27d4c4aae92a7f79dbb2f8d4
refs/heads/master
2022-11-24T03:12:09.640703
2020-07-30T03:48:54
2020-07-30T03:48:54
266,343,526
0
0
null
null
null
null
UTF-8
Java
false
false
4,683
java
package com.bhst.wq.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.bhst.wq.entity.WqActivityRecruitment; import com.bhst.wq.entity.WqPunchManagement; import com.bhst.wq.entity.WqUser; import com.bhst.wq.mapper.WqActivityRecruitmentMapper; import com.bhst.wq.mapper.WqPunchManagementMapper; import com.bhst.wq.mapper.WqUserMapper; import com.bhst.wq.request.WqPunchManagementDetailDelRequest; import com.bhst.wq.request.WqPunchManagementPageListRequest; import com.bhst.wq.service.WqPunchManagementService; import com.bhst.wq.utils.UserUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.List; import java.util.stream.Collectors; @Service public class WqPunchManagementServiceImpl extends ServiceImpl<WqPunchManagementMapper, WqPunchManagement> implements WqPunchManagementService { private final WqPunchManagementMapper wqPunchManagementMapper; private final WqUserMapper wqUserMapper; private final WqActivityRecruitmentMapper wqActivityRecruitmentMapper; @Autowired public WqPunchManagementServiceImpl(WqPunchManagementMapper wqPunchManagementMapper, WqUserMapper wqUserMapper, WqActivityRecruitmentMapper wqActivityRecruitmentMapper) { this.wqPunchManagementMapper = wqPunchManagementMapper; this.wqUserMapper = wqUserMapper; this.wqActivityRecruitmentMapper = wqActivityRecruitmentMapper; } @Override public IPage<WqPunchManagement> getPageList(WqPunchManagementPageListRequest request) { Page<WqPunchManagement> page = new Page<>(request.getPageIndex(), request.getPageSize()); QueryWrapper<WqPunchManagement> queryWrapperUser = new QueryWrapper(); queryWrapperUser.eq("user_id", UserUtils.getUserId()); queryWrapperUser.orderByDesc("create_time"); if (null != request.getActivityId()) { queryWrapperUser.eq("activity_id", request.getActivityId()); } return wqPunchManagementMapper.selectPage(page, queryWrapperUser); } @Override public IPage<WqUser> getUserPageList(WqPunchManagementPageListRequest request) { QueryWrapper<WqPunchManagement> queryWrapper = new QueryWrapper(); queryWrapper.eq("activity_id", request.getActivityId()); queryWrapper.groupBy("user_id"); queryWrapper.select("user_id"); List<WqPunchManagement> wqPunchManagements = wqPunchManagementMapper.selectList(queryWrapper); if (CollectionUtils.isEmpty(wqPunchManagements)) { List<Integer> collect = wqPunchManagements.stream().map(WqPunchManagement::getUserId).collect(Collectors.toList()); Page<WqUser> page = new Page<>(request.getPageIndex(), request.getPageSize()); QueryWrapper<WqUser> queryUserWrapper = new QueryWrapper(); queryUserWrapper.in("id", collect); return wqUserMapper.selectPage(page, queryUserWrapper); } return null; } @Override public WqPunchManagement getById(WqPunchManagementDetailDelRequest request) { return wqPunchManagementMapper.selectById(request.getId()); } @Override public Boolean delById(WqPunchManagementDetailDelRequest request) { return wqPunchManagementMapper.deleteById(request.getId()) > 0; } @Override public WqPunchManagement selectOneByTime(QueryWrapper<WqPunchManagement> queryWrapper) { return wqPunchManagementMapper.selectOne(queryWrapper); } @Override public List<WqActivityRecruitment> getByUserActivity(WqPunchManagementPageListRequest request) { QueryWrapper<WqPunchManagement> queryWrapper = new QueryWrapper(); queryWrapper.eq("user_id", UserUtils.getUserId()); if (StringUtils.isEmpty(request.getSignUp())) { queryWrapper.eq("status", request.getSignUp()); } queryWrapper.groupBy("activity_id"); queryWrapper.select("activity_id"); List<WqPunchManagement> wqPunchManagements = wqPunchManagementMapper.selectList(queryWrapper); if (!CollectionUtils.isEmpty(wqPunchManagements)) { List<Integer> collect = wqPunchManagements.stream().map(WqPunchManagement::getActivityId).collect(Collectors.toList()); return wqActivityRecruitmentMapper.selectBatchIds(collect); } return null; } }
[ "505604843@qq.com" ]
505604843@qq.com
283a0ad4d6722d23c328c0613dc7b7bc3fda911c
4004a7c810caa2522d0ee3ab09f8bfe1d901df87
/src/main/java/sda/zadaniezespringa/construction_store/model/User.java
9bd20fb9b23ff836f99b31951ccba60325409227
[]
no_license
Adriodx/StoreProject
057ffc7bc969b25ce1cc15fe7a54785f05d024ab
a8ed74fdd6df948beec8dd7663926a0115c6ad32
refs/heads/master
2023-06-16T23:27:30.532991
2021-02-21T00:26:21
2021-02-21T00:26:21
383,746,410
0
0
null
null
null
null
UTF-8
Java
false
false
357
java
package sda.zadaniezespringa.construction_store.model; import javax.persistence.GeneratedValue; import javax.persistence.Id; public class User { @Id @GeneratedValue private Long clientId; private String email; private String firstName; private String surname; private String password; private String paymentMethod; }
[ "katarzyna_synowiec@wp.pl" ]
katarzyna_synowiec@wp.pl
9809600b63fbc7d63bb663962651ad358dcb075e
2fc7f6b10ea17130a117754a20ec249099693a23
/src/me/piatgory/game/controller/TurnController.java
f2ab3e3b24a95f48ead0838ff3ba5837487458e4
[]
no_license
GregoirePiat/Polytech-SpaceRPG
587b495b2edc0b29c57297ae469ef6348c78f58d
2a269e695dfb7b968618329585573f1e540a4153
refs/heads/master
2021-01-18T08:34:09.015253
2016-01-20T19:02:38
2016-01-20T19:02:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,897
java
package me.piatgory.game.controller; import me.grea.antoine.utils.Dice; import me.piatgory.game.Action.Action; import me.piatgory.game.Action.ActionUsable; import me.piatgory.game.core.CoreController; import me.piatgory.model.Entity.Monster; import me.piatgory.model.Item.consumable.Consumable; import me.piatgory.persistance.DataGame; import java.util.ArrayList; import java.util.List; /** * Created by Alexandre on 12/01/2016. */ public class TurnController extends CoreController { public List<Action> actions; private Monster monster; public TurnController(DataGame dataGame, Monster monster, List<Action> actions) { super(dataGame); this.actions = actions; this.monster = monster; } public void run(){ for (int i = 0; i <= Action.getMaxPriority(); i++){ if(!getCharacter().isDead()&& !monster.isDead()) runEventRandom(this.getEventByPriority(i)); } getCharacter().decreasingNbTurnBuffs(); monster.decreasingNbTurnBuffs(); } private List<Action> getEventByPriority(int i){ List<Action> actions = new ArrayList<Action>(); for (Action action :this.actions) { if(action.getPriority()==i) actions.add(action); } return actions; } private void runEventRandom(List<Action> actions){ while (actions.size() > 0 && !getCharacter().isDead()&& !monster.isDead() ){ int i = Dice.roll(actions.size()-1); Action action = actions.get(i); write(action.getSource().getName() + " : " + action.run()); if(action instanceof ActionUsable && ((ActionUsable)action).getUsable() instanceof Consumable){ getCharacter().removeFromInventory((Consumable)((ActionUsable)action).getUsable()); } actions.remove(action); } } }
[ "gory.alexandre02@gmail.com" ]
gory.alexandre02@gmail.com
6036514c79f54f489a272484781527f678fa1732
92689eb25786ae97abc6600870496042e8b07b7a
/spring-framework-3.2.16.RELEASE/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerExceptionResolver.java
dba6ae36e056152097e4a5a7aa182de9d13cead3
[ "Apache-2.0" ]
permissive
wangyingjie/spring3.2.6
27da141d3fd20b2e2cba20bea39bfdc33195805e
46bd3363fcca10d2327bd29d7cca56ede9f53c3e
refs/heads/master
2020-04-12T09:38:56.896199
2017-01-11T08:20:11
2017-01-11T08:20:11
51,057,084
1
0
null
null
null
null
UTF-8
Java
false
false
9,655
java
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.handler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.Ordered; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Set; /** * Abstract base class for {@link HandlerExceptionResolver} implementations. * * <p>Provides a set of mapped handlers that the resolver should map to, * and the {@link Ordered} implementation. * * @author Arjen Poutsma * @author Juergen Hoeller * @since 3.0 * * 模板类,具体的解析由子类处理 */ public abstract class AbstractHandlerExceptionResolver implements HandlerExceptionResolver, Ordered { private static final String HEADER_PRAGMA = "Pragma"; private static final String HEADER_EXPIRES = "Expires"; private static final String HEADER_CACHE_CONTROL = "Cache-Control"; /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); private int order = Ordered.LOWEST_PRECEDENCE; private Set<?> mappedHandlers; private Class[] mappedHandlerClasses; private Log warnLogger; private boolean preventResponseCaching = false; public void setOrder(int order) { this.order = order; } public int getOrder() { return this.order; } /** * Specify the set of handlers that this exception resolver should apply to. * The exception mappings and the default error view will only apply to the specified handlers. * <p>If no handlers and handler classes are set, the exception mappings and the default error * view will apply to all handlers. This means that a specified default error view will be used * as fallback for all exceptions; any further HandlerExceptionResolvers in the chain will be * ignored in this case. */ public void setMappedHandlers(Set<?> mappedHandlers) { this.mappedHandlers = mappedHandlers; } /** * Specify the set of classes that this exception resolver should apply to. * The exception mappings and the default error view will only apply to handlers of the * specified type; the specified types may be interfaces and superclasses of handlers as well. * <p>If no handlers and handler classes are set, the exception mappings and the default error * view will apply to all handlers. This means that a specified default error view will be used * as fallback for all exceptions; any further HandlerExceptionResolvers in the chain will be * ignored in this case. */ public void setMappedHandlerClasses(Class[] mappedHandlerClasses) { this.mappedHandlerClasses = mappedHandlerClasses; } /** * Set the log category for warn logging. The name will be passed to the underlying logger * implementation through Commons Logging, getting interpreted as log category according * to the logger's configuration. * <p>Default is no warn logging. Specify this setting to activate warn logging into a specific * category. Alternatively, override the {@link #logException} method for custom logging. * @see org.apache.commons.logging.LogFactory#getLog(String) * @see org.apache.log4j.Logger#getLogger(String) * @see java.util.logging.Logger#getLogger(String) */ public void setWarnLogCategory(String loggerName) { this.warnLogger = LogFactory.getLog(loggerName); } /** * Specify whether to prevent HTTP response caching for any view resolved * by this HandlerExceptionResolver. * <p>Default is "false". Switch this to "true" in order to automatically * generate HTTP response headers that suppress response caching. */ public void setPreventResponseCaching(boolean preventResponseCaching) { this.preventResponseCaching = preventResponseCaching; } /** * Checks whether this resolver is supposed to apply (i.e. the handler matches * in case of "mappedHandlers" having been specified), then delegates to the * {@link #doResolveException} template method. * * 解析异常 */ public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if (shouldApplyTo(request, handler)) { // Log exception, both at debug log level and at warn level, if desired. if (logger.isDebugEnabled()) { logger.debug("Resolving exception from handler [" + handler + "]: " + ex); } //打印日常 logException(ex, request); //设置response缓存的属性 prepareResponse(ex, response); //解析异常 return doResolveException(request, response, handler, ex); } else { return null; } } /** * Check whether this resolver is supposed to apply to the given handler. * <p>The default implementation checks against the specified mapped handlers * and handler classes, if any. * @param request current HTTP request * @param handler the executed handler, or {@code null} if none chosen * at the time of the exception (for example, if multipart resolution failed) * @return whether this resolved should proceed with resolving the exception * for the given request and handler * @see #setMappedHandlers * @see #setMappedHandlerClasses */ protected boolean shouldApplyTo(HttpServletRequest request, Object handler) { if (handler != null) { //包含处理的 handler if (this.mappedHandlers != null && this.mappedHandlers.contains(handler)) { return true; } if (this.mappedHandlerClasses != null) { for (Class handlerClass : this.mappedHandlerClasses) { if (handlerClass.isInstance(handler)) { return true; } } } } // Else only apply if there are no explicit handler mappings. return (this.mappedHandlers == null && this.mappedHandlerClasses == null); } /** * Log the given exception at warn level, provided that warn logging has been * activated through the {@link #setWarnLogCategory "warnLogCategory"} property. * <p>Calls {@link #buildLogMessage} in order to determine the concrete message to log. * Always passes the full exception to the logger. * @param ex the exception that got thrown during handler execution * @param request current HTTP request (useful for obtaining metadata) * @see #setWarnLogCategory * @see #buildLogMessage * @see org.apache.commons.logging.Log#warn(Object, Throwable) */ protected void logException(Exception ex, HttpServletRequest request) { if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) { this.warnLogger.warn(buildLogMessage(ex, request), ex); } } /** * Build a log message for the given exception, occured during processing the given request. * @param ex the exception that got thrown during handler execution * @param request current HTTP request (useful for obtaining metadata) * @return the log message to use */ protected String buildLogMessage(Exception ex, HttpServletRequest request) { return "Handler execution resulted in exception"; } /** * Prepare the response for the exceptional case. * <p>The default implementation prevents the response from being cached, * if the {@link #setPreventResponseCaching "preventResponseCaching"} property * has been set to "true". * @param ex the exception that got thrown during handler execution * @param response current HTTP response * @see #preventCaching */ protected void prepareResponse(Exception ex, HttpServletResponse response) { // 是否禁用 if (this.preventResponseCaching) { preventCaching(response); } } /** * Prevents the response from being cached, through setting corresponding * HTTP headers. See {@code http://www.mnot.net/cache_docs}. * @param response current HTTP response */ protected void preventCaching(HttpServletResponse response) { response.setHeader(HEADER_PRAGMA, "no-cache"); response.setDateHeader(HEADER_EXPIRES, 1L); response.setHeader(HEADER_CACHE_CONTROL, "no-cache"); response.addHeader(HEADER_CACHE_CONTROL, "no-store"); } /** * Actually resolve the given exception that got thrown during on handler execution, * returning a ModelAndView that represents a specific error page if appropriate. * <p>May be overridden in subclasses, in order to apply specific exception checks. * Note that this template method will be invoked <i>after</i> checking whether this * resolved applies ("mappedHandlers" etc), so an implementation may simply proceed * with its actual exception handling. * @param request current HTTP request * @param response current HTTP response * @param handler the executed handler, or {@code null} if none chosen at the time * of the exception (for example, if multipart resolution failed) * @param ex the exception that got thrown during handler execution * @return a corresponding ModelAndView to forward to, or {@code null} for default processing */ protected abstract ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex); }
[ "wangyingjie1@jd.com" ]
wangyingjie1@jd.com
1948d7618a564a357102042a21e775300c182a8b
95cfe2239c8fce0cec91d76e0a82f59a9efc4cb8
/sourceCode/CommonsLangMutGenerator/java.lang.NullPointerException/19453_lang/mut/EqualsBuilder.java
a41778afa19542f9ec652faec2ed8aa96c5167b9
[]
no_license
Djack1010/BUG_DB
28eff24aece45ed379b49893176383d9260501e7
a4b6e4460a664ce64a474bfd7da635aa7ff62041
refs/heads/master
2022-04-09T01:58:29.736794
2020-03-13T14:15:11
2020-03-13T14:15:11
141,260,015
0
1
null
null
null
null
UTF-8
Java
false
false
33,273
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.builder; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.tuple.Pair; /** * <p>Assists in implementing {@link Object#equals(Object)} methods.</p> * * <p> This class provides methods to build a good equals method for any * class. It follows rules laid out in * <a href="http://www.oracle.com/technetwork/java/effectivejava-136174.html">Effective Java</a> * , by Joshua Bloch. In particular the rule for comparing <code>doubles</code>, * <code>floats</code>, and arrays can be tricky. Also, making sure that * <code>equals()</code> and <code>hashCode()</code> are consistent can be * difficult.</p> * * <p>Two Objects that compare as equals must generate the same hash code, * but two Objects with the same hash code do not have to be equal.</p> * * <p>All relevant fields should be included in the calculation of equals. * Derived fields may be ignored. In particular, any field used in * generating a hash code must be used in the equals method, and vice * versa.</p> * * <p>Typical use for the code is as follows:</p> * <pre> * public boolean equals(Object obj) { * if (obj == null) { return false; } * if (obj == this) { return true; } * if (obj.getClass() != getClass()) { * return false; * } * MyClass rhs = (MyClass) obj; * return new EqualsBuilder() * .appendSuper(super.equals(obj)) * .append(field1, rhs.field1) * .append(field2, rhs.field2) * .append(field3, rhs.field3) * .isEquals(); * } * </pre> * * <p> Alternatively, there is a method that uses reflection to determine * the fields to test. Because these fields are usually private, the method, * <code>reflectionEquals</code>, uses <code>AccessibleObject.setAccessible</code> to * change the visibility of the fields. This will fail under a security * manager, unless the appropriate permissions are set up correctly. It is * also slower than testing explicitly. Non-primitive fields are compared using * <code>equals()</code>.</p> * * <p> A typical invocation for this method would look like:</p> * <pre> * public boolean equals(Object obj) { * return EqualsBuilder.reflectionEquals(this, obj); * } * </pre> * * @since 1.0 * @version $Id: EqualsBuilder.java 1623970 2014-09-10 11:32:53Z djones $ */ public class EqualsBuilder implements Builder<Boolean> { /** * <p> * A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops. * </p> * * @since 3.0 */ private static final ThreadLocal<Set<Pair<IDKey, IDKey>>> REGISTRY = new ThreadLocal<Set<Pair<IDKey, IDKey>>>(); /* * NOTE: we cannot store the actual objects in a HashSet, as that would use the very hashCode() * we are in the process of calculating. * * So we generate a one-to-one mapping from the original object to a new object. * * Now HashSet uses equals() to determine if two elements with the same hashcode really * are equal, so we also need to ensure that the replacement objects are only equal * if the original objects are identical. * * The original implementation (2.4 and before) used the System.indentityHashCode() * method - however this is not guaranteed to generate unique ids (e.g. LANG-459) * * We now use the IDKey helper class (adapted from org.apache.axis.utils.IDKey) * to disambiguate the duplicate ids. */ /** * <p> * Returns the registry of object pairs being traversed by the reflection * methods in the current thread. * </p> * * @return Set the registry of objects being traversed * @since 3.0 */ static Set<Pair<IDKey, IDKey>> getRegistry() { return REGISTRY.get(); } /** * <p> * Converters value pair into a register pair. * </p> * * @param lhs <code>this</code> object * @param rhs the other object * * @return the pair */ static Pair<IDKey, IDKey> getRegisterPair(final Object lhs, final Object rhs) { final IDKey left = new IDKey(lhs); final IDKey right = new IDKey(rhs); return Pair.of(left, right); } /** * <p> * Returns <code>true</code> if the registry contains the given object pair. * Used by the reflection methods to avoid infinite loops. * Objects might be swapped therefore a check is needed if the object pair * is registered in given or swapped order. * </p> * * @param lhs <code>this</code> object to lookup in registry * @param rhs the other object to lookup on registry * @return boolean <code>true</code> if the registry contains the given object. * @since 3.0 */ static boolean isRegistered(final Object lhs, final Object rhs) { final Set<Pair<IDKey, IDKey>> registry = getRegistry(); final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs); final Pair<IDKey, IDKey> swappedPair = Pair.of(pair.getLeft(), pair.getRight()); return registry != null && (registry.contains(pair) || registry.contains(swappedPair)); } /** * <p> * Registers the given object pair. * Used by the reflection methods to avoid infinite loops. * </p> * * @param lhs <code>this</code> object to register * @param rhs the other object to register */ static void register(final Object lhs, final Object rhs) { synchronized (EqualsBuilder.class) { if (getRegistry() == null) { REGISTRY.set(new HashSet<Pair<IDKey, IDKey>>()); } } final Set<Pair<IDKey, IDKey>> registry = getRegistry(); final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs); registry.add(pair); } /** * <p> * Unregisters the given object pair. * </p> * * <p> * Used by the reflection methods to avoid infinite loops. * * @param lhs <code>this</code> object to unregister * @param rhs the other object to unregister * @since 3.0 */ static void unregister(final Object lhs, final Object rhs) { Set<Pair<IDKey, IDKey>> registry = getRegistry(); if (registry != null) { final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs); registry.remove(pair); synchronized (EqualsBuilder.class) { //read again registry = getRegistry(); if (registry != null && registry.isEmpty()) { REGISTRY.remove(); } } } } /** * If the fields tested are equals. * The default value is <code>true</code>. */ private boolean isEquals = true; /** * <p>Constructor for EqualsBuilder.</p> * * <p>Starts off assuming that equals is <code>true</code>.</p> * @see Object#equals(Object) */ public EqualsBuilder() { // do nothing for now. } //------------------------------------------------------------------------- /** * <p>This method uses reflection to determine if the two <code>Object</code>s * are equal.</p> * * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly. Non-primitive fields are compared using * <code>equals()</code>.</p> * * <p>Transient members will be not be tested, as they are likely derived * fields, and not part of the value of the Object.</p> * * <p>Static fields will not be tested. Superclass fields will be included.</p> * * @param lhs <code>this</code> object * @param rhs the other object * @param excludeFields Collection of String field names to exclude from testing * @return <code>true</code> if the two Objects have tested equals. */ public static boolean reflectionEquals(final Object lhs, final Object rhs, final Collection<String> excludeFields) { return reflectionEquals(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields)); } /** * <p>This method uses reflection to determine if the two <code>Object</code>s * are equal.</p> * * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly. Non-primitive fields are compared using * <code>equals()</code>.</p> * * <p>Transient members will be not be tested, as they are likely derived * fields, and not part of the value of the Object.</p> * * <p>Static fields will not be tested. Superclass fields will be included.</p> * * @param lhs <code>this</code> object * @param rhs the other object * @param excludeFields array of field names to exclude from testing * @return <code>true</code> if the two Objects have tested equals. */ public static boolean reflectionEquals(final Object lhs, final Object rhs, final String... excludeFields) { return reflectionEquals(lhs, rhs, false, null, excludeFields); } /** * <p>This method uses reflection to determine if the two <code>Object</code>s * are equal.</p> * * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly. Non-primitive fields are compared using * <code>equals()</code>.</p> * * <p>If the TestTransients parameter is set to <code>true</code>, transient * members will be tested, otherwise they are ignored, as they are likely * derived fields, and not part of the value of the <code>Object</code>.</p> * * <p>Static fields will not be tested. Superclass fields will be included.</p> * * @param lhs <code>this</code> object * @param rhs the other object * @param testTransients whether to include transient fields * @return <code>true</code> if the two Objects have tested equals. */ public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients) { return reflectionEquals(lhs, rhs, testTransients, null); } /** * <p>This method uses reflection to determine if the two <code>Object</code>s * are equal.</p> * * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly. Non-primitive fields are compared using * <code>equals()</code>.</p> * * <p>If the testTransients parameter is set to <code>true</code>, transient * members will be tested, otherwise they are ignored, as they are likely * derived fields, and not part of the value of the <code>Object</code>.</p> * * <p>Static fields will not be included. Superclass fields will be appended * up to and including the specified superclass. A null superclass is treated * as java.lang.Object.</p> * * @param lhs <code>this</code> object * @param rhs the other object * @param testTransients whether to include transient fields * @param reflectUpToClass the superclass to reflect up to (inclusive), * may be <code>null</code> * @param excludeFields array of field names to exclude from testing * @return <code>true</code> if the two Objects have tested equals. * @since 2.0 */ public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients, final Class<?> reflectUpToClass, final String... excludeFields) { if (lhs == rhs) { return true; } if (lhs == null || rhs == null) { return false; } // Find the leaf class since there may be transients in the leaf // class or in classes between the leaf and root. // If we are not testing transients or a subclass has no ivars, // then a subclass can test equals to a superclass. final Class<?> lhsClass = lhs.getClass(); final Class<?> rhsClass = rhs.getClass(); Class<?> testClass; if (lhsClass.isInstance(rhs)) { testClass = lhsClass; if (!rhsClass.isInstance(lhs)) { // rhsClass is a subclass of lhsClass testClass = rhsClass; } } else if (rhsClass.isInstance(lhs)) { testClass = rhsClass; if (!lhsClass.isInstance(rhs)) { // lhsClass is a subclass of rhsClass testClass = lhsClass; } } else { // The two classes are not related. return false; } final EqualsBuilder equalsBuilder = new EqualsBuilder(); try { if (testClass.isArray()) { equalsBuilder.append(lhs, rhs); } else { reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields); while (testClass.getSuperclass() != null && testClass != reflectUpToClass) { testClass = testClass.getSuperclass(); reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields); } } } catch (final IllegalArgumentException e) { // In this case, we tried to test a subclass vs. a superclass and // the subclass has ivars or the ivars are transient and // we are testing transients. // If a subclass has ivars that we are trying to test them, we get an // exception and we know that the objects are not equal. return false; } return equalsBuilder.isEquals(); } /** * <p>Appends the fields and values defined by the given object of the * given Class.</p> * * @param lhs the left hand object * @param rhs the right hand object * @param clazz the class to append details of * @param builder the builder to append to * @param useTransients whether to test transient fields * @param excludeFields array of field names to exclude from testing */ private static void reflectionAppend( final Object lhs, final Object rhs, final Class<?> clazz, final EqualsBuilder builder, final boolean useTransients, final String[] excludeFields) { if (isRegistered(lhs, rhs)) { return; } try { register(lhs, rhs); final Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length && builder.isEquals; i++) { final Field f = fields[i]; if (!ArrayUtils.contains(excludeFields, f.getName()) && (f.getName().indexOf('$') == -1) && (useTransients || !Modifier.isTransient(f.getModifiers())) && (!Modifier.isStatic(f.getModifiers()))) { try { builder.append(f.get(lhs), f.get(rhs)); } catch (final IllegalAccessException e) { //this can't happen. Would get a Security exception instead //throw a runtime exception in case the impossible happens. throw new InternalError("Unexpected IllegalAccessException"); } } } } finally { unregister(lhs, rhs); } } //------------------------------------------------------------------------- /** * <p>Adds the result of <code>super.equals()</code> to this builder.</p> * * @param superEquals the result of calling <code>super.equals()</code> * @return EqualsBuilder - used to chain calls. * @since 2.0 */ public EqualsBuilder appendSuper(final boolean superEquals) { if (isEquals == false) { return this; } isEquals = superEquals; return this; } //------------------------------------------------------------------------- /** * <p>Test if two <code>Object</code>s are equal using their * <code>equals</code> method.</p> * * @param lhs the left hand object * @param rhs the right hand object * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final Object lhs, final Object rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } final Class<?> lhsClass = lhs.getClass(); if (!lhsClass.isArray()) { // The simple case, not an array, just test the element isEquals = lhs.equals(rhs); } else if (lhs.getClass() != rhs.getClass()) { // Here when we compare different dimensions, for example: a boolean[][] to a boolean[] this.setEquals(false); } // 'Switch' on type of array, to dispatch to the correct handler // This handles multi dimensional arrays of the same depth else if (lhs instanceof long[]) { append((long[]) lhs, (long[]) rhs); } else if (lhs instanceof int[]) { append((int[]) lhs, (int[]) rhs); } else if (lhs instanceof short[]) { append((short[]) lhs, (short[]) rhs); } else if (lhs instanceof char[]) { append((char[]) lhs, (char[]) rhs); } else if (lhs instanceof byte[]) { append((byte[]) lhs, (byte[]) rhs); } else if (lhs instanceof double[]) { append((double[]) lhs, (double[]) rhs); } else if (lhs instanceof float[]) { append((float[]) lhs, (float[]) rhs); } else if (lhs instanceof boolean[]) { append((boolean[]) lhs, (boolean[]) rhs); } else { // Not an array of primitives append((Object[]) lhs, (Object[]) rhs); } return this; } /** * <p> * Test if two <code>long</code> s are equal. * </p> * * @param lhs * the left hand <code>long</code> * @param rhs * the right hand <code>long</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final long lhs, final long rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** * <p>Test if two <code>int</code>s are equal.</p> * * @param lhs the left hand <code>int</code> * @param rhs the right hand <code>int</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final int lhs, final int rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** * <p>Test if two <code>short</code>s are equal.</p> * * @param lhs the left hand <code>short</code> * @param rhs the right hand <code>short</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final short lhs, final short rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** * <p>Test if two <code>char</code>s are equal.</p> * * @param lhs the left hand <code>char</code> * @param rhs the right hand <code>char</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final char lhs, final char rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** * <p>Test if two <code>byte</code>s are equal.</p> * * @param lhs the left hand <code>byte</code> * @param rhs the right hand <code>byte</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final byte lhs, final byte rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** * <p>Test if two <code>double</code>s are equal by testing that the * pattern of bits returned by <code>doubleToLong</code> are equal.</p> * * <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p> * * <p>It is compatible with the hash code generated by * <code>HashCodeBuilder</code>.</p> * * @param lhs the left hand <code>double</code> * @param rhs the right hand <code>double</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final double lhs, final double rhs) { if (isEquals == false) { return this; } return append(Double.doubleToLongBits(lhs), Double.doubleToLongBits(rhs)); } /** * <p>Test if two <code>float</code>s are equal byt testing that the * pattern of bits returned by doubleToLong are equal.</p> * * <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p> * * <p>It is compatible with the hash code generated by * <code>HashCodeBuilder</code>.</p> * * @param lhs the left hand <code>float</code> * @param rhs the right hand <code>float</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final float lhs, final float rhs) { if (isEquals == false) { return this; } return append(Float.floatToIntBits(lhs), Float.floatToIntBits(rhs)); } /** * <p>Test if two <code>booleans</code>s are equal.</p> * * @param lhs the left hand <code>boolean</code> * @param rhs the right hand <code>boolean</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final boolean lhs, final boolean rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** * <p>Performs a deep comparison of two <code>Object</code> arrays.</p> * * <p>This also will be called for the top level of * multi-dimensional, ragged, and multi-typed arrays.</p> * * @param lhs the left hand <code>Object[]</code> * @param rhs the right hand <code>Object[]</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final Object[] lhs, final Object[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** * <p>Deep comparison of array of <code>long</code>. Length and all * values are compared.</p> * * <p>The method {@link #append(long, long)} is used.</p> * * @param lhs the left hand <code>long[]</code> * @param rhs the right hand <code>long[]</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final long[] lhs, final long[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** * <p>Deep comparison of array of <code>int</code>. Length and all * values are compared.</p> * * <p>The method {@link #append(int, int)} is used.</p> * * @param lhs the left hand <code>int[]</code> * @param rhs the right hand <code>int[]</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final int[] lhs, final int[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** * <p>Deep comparison of array of <code>short</code>. Length and all * values are compared.</p> * * <p>The method {@link #append(short, short)} is used.</p> * * @param lhs the left hand <code>short[]</code> * @param rhs the right hand <code>short[]</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final short[] lhs, final short[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** * <p>Deep comparison of array of <code>char</code>. Length and all * values are compared.</p> * * <p>The method {@link #append(char, char)} is used.</p> * * @param lhs the left hand <code>char[]</code> * @param rhs the right hand <code>char[]</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final char[] lhs, final char[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** * <p>Deep comparison of array of <code>byte</code>. Length and all * values are compared.</p> * * <p>The method {@link #append(byte, byte)} is used.</p> * * @param lhs the left hand <code>byte[]</code> * @param rhs the right hand <code>byte[]</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final byte[] lhs, final byte[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** * <p>Deep comparison of array of <code>double</code>. Length and all * values are compared.</p> * * <p>The method {@link #append(double, double)} is used.</p> * * @param lhs the left hand <code>double[]</code> * @param rhs the right hand <code>double[]</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final double[] lhs, final double[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** * <p>Deep comparison of array of <code>float</code>. Length and all * values are compared.</p> * * <p>The method {@link #append(float, float)} is used.</p> * * @param lhs the left hand <code>float[]</code> * @param rhs the right hand <code>float[]</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final float[] lhs, final float[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** * <p>Deep comparison of array of <code>boolean</code>. Length and all * values are compared.</p> * * <p>The method {@link #append(boolean, boolean)} is used.</p> * * @param lhs the left hand <code>boolean[]</code> * @param rhs the right hand <code>boolean[]</code> * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(final boolean[] lhs, final boolean[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || false) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** * <p>Returns <code>true</code> if the fields that have been checked * are all equal.</p> * * @return boolean */ public boolean isEquals() { return this.isEquals; } /** * <p>Returns <code>true</code> if the fields that have been checked * are all equal.</p> * * @return <code>true</code> if all of the fields that have been checked * are equal, <code>false</code> otherwise. * * @since 3.0 */ public Boolean build() { return Boolean.valueOf(isEquals()); } /** * Sets the <code>isEquals</code> value. * * @param isEquals The value to set. * @since 2.1 */ protected void setEquals(final boolean isEquals) { this.isEquals = isEquals; } /** * Reset the EqualsBuilder so you can use the same object again * @since 2.5 */ public void reset() { this.isEquals = true; } }
[ "giachi.iada@gmail.com" ]
giachi.iada@gmail.com
01840ce7e2dfb5f2701ba45738beb6773439692d
8d16442c9016569d3da98a2670b7051bcb246862
/src/test/java/test/com/www/course/c02/AnnotationTest.java
1de856adb41c85db17ace399e34b79e0b5752c4a
[]
no_license
boilfish/SpringLearn
ddbf02ea5be375d0fa479355420683354ac77ade
2c0844c8c9117dc40c915d89e933d9c73f2976a9
refs/heads/master
2020-04-05T12:17:10.036165
2018-11-17T06:26:49
2018-11-17T06:26:49
156,863,706
0
0
null
null
null
null
UTF-8
Java
false
false
548
java
package test.com.www.course.c02; import com.www.course.c02.annotation.ClazzAnnotation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AnnotationTest { public static void main(String [] args){ ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config-annotation.xml"); ClazzAnnotation ca = (ClazzAnnotation) ac.getBean("ClazzAnnotation"); ca.getMaster(); System.out.println(ca.toString()); } }
[ "vs2012@live.com" ]
vs2012@live.com
6abc707a4450ed8a10c7f97a82a30cfc4ef4ad29
7b82d70ba5fef677d83879dfeab859d17f4809aa
/tmp/sys/ws/src/main/java/com/coldfeng/oauth/common/UserAccount.java
2e573d9a1fec0eaa325795386265d4fe48ac176a
[]
no_license
apollowesley/jun_test
fb962a28b6384c4097c7a8087a53878188db2ebc
c7a4600c3f0e1b045280eaf3464b64e908d2f0a2
refs/heads/main
2022-12-30T20:47:36.637165
2020-10-13T18:10:46
2020-10-13T18:10:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
974
java
/** * Copyright (C) 2011 Talend Inc. - www.talend.com */ package com.coldfeng.oauth.common; public class UserAccount { private String name; private String password; private String accountAlias; private Calendar calendar = new Calendar(); public UserAccount(String name, String password) { this.name = name; this.password = password; } public UserAccount(String name, String password, String alias) { this.name = name; this.password = password; if (alias != null) { this.accountAlias = alias; } else { this.accountAlias = name; } } public String getName() { return name; } public String getPassword() { return password; } public Calendar getCalendar() { return calendar; } public String getAccountAlias() { return accountAlias; } public void setAccountAlias(String accountAlias) { this.accountAlias = accountAlias; } }
[ "wujun728@hotmail.com" ]
wujun728@hotmail.com