blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
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
689M
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
131 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
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
4ec44849455d7379f345cd926e24dd0cd04318b9
a37e582c3df387d469d47931a0090a8f38010ac2
/app/src/main/java/com/example/myapplication/helper/SessionManager.java
9ed80f2a84005784cd003c47c46686998f92f0a7
[]
no_license
sinungaji/MyApplication
9c494631486df752be085860ff930f5be15a7fae
fe40703d8c7000031e080df7405efaf7eba42120
refs/heads/master
2023-01-24T16:10:30.822157
2020-11-23T22:37:40
2020-11-23T22:37:40
309,934,143
0
0
null
null
null
null
UTF-8
Java
false
false
2,276
java
package com.example.myapplication.helper; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import com.example.myapplication.Login; import java.util.HashMap; public class SessionManager { private SharedPreferences pref; private SharedPreferences.Editor editor; private Context _context; private static final String PREF_NAME = "sinung"; private static final String IS_LOGIN = "IsLoggedIn"; public static final String KEY_ID_ANGGOTA = "name"; public static final String KEY_ABSEN_ANGGOTA = "0"; // Constructor @SuppressLint("CommitPrefEdits") public SessionManager(Context context){ this._context = context; int PRIVATE_MODE = 0; pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); editor = pref.edit(); } /** * Create login session * */ public void createLoginSession(String id_anggota, String absen){ // Storing login value as TRUE editor.putBoolean(IS_LOGIN, true); editor.putString(KEY_ID_ANGGOTA, id_anggota); editor.putString(KEY_ABSEN_ANGGOTA, absen); editor.commit(); } public void checkLogin(){ if(!this.isLoggedIn()){ Intent i = new Intent(_context, Login.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); _context.startActivity(i); } } /** * Get stored session data * */ public HashMap<String, String> getUserDetails(){ HashMap<String, String> user = new HashMap<>(); user.put(KEY_ID_ANGGOTA, pref.getString(KEY_ID_ANGGOTA, null)); user.put(KEY_ABSEN_ANGGOTA, pref.getString(KEY_ABSEN_ANGGOTA, null)); return user; } /** * Clear session details * */ public void logoutUser(){ editor.clear(); editor.commit(); Intent i = new Intent(_context, Login.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); _context.startActivity(i); } public boolean isLoggedIn(){ return pref.getBoolean(IS_LOGIN, false); } }
[ "sinung.purnama@ti.ukdw.ac.id" ]
sinung.purnama@ti.ukdw.ac.id
004f94fa3d5c7dcfcc99c6373b407e5c81901640
7a42579f1ea96d2c6117a2933a3697d4a376a191
/app/src/androidTest/java/com/yandex/academy/lesson10/ExampleInstrumentedTest.java
dec8bfd16e229db059cc59d0997307567202626d
[]
no_license
satsakul/Lesson10
02292ea00bc62622f7be89f80de20da57b112ca4
c5719c7e0e02acca960fcc627e0824192e19bec4
refs/heads/master
2021-01-20T17:39:44.621260
2017-05-10T15:51:04
2017-05-10T15:51:04
90,881,846
1
0
null
null
null
null
UTF-8
Java
false
false
758
java
package com.yandex.academy.lesson10; 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.*; /** * Instrumentation 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() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.yandex.academy.lesson10", appContext.getPackageName()); } }
[ "satsakul@yandex-team.ru" ]
satsakul@yandex-team.ru
be0d4150e5c0e9413c9c7469d26466fb33192026
cd744f6afffca9163e5d29a96156ede6fccb5b6d
/src/edu/iastate/anthill/indus/gui/panel/TypePanelGUI.java
0519cfe068b77dd40a0b1272c10749df209895ee
[]
no_license
baojie/indus
cf2110605bdf2ffa46434b57552474eaf6065c01
43b7b68e83134901b3c3845e207fa43fed400af4
refs/heads/master
2020-06-01T09:10:58.534877
2013-03-06T20:04:14
2013-03-06T20:04:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,684
java
package edu.iastate.anthill.indus.gui.panel; import java.awt.BorderLayout; import java.awt.Component; import java.awt.FlowLayout; import java.util.HashMap; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import edu.iastate.anthill.indus.IndusConstants; import edu.iastate.utils.Debug; public abstract class TypePanelGUI extends IndusPane { public TypePanelGUI() { super(); //Debug.trace(this, "DataTypePanelGUI:DataTypePanelGUI"); try { jbInit(); } catch (Exception ex) { Debug.trace(this, "haha , a bug"); ex.printStackTrace(); } } JSplitPane jSplitPane1 = new JSplitPane(); JPanel leftPanel = new JPanel(); JPanel rightPanel = new JPanel(); DefaultListModel model = new DefaultListModel(); public JList listAllTypes = new JList(model); JButton btnNewType = new JButton(); JLabel labelSelectedType = new JLabel(); JPanel treePanel = new JPanel(); BorderLayout borderLayout1 = new BorderLayout(); JPanel buttonPanel = new JPanel(); JButton btnSave = new JButton(); JScrollPane jScrollPaneTree = new JScrollPane(); BorderLayout borderLayout2 = new BorderLayout(); FlowLayout flowLayout1 = new FlowLayout(); JButton btnExportXML = new JButton(); JButton btnImportText = new JButton("Import(Text)"); JButton btnImportXML = new JButton("Import(XML)"); JButton btnExportText = new JButton(); JButton btnReload = new JButton("Reload"); void jbInit() throws Exception { //Debug.trace(this, "DataTypePanelGUI:jbInit"); this.setLayout(new BorderLayout()); // left panel leftPanel.setLayout(new BorderLayout()); listAllTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listAllTypes.setCellRenderer(new TypeListCellRenderer()); JScrollPane jp = new JScrollPane(); jp.setBorder(BorderFactory.createTitledBorder("Registered types")); jp.getViewport().add(listAllTypes); btnSave.setText("Save Type"); leftPanel.add(jp, BorderLayout.CENTER); // right panel rightPanel.setLayout(borderLayout1); // tree panel treePanel.setLayout(borderLayout2); treePanel.add(jScrollPaneTree, BorderLayout.CENTER); rightPanel.add(treePanel, BorderLayout.CENTER); // button btnNewType.setText("New Type"); btnExportXML.setText("Export(XML)"); btnExportText.setText("Export(Text)"); buttonPanel.add(btnReload); buttonPanel.add(btnSave); buttonPanel.add(btnNewType); buttonPanel.add(btnExportXML, null); buttonPanel.add(btnExportText, null); buttonPanel.add(btnImportXML, null); buttonPanel.add(btnImportText, null); buttonPanel.setLayout(flowLayout1); rightPanel.add(buttonPanel, BorderLayout.SOUTH); // the label labelSelectedType.setText(""); rightPanel.add(labelSelectedType, BorderLayout.NORTH); // split panel jSplitPane1.setOneTouchExpandable(true); jSplitPane1.add(leftPanel, JSplitPane.LEFT); jSplitPane1.add(rightPanel, JSplitPane.RIGHT); jSplitPane1.setDividerLocation(0.3); this.add(jSplitPane1, BorderLayout.CENTER); } /** * Add icon to list based on super type * @author Jie Bao * @since 1.0 2004-10-15 */ class TypeListCellRenderer extends DefaultListCellRenderer { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component retValue = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); ImageIcon icon = (ImageIcon) typeIcon.get(value); if(icon == null) icon = IndusConstants.iconDatatype; setIcon(icon); return retValue; } } HashMap<Object, ImageIcon> typeIcon = new HashMap<Object, ImageIcon>(); }
[ "baojie" ]
baojie
d50487440d524ea946c8af47986f5d7082af240d
7daea517406d555993e9214ff30a1d89671a5b1a
/hrms/src/main/java/kodlamaio/hrms/dataAccess/abstracts/SystemEmployeeConfirmDao.java
edc68337851e00029ee4d61d78e5a280b2784bb9
[]
no_license
acarbey02400/Java
0ee2ce980644600b09296f21bfeaea7f33c8cedf
66412d06e67297bf1d8882a5c7719f747731a2fc
refs/heads/main
2023-08-15T16:21:46.660329
2021-10-21T15:19:43
2021-10-21T15:19:43
366,969,420
7
0
null
null
null
null
UTF-8
Java
false
false
276
java
package kodlamaio.hrms.dataAccess.abstracts; import org.springframework.data.jpa.repository.JpaRepository; import kodlamaio.hrms.entities.concretes.SystemEmployeeConfirm; public interface SystemEmployeeConfirmDao extends JpaRepository<SystemEmployeeConfirm, Integer> { }
[ "acarwoody01@gmail.com" ]
acarwoody01@gmail.com
c61da7ce58b70eac21a634a2a7b82f59e1ca212d
517b7f6e908f083930ce3d491db8b8cfea87fd1e
/mantis-tests/src/test/java/ru/stqa/island/mantis/tests/ChangePasswordTests.java
de8bafb89342ef0d54705d7da34f59df700be9ea
[ "MIT" ]
permissive
ekhanina/java_like_an_island
ff45fe8554085bf2775d6538baddce1ce9d1148e
555b6f90cd21fe100f60b2ef28228f59ac78e4a5
refs/heads/master
2020-03-22T17:56:41.052923
2018-09-13T16:24:10
2018-09-13T16:24:10
140,425,709
0
0
null
null
null
null
UTF-8
Java
false
false
1,830
java
package ru.stqa.island.mantis.tests; import org.testng.annotations.Test; import ru.stqa.island.mantis.appmanager.DbHelper; import ru.stqa.island.mantis.appmanager.HttpSession; import ru.stqa.island.mantis.model.MailMessage; import ru.stqa.island.mantis.model.UserData; import javax.mail.MessagingException; import java.io.IOException; import java.util.List; import java.util.Random; import static org.testng.Assert.assertTrue; public class ChangePasswordTests extends TestBase { @Test public void changePassword() throws IOException, MessagingException { List<UserData> users = new DbHelper().users(); int index = 0; do { index = (int) new Random().nextInt(users.size()); } while (users.get(index).getUser().equals("administrator")); String email = users.get(index).getEmail(); String username = users.get(index).getUser(); String password = "password"; List<MailMessage> mailMessagesBefore = app.james().waitForMail(username,password,60000); app.changepassword().start("administrator","root"); app.changepassword().clickManageUsers(); app.changepassword().clickUser(username); app.changepassword().resetPassword(); List<MailMessage> mailMessagesAfter; do { mailMessagesAfter = app.james().waitForMail(username, password, 60000); } while (mailMessagesBefore.size()==mailMessagesAfter.size()); String passchangeLink = app.changepassword().findChangePasswordLink(mailMessagesAfter, email); String newPassword = "password1"; app.changepassword().finish(passchangeLink,newPassword); HttpSession session = app.newSession(); assertTrue(session.login(username, newPassword)); assertTrue(session.isLoggedInAs(username)); } }
[ "urbangirl@mail.ru" ]
urbangirl@mail.ru
99c564fbe996e4e7dc7eef0bec409d8f6554b2ab
f0d25d83176909b18b9989e6fe34c414590c3599
/app/src/main/java/com/google/firebase/storage/zzab.java
aec0f063a3a0d1d54ffee5a44f77767d3c6a02a8
[]
no_license
lycfr/lq
e8dd702263e6565486bea92f05cd93e45ef8defc
123914e7c0d45956184dc908e87f63870e46aa2e
refs/heads/master
2022-04-07T18:16:31.660038
2020-02-23T03:09:18
2020-02-23T03:09:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,195
java
package com.google.firebase.storage; import android.os.RemoteException; import android.support.annotation.NonNull; import android.util.Log; import com.google.android.gms.internal.abu; import com.google.android.gms.internal.acf; import com.google.android.gms.tasks.TaskCompletionSource; import com.google.firebase.storage.StorageMetadata; import org.json.JSONException; final class zzab implements Runnable { private final StorageReference zzcoe; private final TaskCompletionSource<StorageMetadata> zzcof; private abu zzcog; private StorageMetadata zzcor = null; private final StorageMetadata zzcpJ; public zzab(@NonNull StorageReference storageReference, @NonNull TaskCompletionSource<StorageMetadata> taskCompletionSource, @NonNull StorageMetadata storageMetadata) { this.zzcoe = storageReference; this.zzcof = taskCompletionSource; this.zzcpJ = storageMetadata; this.zzcog = new abu(this.zzcoe.getStorage().getApp(), this.zzcoe.getStorage().getMaxOperationRetryTimeMillis()); } public final void run() { try { acf zza = this.zzcoe.zzKO().zza(this.zzcoe.zzKP(), this.zzcpJ.zzKN()); this.zzcog.zza(zza, true); if (zza.zzLk()) { try { this.zzcor = new StorageMetadata.Builder(zza.zzLn(), this.zzcoe).build(); } catch (RemoteException | JSONException e) { String valueOf = String.valueOf(zza.zzLi()); Log.e("UpdateMetadataTask", valueOf.length() != 0 ? "Unable to parse a valid JSON object from resulting metadata:".concat(valueOf) : new String("Unable to parse a valid JSON object from resulting metadata:"), e); this.zzcof.setException(StorageException.fromException(e)); return; } } if (this.zzcof != null) { zza.zza(this.zzcof, this.zzcor); } } catch (RemoteException | JSONException e2) { Log.e("UpdateMetadataTask", "Unable to create the request from metadata.", e2); this.zzcof.setException(StorageException.fromException(e2)); } } }
[ "quyenlm.vn@gmail.com" ]
quyenlm.vn@gmail.com
20fc39925a5598b93b0605b7805c02185474a5da
e01987d25063d369877d72c18be948f4f6c682f4
/app/src/main/java/com/shangeeth/animationtypes/ui/ControllerFragment.java
c822b52ef8fd1eb35ab46c3a01ad3be454c47814
[]
no_license
shangeethsivan/RandomAnimationsAndroid
550f51857b7f5037e957d0775b2cd960e5c3153b
d1a56a7bb43ae9a3169016815d03cae02c051f08
refs/heads/master
2021-06-16T15:30:59.414278
2017-04-26T05:08:39
2017-04-26T05:08:39
89,440,245
1
0
null
null
null
null
UTF-8
Java
false
false
1,831
java
package com.shangeeth.animationtypes.ui; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.GridView; import com.shangeeth.animationtypes.R; import com.shangeeth.animationtypes.adapters.CustomGridAdapter; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class ControllerFragment extends Fragment { Context mContext; GridView mGridView; public ControllerFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View lView = inflater.inflate(R.layout.fragment_controller,container,false); mGridView = (GridView) lView.findViewById(R.id.grid_view); mGridView.setAdapter(new CustomGridAdapter(mContext,getResources().getStringArray(R.array.animation_types))); mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { LocalBroadcastManager.getInstance(mContext) .sendBroadcast(new Intent().setAction(DisplayFragment.CUSTOM_INTENT) .putExtra(getString(R.string.animation_type),position)); } }); return lView; } @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } }
[ "shivthepro@github.com" ]
shivthepro@github.com
3e77fba380c7883f4ce2d2420f20132f3db24124
3ea2b82f5592f20a4775341a931f9565451d42c0
/app/src/main/java/edu/galileo/android/androidchat/login/events/LoginEvent.java
add6d10749c3dd799a08b0d29e04ef12038655e6
[]
no_license
Hiro6634/AndroidChat.old
d45ffa7e62cd270e9311e5e73fa38473bf802785
5714d79be86c0c867e73bdfb9fe355ad3e4117ca
refs/heads/master
2021-06-01T00:17:33.527427
2016-07-06T16:30:56
2016-07-06T16:30:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
768
java
package edu.galileo.android.androidchat.login.events; /** * Created by Hiro on 22/06/2016. */ public class LoginEvent { public final static int onSignInError = 0; public final static int onSignUpError = 1; public final static int onSignInSuccess = 2; public final static int onSignUpSuccess = 3; public final static int onFailedToRecoverSession = 4; private int eventType; private String errorMessage; public int getEventType() { return eventType; } public void setEventType(int eventType) { this.eventType = eventType; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
[ "hiro.suyama@gmail.com" ]
hiro.suyama@gmail.com
b117e860038d531e3139d9c08c994368a89a5f66
982de77343a55c5fc3f26007bc84472fd4654479
/src/main/java/com/fuyong/imwebtest/pojo/Invoice.java
efc6fcdaa91afb32dba308acef317b0e9d903cdb
[]
no_license
fuyong520z/im-web-test1
911d8790b93c5645efaacdf42c3a8545085857bd
f7e2c4e2bddd841a47288cd2fede30aa69bf38ab
refs/heads/master
2022-06-28T03:21:29.296401
2019-10-15T07:10:18
2019-10-15T07:10:18
215,197,388
0
0
null
2022-06-17T02:35:53
2019-10-15T03:25:04
Java
GB18030
Java
false
false
2,012
java
package com.fuyong.imwebtest.pojo; import org.springframework.stereotype.Controller; import java.math.BigDecimal; @Controller public class Invoice { private String invoiceCode; //发票代码 private String invoiceDate; //开票时间 private String purchaserName; //购方名称 private String purchaserRegisterNum; //购方纳税人识别号 private BigDecimal amountInFiguers; //价税合计 private String sellerName; //售方名称 private String sellerRegisterNum; //售方纳税人识别号 public String getInvoiceCode() { return invoiceCode; } public void setInvoiceCode(String invoiceCode) { this.invoiceCode = invoiceCode; } public String getInvoiceDate() { return invoiceDate; } public void setInvoiceDate(String invoiceDate) { this.invoiceDate = invoiceDate; } public String getPurchaserName() { return purchaserName; } public void setPurchaserName(String purchaserName) { this.purchaserName = purchaserName; } public String getPurchaserRegisterNum() { return purchaserRegisterNum; } public void setPurchaserRegisterNum(String purchaserRegisterNum) { this.purchaserRegisterNum = purchaserRegisterNum; } public BigDecimal getAmountInFiguers() { return amountInFiguers; } public void setAmountInFiguers(BigDecimal amountInFiguers) { this.amountInFiguers = amountInFiguers; } public String getSellerName() { return sellerName; } public void setSellerName(String sellerName) { this.sellerName = sellerName; } public String getSellerRegisterNum() { return sellerRegisterNum; } public void setSellerRegisterNum(String sellerRegisterNum) { this.sellerRegisterNum = sellerRegisterNum; } @Override public String toString() { return "Invoice [invoiceCode=" + invoiceCode + ", invoiceDate=" + invoiceDate + ", purchaserName=" + purchaserName + ", purchaserRegisterNum=" + purchaserRegisterNum + ", amountInFiguers=" + amountInFiguers + ", sellerName=" + sellerName + ", sellerRegisterNum=" + sellerRegisterNum + "]"; } }
[ "yong.fu@meikejob.com" ]
yong.fu@meikejob.com
e53387bb885ef2cc62d72f91392e24c327620af6
88e33f8e6db8cc9459857bd752adc5a2ff1e1f57
/excelpanel/src/main/java/cn/zhouchaoyuan/excelpanel/RecyclerViewAdapter.java
8f47b1b0495a66c8dd52871240c2c5621f07000c
[ "Apache-2.0" ]
permissive
JacksonLi-LiBin/excelPanel
e3f2b951af92b66740e8533606ad1871ed681c5c
70a509c1a6d4aa5cce16e9fd1675ff4f32beae85
refs/heads/master
2021-01-21T06:52:52.864922
2019-06-27T08:17:41
2019-06-27T08:17:41
101,950,376
0
0
Apache-2.0
2019-06-27T08:17:42
2017-08-31T02:31:38
Java
UTF-8
Java
false
false
4,495
java
package cn.zhouchaoyuan.excelpanel; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import cn.zhouchaoyuan.utils.Utils; /** * Created by gcq on 16/8/19. */ public abstract class RecyclerViewAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public static final int TYPE_HEADER = 0; public static final int TYPE_FOOTER = 1; public static final int TYPE_NORMAL = 2; protected View mHeader; protected View mFooter; protected List<T> mDatas; protected Context mContext; protected LayoutInflater mInflater; public RecyclerViewAdapter(Context context) { this(context, (List) null); } public RecyclerViewAdapter(Context context, List<T> list) { mDatas = list; this.mContext = context; if (list != null) { this.mDatas = new ArrayList(list); } this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setData(List<T> data) { if (data == null) { this.mDatas = null; } else { this.mDatas = new ArrayList(data); } this.notifyDataSetChanged(); } public void setHeaderView(View headerView) { if (null == headerView) { if (null != mHeader) { mHeader = null; notifyItemRemoved(0); } } else { if (null != mHeader) { if (mHeader != headerView) { mHeader = headerView; notifyItemChanged(0); } } else { mHeader = headerView; notifyItemInserted(0); } } } public void setFooterView(View footerView) { if (null == footerView) { if (null != mFooter) { mFooter = null; notifyItemRemoved(getItemCount()); } } else { if (null != mFooter) { if (mFooter != footerView) { mFooter = footerView; notifyItemChanged(getItemCount()); } } else { mFooter = footerView; notifyItemInserted(getItemCount()); } } } public T getItem(int position) { if (Utils.isEmpty(mDatas) || position < 0 || position >= mDatas.size()) { return null; } return this.mDatas.get(position); } public int getHeaderViewsCount() { return null == mHeader ? 0 : 1; } public int getFooterViewsCount() { return null == mFooter ? 0 : 1; } @Override public int getItemViewType(int position) { if (null != mHeader && position == 0) { return TYPE_HEADER; } if (null != mFooter && position == getItemCount() - 1) { return TYPE_FOOTER; } return TYPE_NORMAL; } @Override public int getItemCount() { int size = getHeaderViewsCount(); size += getFooterViewsCount(); if (null != mDatas) { size += mDatas.size(); } return size; } public int getRealCount() { return null == mDatas ? 0 : mDatas.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_HEADER) { return new HeaderFooterHolder(mHeader); } else if (viewType == TYPE_FOOTER) { return new HeaderFooterHolder(mFooter); } else { return onCreateNormalViewHolder(parent, viewType); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { int viewType = getItemViewType(position); if (viewType == TYPE_NORMAL) { onBindNormalViewHolder(holder, position - getHeaderViewsCount()); } } public abstract RecyclerView.ViewHolder onCreateNormalViewHolder(ViewGroup parent, int viewType); public abstract void onBindNormalViewHolder(RecyclerView.ViewHolder holder, int position); static class HeaderFooterHolder extends RecyclerView.ViewHolder { public HeaderFooterHolder(View itemView) { super(itemView); } } }
[ "zhouchaoyuan@meituan.com" ]
zhouchaoyuan@meituan.com
ddd63b3501567cb9686b37a5e8a7f7089cea668b
09cab16393de97786db35d5e10e0233a1ba7880a
/src/main/java/cn/edu/jxnu/practice/NumberOf0.java
25e4cde97cc77e33f622349d49383a319ad2c46e
[ "Apache-2.0" ]
permissive
yangzaiqiong/cs-summary-reflection
ab6cc3289ad7c05e0a86ff69f93e2d135627c61b
3356520e44a0f892c72b37f93e6836f8422cd3ae
refs/heads/master
2020-07-11T22:41:00.549023
2019-08-26T15:45:04
2019-08-26T15:45:04
204,659,061
1
0
Apache-2.0
2019-08-27T16:42:01
2019-08-27T08:42:00
null
UTF-8
Java
false
false
954
java
package cn.edu.jxnu.practice; /** * 参考:编程之美 * * @description 计算n的阶乘中,末尾含有0的个数 * @author Mr.Li * */ public class NumberOf0 { public static void main(String[] args) { int n = 1024; int result = NumberOf0_2(n); System.out.println(n + "的阶乘中含有:" + result + "个0"); } public static int NumberOf0_1(int n) { int ret = 0; int j; for (int i = 1; i <= n; i++) { j = i; while (j % 5 == 0) { ret++; j /= 5; } } return ret; } /** * @description 使用公式Z=[N/5]+[N/5^2]+[N/5^3]....{存在K使得5^K>N即[N/5^K]==0} * [N/5]=不大于N的数中,5的倍数贡献一个5 [N/5^2]=不大于N的数中,5^2的倍数贡献一个5 * 上公式意味:[N/K]=1,2,3....N中能被k整除的数的个数 */ public static int NumberOf0_2(int n) { int ret = 0; while (n != 0) { ret += n / 5; n /= 5; } return ret; } }
[ "568845948@qq.com" ]
568845948@qq.com
8a8e1ff98a49746e3bcf36c7a789baf2b99b7cc3
898ec8eff622139e60db800df528f0058f0208be
/src/main/java/com/book/system/entity/BookCollection.java
1b639e271f6c00263d5e75125ff4dbfb7dafb2ff
[]
no_license
VlanBlues/BookManageSyetem
25fd385e5f944002b17bd4111c8d119ddb140166
46b2fae197e173c220d4c69b6c852a8fe98967d7
refs/heads/master
2023-01-22T01:56:57.229859
2020-12-08T08:55:24
2020-12-08T08:55:24
305,936,303
0
0
null
null
null
null
UTF-8
Java
false
false
652
java
package com.book.system.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; /** * <p> * * </p> * * @author lan * @since 2020-10-21 */ @Data @EqualsAndHashCode(callSuper = false) public class BookCollection implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "collection_id", type = IdType.AUTO) private Integer collectionId; private Integer bookId; private Integer readerId; }
[ "794758167@qq.com" ]
794758167@qq.com
a0799080f87da2ac23e059087f3286d7a36b6682
7f684e215e16d41651069961e0b68e2847da3413
/src/main/java/com/yudis/spring/inventory/model/User.java
7b5b0352391670d73b1eea22a9099fb8309545d4
[]
no_license
yudistyra/springrms
ed806a9f226283269e62760359bdd111d562aef0
5107610e3879be6d28c732a1c77f9257a665d729
refs/heads/master
2020-04-08T11:22:18.096368
2018-12-05T08:29:15
2018-12-05T08:29:15
159,143,475
0
0
null
null
null
null
UTF-8
Java
false
false
1,167
java
package com.yudis.spring.inventory.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import org.hibernate.validator.constraints.Length; import org.springframework.lang.Nullable; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @AllArgsConstructor @NoArgsConstructor @Entity public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @NotEmpty(message = "*Please provide a Username") private String username; @Length(min = 5, message = "*Your password must have at least 5 characters") @NotEmpty(message = "*Please provide a Password") private String password; @Email(message = "*Please provide a valid Email") @NotEmpty(message = "*Please provide an email") private String email; @NotEmpty(message = "*Please provide a Name") private String name; private boolean active; @Nullable @OneToOne private Role role; }
[ "Yudistyra_OP355@mitrais.com" ]
Yudistyra_OP355@mitrais.com
9b1a8e50b188b1c2515de88b1d18d244fc0cb0b7
fd19d4e29b640413d72966b39fbefa71c26530c6
/Java/HackerRank/ProblemSolving/Big Sorting/Solution.java
4c66d5c7b0f1402b35f5c14487858c523497c964
[]
no_license
MahdiDavoodi/JK
55cd5abd4b47e9a67bdb7fc11703e717478f8811
8ca8d555816c40b0f4867e7a4ecaae85b4914fa1
refs/heads/master
2023-08-05T10:51:33.266427
2021-09-26T07:09:17
2021-09-26T07:09:17
295,502,547
0
0
null
null
null
null
UTF-8
Java
false
false
1,372
java
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { static String[] bigSorting(String[] unsorted) { Arrays.sort(unsorted, (x, y) -> x.length() == y.length() ? x.compareTo(y) : Long.compare(x.length(), y.length())); return unsorted; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); String[] unsorted = new String[n]; for (int i = 0; i < n; i++) { // Got help from the others for this one (Timeout exception) String unsortedItem = scanner.next(); unsorted[i] = unsortedItem; } String[] result = bigSorting(unsorted); for (int i = 0; i < result.length; i++) { bufferedWriter.write(result[i]); if (i != result.length - 1) { bufferedWriter.write("\n"); } } bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } }
[ "mahdidavoodi@gmail.com" ]
mahdidavoodi@gmail.com
f69721853385b6ff9b0a1ca6f3ed2a9167a1be57
3bd2d8b64c4b61b7b1daafdd4063f2924cd06e00
/app/src/test/java/com/honjane/tagtextview/ExampleUnitTest.java
3791492cbf48ca52a8f289103f80671b50184e0a
[]
no_license
honjane/TagTextViewDemo
4e97a3abe887b9f30eb919f0f060088dd2076e93
4aaee173ff0e392dbbec22f7e8306a0f5f493bc5
refs/heads/master
2021-01-11T08:54:13.605159
2016-12-18T07:49:07
2016-12-18T07:49:07
76,768,858
0
0
null
null
null
null
UTF-8
Java
false
false
401
java
package com.honjane.tagtextview; 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() throws Exception { assertEquals(4, 2 + 2); } }
[ "honjane@126.com" ]
honjane@126.com
51c13e3fb7b1770accc19f05db518f5c5416141c
591b5e3cbbe4ab9c162c6a9fee58102a8fd2c0fb
/src/minecraft/net/minecraft/client/gui/GuiOptions.java
17aaef3632d61969225f7b2977a9ffd6f8ea768e
[]
no_license
day-trip/Sunrise
fd98198b0f61fd09767cda14fdc450afc5854273
1fe0163aabf3f010cf0145821c1f4be97eacd2cd
refs/heads/main
2023-08-24T06:47:57.795982
2021-10-25T21:32:36
2021-10-25T21:32:36
411,857,044
0
0
null
null
null
null
UTF-8
Java
false
false
10,088
java
package net.minecraft.client.gui; import java.io.IOException; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.audio.SoundCategory; import net.minecraft.client.audio.SoundEventAccessorComposite; import net.minecraft.client.audio.SoundHandler; import net.minecraft.client.gui.stream.GuiStreamOptions; import net.minecraft.client.gui.stream.GuiStreamUnavailable; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; import net.minecraft.client.stream.IStream; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; import net.minecraft.world.EnumDifficulty; public class GuiOptions extends GuiScreen { private static final GameSettings.Options[] field_146440_f = {GameSettings.Options.FOV}; private final GuiScreen field_146441_g; /** Reference to the GameSettings object. */ private final GameSettings game_settings_1; private GuiButton field_175357_i; private GuiLockIconButton field_175356_r; protected String field_146442_a = "Options"; public GuiOptions(GuiScreen p_i1046_1_, GameSettings p_i1046_2_) { field_146441_g = p_i1046_1_; game_settings_1 = p_i1046_2_; } /** * Adds the buttons (and other controls) to the screen in question. Called when the GUI is displayed and when the * window resizes, the buttonList is cleared beforehand. */ public void initGui() { int i = 0; field_146442_a = I18n.format("options.title"); for (GameSettings.Options gamesettings$options : field_146440_f) { if (gamesettings$options.getEnumFloat()) { buttonList.add(new GuiOptionSlider(gamesettings$options.returnEnumOrdinal(), width / 2 - 155 + i % 2 * 160, height / 6 - 12 + 24 * (i >> 1), gamesettings$options)); } else { GuiOptionButton guioptionbutton = new GuiOptionButton(gamesettings$options.returnEnumOrdinal(), width / 2 - 155 + i % 2 * 160, height / 6 - 12 + 24 * (i >> 1), gamesettings$options, game_settings_1.getKeyBinding(gamesettings$options)); buttonList.add(guioptionbutton); } ++i; } if (mc.theWorld != null) { EnumDifficulty enumdifficulty = mc.theWorld.getDifficulty(); field_175357_i = new GuiButton(108, width / 2 - 155 + i % 2 * 160, height / 6 - 12 + 24 * (i >> 1), 150, 20, func_175355_a(enumdifficulty)); buttonList.add(field_175357_i); if (mc.isSingleplayer() && !mc.theWorld.getWorldInfo().isHardcoreModeEnabled()) { field_175357_i.setWidth(field_175357_i.getButtonWidth() - 20); field_175356_r = new GuiLockIconButton(109, field_175357_i.xPosition + field_175357_i.getButtonWidth(), field_175357_i.yPosition); buttonList.add(field_175356_r); field_175356_r.func_175229_b(mc.theWorld.getWorldInfo().isDifficultyLocked()); field_175356_r.enabled = !field_175356_r.func_175230_c(); field_175357_i.enabled = !field_175356_r.func_175230_c(); } else { field_175357_i.enabled = false; } } buttonList.add(new GuiButton(110, width / 2 - 155, height / 6 + 48 - 6, 150, 20, I18n.format("options.skinCustomisation"))); buttonList.add(new GuiButton(8675309, width / 2 + 5, height / 6 + 48 - 6, 150, 20, "Super Secret Settings...") { public void playPressSound(SoundHandler soundHandlerIn) { SoundEventAccessorComposite soundeventaccessorcomposite = soundHandlerIn.getRandomSoundFromCategories(SoundCategory.ANIMALS, SoundCategory.BLOCKS, SoundCategory.MOBS, SoundCategory.PLAYERS, SoundCategory.WEATHER); if (soundeventaccessorcomposite != null) { soundHandlerIn.playSound(PositionedSoundRecord.create(soundeventaccessorcomposite.getSoundEventLocation(), 0.5F)); } } }); buttonList.add(new GuiButton(106, width / 2 - 155, height / 6 + 72 - 6, 150, 20, I18n.format("options.sounds"))); buttonList.add(new GuiButton(107, width / 2 + 5, height / 6 + 72 - 6, 150, 20, I18n.format("options.stream"))); buttonList.add(new GuiButton(101, width / 2 - 155, height / 6 + 96 - 6, 150, 20, I18n.format("options.video"))); buttonList.add(new GuiButton(100, width / 2 + 5, height / 6 + 96 - 6, 150, 20, I18n.format("options.controls"))); buttonList.add(new GuiButton(102, width / 2 - 155, height / 6 + 120 - 6, 150, 20, I18n.format("options.language"))); buttonList.add(new GuiButton(103, width / 2 + 5, height / 6 + 120 - 6, 150, 20, I18n.format("options.chat.title"))); buttonList.add(new GuiButton(105, width / 2 - 155, height / 6 + 144 - 6, 150, 20, I18n.format("options.resourcepack"))); buttonList.add(new GuiButton(104, width / 2 + 5, height / 6 + 144 - 6, 150, 20, I18n.format("options.snooper.view"))); buttonList.add(new GuiButton(200, width / 2 - 100, height / 6 + 168, I18n.format("gui.done"))); } public String func_175355_a(EnumDifficulty p_175355_1_) { IChatComponent ichatcomponent = new ChatComponentText(""); ichatcomponent.appendSibling(new ChatComponentTranslation("options.difficulty")); ichatcomponent.appendText(": "); ichatcomponent.appendSibling(new ChatComponentTranslation(p_175355_1_.getDifficultyResourceKey())); return ichatcomponent.getFormattedText(); } public void confirmClicked(boolean result, int id) { mc.displayGuiScreen(this); if (id == 109 && result && mc.theWorld != null) { mc.theWorld.getWorldInfo().setDifficultyLocked(true); field_175356_r.func_175229_b(true); field_175356_r.enabled = false; field_175357_i.enabled = false; } } /** * Called by the controls from the buttonList when activated. (Mouse pressed for buttons) */ protected void actionPerformed(GuiButton button) throws IOException { if (button.enabled) { if (button.id < 100 && button instanceof GuiOptionButton) { GameSettings.Options gamesettings$options = ((GuiOptionButton)button).returnEnumOptions(); game_settings_1.setOptionValue(gamesettings$options, 1); button.displayString = game_settings_1.getKeyBinding(GameSettings.Options.getEnumOptions(button.id)); } if (button.id == 108) { mc.theWorld.getWorldInfo().setDifficulty(EnumDifficulty.getDifficultyEnum(mc.theWorld.getDifficulty().getDifficultyId() + 1)); field_175357_i.displayString = func_175355_a(mc.theWorld.getDifficulty()); } if (button.id == 109) { mc.displayGuiScreen(new GuiYesNo(this, (new ChatComponentTranslation("difficulty.lock.title")).getFormattedText(), (new ChatComponentTranslation("difficulty.lock.question", new ChatComponentTranslation(mc.theWorld.getWorldInfo().getDifficulty().getDifficultyResourceKey()))).getFormattedText(), 109)); } if (button.id == 110) { mc.gameSettings.saveOptions(); mc.displayGuiScreen(new GuiCustomizeSkin(this)); } if (button.id == 8675309) { mc.entityRenderer.activateNextShader(); } if (button.id == 101) { mc.gameSettings.saveOptions(); mc.displayGuiScreen(new GuiVideoSettings(this, game_settings_1)); } if (button.id == 100) { mc.gameSettings.saveOptions(); mc.displayGuiScreen(new GuiControls(this, game_settings_1)); } if (button.id == 102) { mc.gameSettings.saveOptions(); mc.displayGuiScreen(new GuiLanguage(this, game_settings_1, mc.getLanguageManager())); } if (button.id == 103) { mc.gameSettings.saveOptions(); mc.displayGuiScreen(new ScreenChatOptions(this, game_settings_1)); } if (button.id == 104) { mc.gameSettings.saveOptions(); mc.displayGuiScreen(new GuiSnooper(this, game_settings_1)); } if (button.id == 200) { mc.gameSettings.saveOptions(); mc.displayGuiScreen(field_146441_g); } if (button.id == 105) { mc.gameSettings.saveOptions(); mc.displayGuiScreen(new GuiScreenResourcePacks(this)); } if (button.id == 106) { mc.gameSettings.saveOptions(); mc.displayGuiScreen(new GuiScreenOptionsSounds(this, game_settings_1)); } if (button.id == 107) { mc.gameSettings.saveOptions(); IStream istream = mc.getTwitchStream(); if (istream.func_152936_l() && istream.func_152928_D()) { mc.displayGuiScreen(new GuiStreamOptions(this, game_settings_1)); } else { GuiStreamUnavailable.func_152321_a(this); } } } } /** * Draws the screen and all the components in it. Args : mouseX, mouseY, renderPartialTicks */ public void drawScreen(int mouseX, int mouseY, float partialTicks) { drawDefaultBackground(); drawCenteredString(fontRendererObj, field_146442_a, width / 2, 15, 16777215); super.drawScreen(mouseX, mouseY, partialTicks); } }
[ "unconfigured@null.spigotmc.org" ]
unconfigured@null.spigotmc.org
665c7657c1d329e12ada0f6f7bbd0774aea40bcb
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/8/8_a3f79c7cc3a96939b7f599852db0c03acef45ce8/MoonInfo/8_a3f79c7cc3a96939b7f599852db0c03acef45ce8_MoonInfo_s.java
5fd327b50eaf26d9b485203adad35d3f3910d904
[]
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
21,664
java
package com.typeiisoft.lct.utils; import com.typeiisoft.lct.features.LunarFeature; import com.mhuss.AstroLib.Astro; import com.mhuss.AstroLib.AstroDate; import com.mhuss.AstroLib.DateOps; import com.mhuss.AstroLib.LocationElements; import com.mhuss.AstroLib.Lunar; import com.mhuss.AstroLib.LunarCalc; import com.mhuss.AstroLib.NoInitException; import com.mhuss.AstroLib.ObsInfo; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import android.annotation.SuppressLint; import android.util.Log; /** * This class handles calling calculations and returning various bits of * information about the moon. It will also handle the logic for determining * if a lunar feature is visible. * * @author Michael Reuter */ public class MoonInfo { /** Logging identifier. */ private static final String TAG = MoonInfo.class.getName(); /** The current date and time in UTC for all observation information. */ private AstroDate obsDate; /** The current date and time in the local timezone. */ private GregorianCalendar obsLocal; /** Object that does most of the calculations. */ private Lunar lunar; /** Object that holds the observing site information. */ private ObsInfo obsInfo; /** Holder for the Time Zone offset. */ private int tzOffset; /** Holder for the selenographic colongitude. */ private double colongitude; /** Holder for the libration in latitude */ private double liblatitude; /** Holder for the libration in longitude */ private double liblongitude; /** Enum containing the lunar phases for integer comparison. */ private enum Phase { NM, WAXING_CRESENT, FQ, WAXING_GIBBOUS, FM, WANING_GIBBOUS, TQ, WANING_CRESENT; } /** Array of lunar phase names. */ private String[] phaseNames = {"New Moon", "Waxing Cresent", "First Quarter", "Waxing Gibbous", "Full Moon", "Waning Gibbous", "Third Quarter", "Waning Cresent"}; /** Array of lunar phase values. */ private int[] phaseValues = {Lunar.NEW, Lunar.Q1, Lunar.FULL, Lunar.Q3}; /** Array of phase boundaries based on illuminated fraction. */ private double[] phaseBounds = {0.005, 0.49, 0.51, 0.99}; /** Enum containing the time of lunar day for integer comparison. */ private enum TimeOfDay { MORNING, EVENING; } /** Selenographic longitude where relief makes it hard to see feature. */ private static final double FEATURE_CUTOFF = 15D; /** Lunar features to which no selenographic longitude cutoff is applied. */ private String[] noCutoffType = {"Mare", "Oceanus"}; /** Pi divided by four */ private static final double PI_OVER_FOUR = Math.PI / 4D; /** Latitude and/or longitude region where librations makes big effect. */ private static final double LIBRATION_ZONE = 80D; /** Theoretical visibility limit for features. */ private static final double LUNAR_EDGE = 90D; /** * This function is the class constructor. */ public MoonInfo() { Calendar now = Calendar.getInstance(); this.obsLocal = (GregorianCalendar)now.clone(); this.tzOffset = now.getTimeZone().getOffset(now.getTimeInMillis()) / Astro.MILLISECONDS_PER_HOUR; now.add(Calendar.HOUR_OF_DAY, this.tzOffset); this.obsDate = new AstroDate(now.get(Calendar.DATE), now.get(Calendar.MONTH)+1, now.get(Calendar.YEAR), now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND)); this.initialize(); } /** * This function is the class constructor with parameters. * @param datetime : Array of seven values of the current date and time. */ public MoonInfo(int[] datetime) { this.obsDate = new AstroDate(datetime[0], datetime[1], datetime[2], datetime[3], datetime[4], datetime[5]); this.obsLocal = this.obsDate.toGCalendar(); this.tzOffset = datetime[6]; this.obsLocal.add(Calendar.HOUR_OF_DAY, datetime[6]); this.initialize(); } /** * This function consolidates some of the common setup. */ private void initialize() { this.lunar = new Lunar(this.getJulianCenturies()); this.obsInfo = new ObsInfo(); this.colongitude = Double.MAX_VALUE; this.liblatitude = Double.MAX_VALUE; this.liblongitude = Double.MAX_VALUE; } /** * This function calculates the Julian centuries based on the current * observation date/time. The empty AstroDate constructor defaults to * epoch J2000.0 * @return : The Julian centuries for the current observation date/time. */ private double getJulianCenturies() { double daysSinceEpoch = this.obsDate.jd() - new AstroDate().jd(); return daysSinceEpoch / Astro.TO_CENTURIES; } /** * This function sets the latitude and longitude for an observing site. * This is used for some of the calculations. * @param lat : The observing site's latitude in decimal degrees. * @param lon : The observing site's longitude in decimal degrees. */ public void setObservationInfo(double lat, double lon) { this.obsInfo.setLatitudeDeg(lat); this.obsInfo.setLongitudeDeg(lon); } /** * This function gets the age of the Moon in days. * @return : The Moon's age. */ public double age() { return LunarCalc.ageOfMoonInDays(this.obsLocal); } /** * This function gets the illuminated fraction of the Moon's surface. * @return : The fraction of the illuminated Moon surface. */ public double illumation() { double illum = 0.0; try { illum = this.lunar.illuminatedFraction(); } catch (NoInitException nie) { Log.e(TAG, "Lunar object is not initialized for calculating illumination."); } return illum; } /** * This function gets the current local observation time. * @return : The object holding the time. */ public Calendar getObsLocal() { return this.obsLocal; } /** * This function gets the current UTC observation time. * @return : The object holding the time. */ public Calendar getObsUtc() { return this.obsDate.toGCalendar(); } /** * This function returns the selenographic colongitude for the current * date and time. * @return : The current selenographic colongitude. */ public double colong() { this.getColongitude(); Log.i(TAG, "Colongitude calculated = " + Double.toString(this.colongitude)); return this.colongitude; } /** * This function returns the phase angle for the moon in units of * radians. * @return : The current lunar phase angle. */ public double phaseAngle() { double phaseAngle = 0.0; try { phaseAngle = this.lunar.phaseAngle(); } catch (NoInitException nie) { Log.e(TAG, "Lunar object is not initialized for calculating phase angle."); } return phaseAngle; } /** * This function returns the lunar librations in both latitude and longitude. * @return : The lunar librations array. */ public double[] librations() { this.getLibrations(); double[] temp = {this.liblatitude, this.liblongitude}; return temp; } /** * This function returns the phase of the Moon as a string. * @return : The Moon phase as a string. */ public String phase() { return this.phaseNames[this.getPhase().ordinal()]; } /** * This function determines if the given lunar feature is visible based * on the current selenographic colongitude (SELCO). For most features * near the equator, from NM to FM once the SELCO recedes about 15 * degrees, the shadow relief makes it tough to observe. Conversely, the * SELCO needs to be within 15 degrees of the feature from FM to NM. * Features closer to the poles are visible much longer after the 15 * degree cutoff. A 1/cos(latitude) will be applied to the cutoff. * Mare and Oceanus are special exceptions and once FULLY visible they are * always visible. * @param feature : The lunar feature to check for visibility. * @return : True is the feature is visible. */ public boolean isVisible(LunarFeature feature) { double selcoLong = this.colongToLong(); Log.v(TAG, "SelcoLong = " + Double.toString(selcoLong)); int curTod = this.getTimeOfDay().ordinal(); Log.v(TAG, "CurTod = " + Integer.toString(curTod)); double minLon = feature.getLongitude() - feature.getDeltaLongitude() / 2.0; double maxLon = feature.getLongitude() + feature.getDeltaLongitude() / 2.0; // Switch things around if necessary if (minLon > maxLon) { double temp = minLon; minLon = maxLon; maxLon = temp; } boolean isVisible = false; double latitudeScaling = Math.cos(Math.toRadians(Math.abs(feature.getLatitude()))); double cutoff = MoonInfo.FEATURE_CUTOFF / latitudeScaling; double lonCutoff = 0.0; if (TimeOfDay.MORNING.ordinal() == curTod) { // Minimum longitude for morning visibility lonCutoff = minLon - cutoff; if (this.noCutoffFeature(feature.getFeatureType())) { isVisible = selcoLong <= minLon; } else { isVisible = (selcoLong >= lonCutoff && selcoLong <= minLon); } } if (TimeOfDay.EVENING.ordinal() == curTod) { // Maximum longitude for evening visibility lonCutoff = maxLon + cutoff; if (this.noCutoffFeature(feature.getFeatureType())) { isVisible = maxLon <= selcoLong; } else { isVisible = (selcoLong >= maxLon && selcoLong <= lonCutoff); } } return (isVisible && this.isLibrationOk(feature)); } /** * This function determines if feature is effected and possibly obscured * by libration. * @param feature : The lunar feature to check for the libration effect. * @return : False if libration obscures feature. */ private boolean isLibrationOk(LunarFeature feature) { boolean isLongitudeInZone = Math.abs(feature.getLongitude()) > LIBRATION_ZONE; boolean isLatitudeInZone = Math.abs(feature.getLatitude()) > LIBRATION_ZONE; if (isLongitudeInZone || isLatitudeInZone) { this.getLibrations(); if (isLongitudeInZone) { double longitude = feature.getLongitude(); double[] longRange = feature.getLongitudeRange(); longitude -= this.liblongitude; longRange[0] -= this.liblongitude; longRange[1] -= this.liblongitude; Log.d(TAG, "Adjusted longitude: " + longitude + " [" + longRange[0] + ", " + longRange[1] + "]"); if (longitude < 0) { if (longRange[1] < -LUNAR_EDGE) { return false; } } else { if (longRange[0] > LUNAR_EDGE) { return false; } } } if (isLatitudeInZone) { double latitude = feature.getLatitude(); double[] latRange = feature.getLatitudeRange(); latitude -= this.liblatitude; latRange[0] -= this.liblatitude; latRange[1] -= this.liblatitude; Log.d(TAG, "Adjusted latitude: " + latitude + " [" + latRange[0] + ", " + latRange[1] + "]"); if (latitude < 0) { if (latRange[1] < -LUNAR_EDGE) { return false; } } else { if (latRange[0] > LUNAR_EDGE) { return false; } } } return true; } return true; } /** * This function is to set the selenographic colongitude once for a given * instance. This will cut down on the number of calculations done by the * library call. */ private void getColongitude() { if (Double.MAX_VALUE == this.colongitude) { this.colongitude = LunarCalc.colongitude(this.getJulianCenturies()); } } /** * This function obtains the lunar librations in both latitude and longitude. */ private void getLibrations() { if (Double.MAX_VALUE == this.liblatitude && Double.MAX_VALUE == this.liblongitude) { try { LocationElements le = this.lunar.getTotalLibrations(); this.liblatitude = Math.toDegrees(le.getLatitude()); this.liblongitude = Math.toDegrees(le.getLongitude()); Log.i(TAG, "Libration in Latitude = " + this.liblatitude); Log.i(TAG, "Libration in Longitude = " + this.liblongitude); } catch (NoInitException nie) { Log.e(TAG, "Lunar object is not initialized for calculating librations."); } } } /** * This function checks a given lunar feature type against the list of lunar * feature types that have no cutoff. * @param type : The string containing the lunar feature type. * @return : True is the incoming feature type is in no cutoff list. */ private boolean noCutoffFeature(String type) { for (String s : this.noCutoffType) { if (s.equalsIgnoreCase(type)) { return true; } } return false; } /** * This function returns the moon phase according to standard nomenclature. * @return : The moon phase as an enum value. */ private Phase getPhase() { double illum = this.illumation(); double phaseAngle = this.phaseAngle(); double sinPhaseAngle = Math.sin(phaseAngle); if (illum < phaseBounds[0]) { return Phase.NM; } if (phaseBounds[0] <= illum && illum <= phaseBounds[1]) { if (sinPhaseAngle > 0.0) { return Phase.WAXING_CRESENT; } else { return Phase.WANING_CRESENT; } } if (phaseBounds[1] < illum && illum < phaseBounds[2]) { if (sinPhaseAngle > 0.0) { return Phase.FQ; } else { return Phase.TQ; } } if (phaseBounds[2] <= illum && illum <= phaseBounds[3]) { if (sinPhaseAngle > 0.0) { return Phase.WAXING_GIBBOUS; } else { return Phase.WANING_GIBBOUS; } } if (illum > phaseBounds[3]) { return Phase.FM; } // Shouldn't make it here return Phase.NM; } /** * This function determines the current time of day on the moon. In * otherwords, if the sun is rising on the moon it is morning or if the * sun is setting on the moon it is evening. * @return : The current time of day. */ private TimeOfDay getTimeOfDay() { double phaseAngle = this.phaseAngle(); double sinPhaseAngle = Math.sin(phaseAngle); if (sinPhaseAngle > 0.0) { return TimeOfDay.MORNING; } else if (sinPhaseAngle < 0.0) { return TimeOfDay.EVENING; } else { if (phaseAngle == 0.0 || phaseAngle == Astro.TWO_PI) { return TimeOfDay.EVENING; } } return TimeOfDay.MORNING; } /** * This function calculates the conversion between the selenographic * colongitude and actual lunar longitude. * @return : The lunar longitude for the current selenographic colongitude. */ private double colongToLong() { this.getColongitude(); double phaseAngle = this.phaseAngle(); double sinPhaseAngle = Math.sin(phaseAngle); if (phaseAngle <= Astro.PI_OVER_TWO && phaseAngle > PI_OVER_FOUR) { return 360.0 - this.colongitude; } if (phaseAngle <= PI_OVER_FOUR && phaseAngle > 0.0) { return -1.0 * this.colongitude; } if (sinPhaseAngle < 0.0 || phaseAngle == 0.0 || phaseAngle == Astro.TWO_PI) { return 180.0 - this.colongitude; } Log.d(TAG, "Oops, shouldn't have gotten here!"); return this.colongitude; } /** * This function creates the string representation of the object. * @return : The current string representation. */ public String toString() { StringBuffer buf = new StringBuffer(); String[] tmp = StrFormat.dateFormat(this.obsLocal).split(" ", 2); buf.append("Date: ").append(tmp[0]).append(System.getProperty("line.separator")); buf.append("Time: ").append(tmp[1]).append(System.getProperty("line.separator")); buf.append("Julian Date: ").append(Double.toString(this.obsDate.jd())); buf.append(System.getProperty("line.separator")); return buf.toString(); } /** * This function returns the local date of the previous new Moon. * @return : The date of the previous new Moon. */ public Calendar previousNewMoon() { AstroDate nmDate = this.findPreviousPhase(Lunar.NEW); return this.fixTime(nmDate); } /** * This function returns the local date of the previous full Moon. * @return : The date of the previous full Moon. */ public Calendar previousFullMoon() { AstroDate fmDate = this.findPreviousPhase(Lunar.FULL); return this.fixTime(fmDate); } /** * This function returns the local date of the previous first quarter Moon. * @return : The date of the previous first quarter Moon. */ public Calendar previousFirstQuarterMoon() { AstroDate fqmDate = this.findPreviousPhase(Lunar.Q1); return this.fixTime(fqmDate); } /** * This function returns the local date of the previous third quarter Moon. * @return : The date of the previous third quarter Moon. */ public Calendar previousThirdQuarterMoon() { AstroDate tqmDate = this.findPreviousPhase(Lunar.Q3); return this.fixTime(tqmDate); } /** * This function returns the local date of the next new Moon. * @return : The date of the next new Moon. */ public Calendar nextNewMoon() { AstroDate nmDate = this.findNextPhase(Lunar.NEW); return this.fixTime(nmDate); } /** * This function returns the local date of the next full Moon. * @return : The date of the next full Moon. */ public Calendar nextFullMoon() { AstroDate fmDate = this.findNextPhase(Lunar.FULL); return this.fixTime(fmDate); } /** * This function returns the local date of the next first quarter Moon. * @return : The date of the next first quarter Moon. */ public Calendar nextFirstQuarterMoon() { AstroDate fqmDate = this.findNextPhase(Lunar.Q1); return this.fixTime(fqmDate); } /** * This function returns the local date of the next third quarter Moon. * @return : The date of the next third quarter Moon. */ public Calendar nextThirdQuarterMoon() { AstroDate tqmDate = this.findNextPhase(Lunar.Q3); return this.fixTime(tqmDate); } /** * This function determines the previous UTC date of the requested lunar * phase. In this context, previous means before the current UTC date. * @param phase : The requested phase to find. * @return : The UTC date of the requested phase. */ private AstroDate findPreviousPhase(int phase) { double date = Lunar.getPhase(DateOps.calendarToDay(this.obsDate.toGCalendar()), phase); AstroDate phaseDate = new AstroDate(date); if (this.obsDate.toGCalendar().before(phaseDate.toGCalendar())) { // Roll date back by Lunar month Calendar cal = this.obsDate.toGCalendar(); cal.add(Calendar.DAY_OF_MONTH, -1*(int)(LunarCalc.SYNODIC_MONTH+0.5)); Log.d(TAG, "Previous phase date to use: " + StrFormat.dateFormat(cal)); date = Lunar.getPhase(DateOps.calendarToDay(cal), phase); phaseDate = new AstroDate(date); } return phaseDate; } /** * This function determines the next UTC date of the requested lunar * phase. In this context, next means after the current UTC date. * @param phase : The requested phase to find. * @return : The UTC date of the requested phase. */ private AstroDate findNextPhase(int phase) { double date = Lunar.getPhase(DateOps.calendarToDay(this.obsDate.toGCalendar()), phase); AstroDate phaseDate = new AstroDate(date); if (this.obsDate.toGCalendar().after(phaseDate.toGCalendar())) { // Push date out by Lunar month Calendar cal = this.obsDate.toGCalendar(); cal.add(Calendar.DAY_OF_MONTH, (int)(LunarCalc.SYNODIC_MONTH+0.5)); Log.d(TAG, "Next phase date to use: " + StrFormat.dateFormat(cal)); date = Lunar.getPhase(DateOps.calendarToDay(cal), phase); phaseDate = new AstroDate(date); } return phaseDate; } /** * This function finds the calendar date of the requested lunar phase. * @param phase : The value of the lunar phase. * @return : The calendar date of the lunar phase. */ private Calendar findPhase(int phase) { double date = Lunar.getPhase(DateOps.calendarToDay(this.obsDate.toGCalendar()), phase); AstroDate phaseDate = new AstroDate(date); GregorianCalendar c = phaseDate.toGCalendar(); c.add(Calendar.HOUR_OF_DAY, this.tzOffset); return c; } /** * This function finds the dates for the next four lunar phases. A map is created that * contains the calendar date of the phase as the map key and an integer values for the * phases as the map value. * @return : A map containing the information. */ @SuppressLint("UseSparseArrays") public Map<Calendar, Integer> findNextFourPhases() { Map<Calendar, Integer> phases = new HashMap<Calendar, Integer>(); List<Integer> indices = new ArrayList<Integer>(); for (int i = 0; i < 4; i++) { Calendar cal = this.findPhase(phaseValues[i]); if (cal.before(this.obsLocal)) { indices.add(Integer.valueOf(i)); continue; } else { phases.put(cal, Integer.valueOf(i)); } } // If the indices list is not empty, need to fill with next phases. Iterator<Integer> lit = indices.iterator(); while (lit.hasNext()) { Integer phase = lit.next(); AstroDate ad = this.findNextPhase(phase.intValue()); Calendar cal = this.fixTime(ad); phases.put(cal, phase); } return phases; } /** * This function takes an AstroDate which is in UTC and changes it to a * GregorianCalendar and then adjusts it for local time. * @param ad : The date to adjust. * @return : The adjusted local date. */ private GregorianCalendar fixTime(AstroDate ad) { GregorianCalendar c = ad.toGCalendar(); c.add(Calendar.HOUR_OF_DAY, this.tzOffset); return c; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
d7f1d4ad889f28c1a1bc54dff7a9723526a46a89
5bb4f2f1f7c30d95ac6d4c2cb4f3de2849110d7f
/DevLibUtils/src/main/java/dev/utils/app/image/BitmapUtils.java
a89f24f891dbb155a343da6bde952e5292d65bec
[ "Apache-2.0" ]
permissive
yangnanhaohnhn/DevUtils
3f8619ad02eef9a298a5539f0b14f619efc2f3e5
c0e12d66f7788d9b49ea4167664661182e537a01
refs/heads/master
2020-04-10T21:46:29.693640
2018-12-11T07:52:07
2018-12-11T07:52:07
161,306,085
1
0
Apache-2.0
2018-12-11T09:00:53
2018-12-11T09:00:52
null
UTF-8
Java
false
false
15,010
java
package dev.utils.app.image; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.PixelFormat; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import dev.utils.LogPrintUtils; import dev.utils.app.AppUtils; import dev.utils.app.ScreenUtils; /** * detail: Bitmap工具类 * Created by Ttt */ public final class BitmapUtils { private BitmapUtils() { } // 日志Tag private static final String TAG = BitmapUtils.class.getSimpleName(); /** * 通过Resources获取Bitmap * @param context * @param resId * @return */ public static Bitmap getBitmapFromResources(Context context, int resId) { Resources res = context.getResources(); return BitmapFactory.decodeResource(res, resId); } /** * 通过Resources获取Drawable * @param context * @param resId * @return */ public static Drawable getDrawableFromResources(Context context, int resId) { Resources res = context.getResources(); return res.getDrawable(resId); } /** * 获取本地SDCard 图片 * @param fPath 图片地址 * @return */ public static Bitmap getSDCardBitmapStream(String fPath) { try { FileInputStream fis = new FileInputStream(new File(fPath));//文件输入流 Bitmap bmp = BitmapFactory.decodeStream(fis); return bmp; } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "getSDCardBitmapStream"); } return null; } /** * 获取本地SDCard 图片 * @param fPath 图片地址 * @return */ public static Bitmap getSDCardBitmapFile(String fPath) { try { Bitmap bmp = BitmapFactory.decodeFile(fPath); return bmp; } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "getSDCardBitmapFile"); } return null; } /** * 获取Bitmap * @param is * @return */ public static Bitmap getBitmap(final InputStream is) { if (is == null) return null; return BitmapFactory.decodeStream(is); } // ===== /** * Bitmay 转换成byte数组 * @param bitmap * @return */ public static byte[] bitmapToByte(Bitmap bitmap) { return bitmapToByte(bitmap, 100, Bitmap.CompressFormat.PNG); } /** * Bitmay 转换成byte数组 * @param bitmap * @param format * @return */ public static byte[] bitmapToByte(Bitmap bitmap, Bitmap.CompressFormat format) { return bitmapToByte(bitmap, 100, format); } /** * Bitmay 转换成byte数组 * @param bitmap * @param quality * @param format * @return */ public static byte[] bitmapToByte(Bitmap bitmap, int quality, Bitmap.CompressFormat format) { if (bitmap == null) { return null; } ByteArrayOutputStream o = new ByteArrayOutputStream(); bitmap.compress(format, quality, o); return o.toByteArray(); } // = /** * Drawable 转换成 byte数组 * @param drawable * @return */ public static byte[] drawableToByte(Drawable drawable) { return bitmapToByte(drawableToBitmap(drawable)); } /** * Drawable 转换成 byte数组 * @param drawable * @param format * @return */ public static byte[] drawableToByte(Drawable drawable, Bitmap.CompressFormat format) { return bitmapToByte(drawableToBitmap(drawable), format); } /** * Drawable 转换成 byte数组 * @param drawable * @return */ public static byte[] drawableToByte2(Drawable drawable) { return drawable == null ? null : bitmapToByte(drawable2Bitmap(drawable)); } /** * Drawable 转换成 byte数组 * @param drawable * @param format * @return */ public static byte[] drawableToByte2(Drawable drawable, Bitmap.CompressFormat format) { return drawable == null ? null : bitmapToByte(drawable2Bitmap(drawable), format); } // == /** * byte 数组转换为Bitmap * @param bytes * @return */ public static Bitmap byteToBitmap(byte[] bytes) { return (bytes == null || bytes.length == 0) ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } /** * Drawable 转换成 Bitmap * @param drawable * @return */ public static Bitmap drawableToBitmap(Drawable drawable) { return drawable == null ? null : ((BitmapDrawable) drawable).getBitmap(); } /** * Bitmap 转换成 Drawable * @param bitmap * @return */ public static Drawable bitmapToDrawable(Bitmap bitmap) { return bitmap == null ? null : new BitmapDrawable(AppUtils.getResources(), bitmap); } /** * byte数组转换成Drawable * @param bytes * @return */ public static Drawable byteToDrawable(byte[] bytes) { return bitmapToDrawable(byteToBitmap(bytes)); } /** * Drawable 转换 Bitmap * @param drawable The drawable. * @return bitmap */ public static Bitmap drawable2Bitmap(final Drawable drawable) { if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if (bitmapDrawable.getBitmap() != null) { return bitmapDrawable.getBitmap(); } } Bitmap bitmap; if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } /** * Drawable 转换 Bitmap * @param drawable The drawable. * @return bitmap */ public static Bitmap drawable3Bitmap(final Drawable drawable) { if (drawable == null){ return null; } Bitmap bitmap; if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } // === /** * 保存图片到SD卡 - JPEG * @param bitmap 需要保存的数据 * @param path 保存路径 * @param quality 压缩比例 */ public static boolean saveBitmapToSDCardJPEG(Bitmap bitmap, String path, int quality) { return saveBitmapToSDCard(bitmap, path, Bitmap.CompressFormat.JPEG, quality); } /** * 保存图片到SD卡 - PNG * @param bitmap 需要保存的数据 * @param path 保存路径 */ public static boolean saveBitmapToSDCardPNG(Bitmap bitmap, String path) { return saveBitmapToSDCard(bitmap, path, Bitmap.CompressFormat.PNG, 80); } /** * 保存图片到SD卡 - PNG * @param bitmap 需要保存的数据 * @param path 保存路径 * @param quality 压缩比例 */ public static boolean saveBitmapToSDCardPNG(Bitmap bitmap, String path, int quality) { return saveBitmapToSDCard(bitmap, path, Bitmap.CompressFormat.PNG, quality); } /** * 保存图片到SD卡 - PNG * @param bitmap 需要保存的数据 * @param path 保存路径 * @param quality 压缩比例 * @return */ public static boolean saveBitmapToSDCard(Bitmap bitmap, String path, int quality) { return saveBitmapToSDCard(bitmap, path, Bitmap.CompressFormat.PNG, quality); } /** * 保存图片到SD卡 * @param bitmap 图片资源 * @param path 保存路径 * @param format 如 Bitmap.CompressFormat.PNG * @param quality 保存的图片质量, 100 则完整质量不压缩保存 * @return 保存结果 */ public static boolean saveBitmapToSDCard(Bitmap bitmap, String path, Bitmap.CompressFormat format, int quality) { FileOutputStream fos = null; try { fos = new FileOutputStream(path); if (fos != null) { bitmap.compress(format, quality, fos); fos.close(); } } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "saveBitmapToSDCard"); return false; } finally { if(fos != null) { try { fos.close(); } catch (IOException e) { } } } return true; } // == /** * 将Drawable转化为Bitmap * @param drawable Drawable * @return Bitmap */ public static Bitmap getBitmapFromDrawable(Drawable drawable) { try { int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, drawable .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, width, height); drawable.draw(canvas); return bitmap; } catch (Exception e){ LogPrintUtils.eTag(TAG, e, "getBitmapFromDrawable"); } return null; } /** * 通过View, 获取背景转换Bitmap * @param view The view. * @return bitmap */ public static Bitmap bitmapToViewBackGround(View view) { if (view == null) return null; try { Bitmap ret = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(ret); Drawable bgDrawable = view.getBackground(); if (bgDrawable != null) { bgDrawable.draw(canvas); } else { canvas.drawColor(Color.WHITE); } view.draw(canvas); return ret; } catch (Exception e){ LogPrintUtils.eTag(TAG, e, "bitmapToViewBackGround"); } return null; } /** * 通过View, 获取Bitmap -> 绘制整个View * @param view View * @return Bitmap */ public static Bitmap getBitmapFromView(View view) { if (view == null) return null; try { Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom()); view.draw(canvas); return bitmap; } catch (Exception e){ LogPrintUtils.eTag(TAG, e, "getBitmapFromView"); } return null; } /** * 把一个View的对象转换成bitmap * @param view View * @return Bitmap */ public static Bitmap getBitmapFromView2(View view) { if (view == null) return null; try { view.clearFocus(); view.setPressed(false); // 能画缓存就返回false boolean willNotCache = view.willNotCacheDrawing(); view.setWillNotCacheDrawing(false); int color = view.getDrawingCacheBackgroundColor(); view.setDrawingCacheBackgroundColor(0); if (color != 0) { view.destroyDrawingCache(); } view.buildDrawingCache(); Bitmap cacheBitmap = view.getDrawingCache(); if (cacheBitmap == null) { return null; } Bitmap bitmap = Bitmap.createBitmap(cacheBitmap); // Restore the view view.destroyDrawingCache(); view.setWillNotCacheDrawing(willNotCache); view.setDrawingCacheBackgroundColor(color); return bitmap; } catch (Exception e){ LogPrintUtils.eTag(TAG, e, "getBitmapFromView2"); } return null; } // === /** * 计算视频宽高大小,视频比例xxx*xxx按屏幕比例放大或者缩小 * @param width 高度比例 * @param height 宽度比例 * @return 返回宽高 0 = 宽,1 = 高 */ public static int[] reckonVideoWidthHeight(float width, float height) { try { // 获取屏幕宽度 int sWidth = ScreenUtils.getScreenWidth(); // 判断宽度比例 float wRatio = 0.0f; // 计算比例 wRatio = (sWidth - width) / width; // 等比缩放 int nWidth = sWidth; int nHeight = (int) (height * (wRatio + 1)); return new int []{ nWidth, nHeight }; } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "reckonVideoWidthHeight"); } return null; } /** * 根据需求的宽和高以及图片实际的宽和高计算SampleSize * @param options * @param reqWidth * @param reqHeight * @return */ public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { int width = options.outWidth; int height = options.outHeight; int inSampleSize = 1; if (width > reqWidth || height > reqHeight) { int widthRadio = Math.round(width * 1.0f / reqWidth); int heightRadio = Math.round(height * 1.0f / reqHeight); inSampleSize = Math.max(widthRadio, heightRadio); } return inSampleSize; } // ================ ImageView 相关 ================== /** * 根据ImageView获适当的压缩的宽和高 * @param imageView * @return */ public static int[] getImageViewSize(ImageView imageView) { int[] imgSize = new int[] {0, 0}; // -- DisplayMetrics displayMetrics = imageView.getContext().getResources().getDisplayMetrics(); LayoutParams lp = imageView.getLayoutParams(); // 获取imageview的实际宽度 int width = imageView.getWidth(); if (width <= 0) { width = lp.width; // 获取imageview在layout中声明的宽度 } if (width <= 0) { // width = imageView.getMaxWidth(); // 检查最大值 width = getImageViewFieldValue(imageView, "mMaxWidth"); } if (width <= 0) { width = displayMetrics.widthPixels; } // -- // 获取imageview的实际高度 int height = imageView.getHeight(); if (height <= 0) { height = lp.height; // 获取imageview在layout中声明的宽度 } if (height <= 0) { height = getImageViewFieldValue(imageView, "mMaxHeight"); // 检查最大值 } if (height <= 0) { height = displayMetrics.heightPixels; } // -- imgSize[0] = width; imgSize[1] = height; return imgSize; } /** * 通过反射获取imageview的某个属性值 * @param object * @param fieldName * @return */ private static int getImageViewFieldValue(Object object, String fieldName) { int value = 0; try { Field field = ImageView.class.getDeclaredField(fieldName); field.setAccessible(true); int fieldValue = field.getInt(object); if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) { value = fieldValue; } } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "getImageViewFieldValue"); } return value; } /** * 获取图片宽度高度(不加载解析图片) * @param path * @return */ public static int[] getImageWidthHeight(String path){ BitmapFactory.Options options = new BitmapFactory.Options(); // 不解析图片信息 options.inJustDecodeBounds = true; // 此时返回的bitmap为null Bitmap bitmap = BitmapFactory.decodeFile(path, options); // options.outHeight为原始图片的高 return new int[]{options.outWidth,options.outHeight}; } }
[ "13798405957@163.com" ]
13798405957@163.com
129c3d744315def70d09560e63f41fc974f0f35f
13c2d3db2d49c40c74c2e6420a9cd89377f1c934
/program_data/JavaProgramData/69/1057.java
0ea63749d7b66244dd74a292834f57dd9bae47dd
[ "MIT" ]
permissive
qiuchili/ggnn_graph_classification
c2090fefe11f8bf650e734442eb96996a54dc112
291ff02404555511b94a4f477c6974ebd62dcf44
refs/heads/master
2021-10-18T14:54:26.154367
2018-10-21T23:34:14
2018-10-21T23:34:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,945
java
//==================================================================================================== //The Free Edition of C++ to Java Converter limits conversion output to 100 lines per snippet. //To purchase the Premium Edition, visit our website: //https://www.tangiblesoftwaresolutions.com/order/order-cplus-to-java.html //==================================================================================================== public class Node { public int num; public Node llink; public Node rlink; } package <missing>; public class GlobalMembers { /****???:???****/ /**??:2012?3?5?**/ /**??:1100012450****/ /**?????????*/ /**????????????**/ public static int count = 1; //?????create???print?? public static int x1 = 0; //C++ TO JAVA CONVERTER NOTE: Java has no need of forward class declarations: //struct Node; //???? public static Node createNullList_link() //????? { Node p = new Node(); if (p != null) { p.rlink = p.llink = null; } else { System.out.print("out of space!\n"); } return (p); } public static Node create() //???????? { //printf("????%d????\n",count); char c; //??????? int X = 0; Node p; p = createNullList_link(); p.rlink = null; while ((c = System.in.read()) != '\n') //??????????????????? { Node q = new Node(); if (q != null) { if (c == '-') { X = 1; continue; } if (X == 1) { q.num = -1 * (c - '0'); //??????????? } else { q.num = c - '0'; } q.rlink = p; q.llink = null; p.llink = q; p = q; } else { System.out.print("out of space!\n"); } } count++; //??????????? return (p); } public static void print(Node llist) //??????? { int x0 = 0; while (llist.rlink != null) { if (llist.num > 0 && llist.rlink.num < 0) //???????? { llist.num--; llist.rlink.num += 10; } if (llist.num == 0 && llist.rlink.num < 0) { System.out.print("-"); } if (x0 == 0 && llist.rlink.rlink != null && llist.num == 0 && x1 == 0) //?????????????0 { llist = llist.rlink; continue; } System.out.printf("%d",Math.abs(llist.num)); llist = llist.rlink; x0++; } } public static Node add(Node p1, Node p2, Node q) //???? { int Jw = 0; //???? int out = 0; //????????? while ((p1.rlink != null) || (p2.rlink != null)) { if ((p1.rlink != null) && (p2.rlink != null)) { out = p1.num + p2.num + Jw; p1 = p1.rlink; p2 = p2.rlink; } else if ((p1.rlink == null) && (p2.rlink != null)) //??1???????????2????1? { out = 0 + p2.num + Jw; p2 = p2.rlink; } else //??2???????????1????2? { out = p1.num + 0 + Jw; p1 = p1.rlink; } Jw = 0; Node p = new Node(); if (p == null) { System.out.print("out of space!\n"); } if (out > 0 || out == 0) { p.num = (out % 10); } else { p.num = -1 * ((-1 * out) % 10); } p.rlink = q; p.llink = null; q.llink = p; q = p; if (out > 0 || out == 0) { Jw = out / 10; } else if (out < (-1 * 9)) { Jw = -1; } } // printf("???????\n"); if (Jw == 1) { System.out.print("1"); x1 = 1; } //??????????1???????????? if (Jw == -1 && out != 0) { System.out.print("-1"); x1 = 1; } //????????????1??? else if (out < 0) { System.out.print("-"); //?? } return q; } public static void destroy1List_link(Node llist) //?????? { Node p; while (llist != null) { p = llist; llist = llist.rlink; p = null; } } //==================================================================================================== //End of the allowed output for the Free Edition of C++ to Java Converter. //To purchase the Premium Edition, visit our website: //https://www.tangiblesoftwaresolutions.com/order/order-cplus-to-java.html //====================================================================================================
[ "y.yu@open.ac.uk" ]
y.yu@open.ac.uk
97e45669cbccfad34becfac8c81d5d81dfb5063b
42639d1e3b47fabd6ab0c98b9ab77cb688acef68
/src/cn/edu/zucc/takeaway/ui/FrmSearch.java
3520414115e3db29fd6f0607b5f1bc84dc5966e7
[]
no_license
SilenceBoom/-31801092
537e2a8704b415baad307687125c84ccb7f29039
dab40cf4d220c2c3463f130774c03ac56dff6f5a
refs/heads/master
2022-11-17T13:15:05.845278
2020-07-15T03:09:32
2020-07-15T03:09:32
276,770,270
0
0
null
null
null
null
GB18030
Java
false
false
4,749
java
package cn.edu.zucc.takeaway.ui; import java.awt.BorderLayout; import java.awt.Button; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import cn.edu.zucc.takeaway.TakeAwayUtil; import cn.edu.zucc.takeaway.model.BeanMerchant; import cn.edu.zucc.takeaway.model.BeanPro; import cn.edu.zucc.takeaway.model.BeanProduct; import cn.edu.zucc.takeaway.model.BeanUser; import cn.edu.zucc.takeaway.util.BaseException; public class FrmSearch extends JDialog implements ActionListener{ private JPanel toolBar = new JPanel(); private Button btnAdd = new Button("添加"); private Button btnBuy = new Button("购物车"); List<BeanMerchant> merchant=null; private Object tblTitle[]=BeanMerchant.tableTitles; private Object tblData[][]; DefaultTableModel tabModel=new DefaultTableModel(); private JTable dataTable=new JTable(tabModel); private Object tblProTitle[]=BeanPro.tableTitles; private Object tblProData[][]; DefaultTableModel tabProModel=new DefaultTableModel(); private JTable dataTablePro=new JTable(tabProModel); List<BeanPro> product=null; private BeanMerchant curmer=null; public void reloadMerchant(){ try { merchant=TakeAwayUtil.merchantManager.loadall(); } catch (BaseException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } tblData = new Object[merchant.size()][BeanMerchant.tableTitles.length]; for(int i=0;i<merchant.size();i++){ for(int j=0;j<BeanMerchant.tableTitles.length;j++) tblData[i][j]=merchant.get(i).getCell(j); } tabModel.setDataVector(tblData,tblTitle); this.dataTable.validate(); this.dataTable.repaint(); } public void reloadProduct(int merIdx) { if(merIdx<0)return; curmer=merchant.get(merIdx); BeanMerchant.currentLogin=curmer; try { product=TakeAwayUtil.merchantManager.loadallP(curmer); }catch(BaseException e1) { JOptionPane.showMessageDialog(null, e1.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } tblProData =new Object[product.size()][BeanPro.tableTitles.length]; for(int i=0;i<product.size();i++){ for(int j=0;j<BeanPro.tableTitles.length;j++) tblProData[i][j]=product.get(i).getCell(j); } tabProModel.setDataVector(tblProData,tblProTitle); this.dataTablePro.validate(); this.dataTablePro.repaint(); } public FrmSearch(Frame f,String s,boolean b) { super(f,s,b); toolBar.setLayout(new FlowLayout(FlowLayout.RIGHT)); toolBar.add(this.btnBuy); toolBar.add(this.btnAdd); this.getContentPane().add(toolBar, BorderLayout.SOUTH); this.setSize(800, 520); // 屏幕居中显示 double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth(); double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight(); this.setLocation((int) (width - this.getWidth())/2, (int) (height - this.getHeight())/2 ); this.validate(); this.getContentPane().add(new JScrollPane(this.dataTable), BorderLayout.WEST); this.dataTable.addMouseListener(new MouseAdapter (){ @Override public void mouseClicked(MouseEvent e) { int i=FrmSearch.this.dataTable.getSelectedRow(); if(i<0) { return; } FrmSearch.this.reloadProduct(i); } }); this.getContentPane().add(new JScrollPane(this.dataTablePro), BorderLayout.CENTER); this.reloadMerchant(); this.btnBuy.addActionListener(this); this.btnAdd.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==this.btnBuy) { FrmBuy dlg=new FrmBuy(this,"购物车",true); dlg.setVisible(true); } if(e.getSource()==this.btnAdd) { int i=this.dataTablePro.getSelectedRow(); if(i<0) { JOptionPane.showMessageDialog(null, "请选择商品","提示",JOptionPane.ERROR_MESSAGE); return; } try { BeanPro p=product.get(i); TakeAwayUtil.userManager.Add(p); FrmAddPro dlg=new FrmAddPro(this,"选择数量",true); dlg.setVisible(true); } catch (Exception e1) { JOptionPane.showMessageDialog(null, e1.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } } } }
[ "noreply@github.com" ]
SilenceBoom.noreply@github.com
88b5c8f501f1ef38bada674e7dc0f53933cb1366
4721053f38206216e73fef1eae10d74635e966ac
/Droid/obj/Debug/android/src/md5b60ffeb829f638581ab2bb9b1a7f4f3f/EntryRenderer.java
37271210884b0fcca8492482f89e972e5eccfb49
[ "MIT" ]
permissive
rlingineni/Xamarin.Forms-ChatMessenger
b81c5a6abf48cbb4a757b28129caac43ddffc8bf
4423f468eef1bad17397fe43d85cbf464805af64
refs/heads/master
2021-01-19T17:37:38.383930
2017-10-25T03:42:21
2017-10-25T03:42:21
51,013,893
8
4
null
null
null
null
UTF-8
Java
false
false
4,375
java
package md5b60ffeb829f638581ab2bb9b1a7f4f3f; public class EntryRenderer extends md5b60ffeb829f638581ab2bb9b1a7f4f3f.ViewRenderer_2 implements mono.android.IGCUserPeer, android.text.TextWatcher, android.text.NoCopySpan, android.widget.TextView.OnEditorActionListener { static final String __md_methods; static { __md_methods = "n_afterTextChanged:(Landroid/text/Editable;)V:GetAfterTextChanged_Landroid_text_Editable_Handler:Android.Text.ITextWatcherInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" + "n_beforeTextChanged:(Ljava/lang/CharSequence;III)V:GetBeforeTextChanged_Ljava_lang_CharSequence_IIIHandler:Android.Text.ITextWatcherInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" + "n_onTextChanged:(Ljava/lang/CharSequence;III)V:GetOnTextChanged_Ljava_lang_CharSequence_IIIHandler:Android.Text.ITextWatcherInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" + "n_onEditorAction:(Landroid/widget/TextView;ILandroid/view/KeyEvent;)Z:GetOnEditorAction_Landroid_widget_TextView_ILandroid_view_KeyEvent_Handler:Android.Widget.TextView/IOnEditorActionListenerInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" + ""; mono.android.Runtime.register ("Xamarin.Forms.Platform.Android.EntryRenderer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", EntryRenderer.class, __md_methods); } public EntryRenderer (android.content.Context p0) throws java.lang.Throwable { super (p0); if (getClass () == EntryRenderer.class) mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.EntryRenderer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0 }); } public EntryRenderer (android.content.Context p0, android.util.AttributeSet p1, int p2) throws java.lang.Throwable { super (p0, p1, p2); if (getClass () == EntryRenderer.class) mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.EntryRenderer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", this, new java.lang.Object[] { p0, p1, p2 }); } public EntryRenderer (android.content.Context p0, android.util.AttributeSet p1) throws java.lang.Throwable { super (p0, p1); if (getClass () == EntryRenderer.class) mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.EntryRenderer, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0, p1 }); } public void afterTextChanged (android.text.Editable p0) { n_afterTextChanged (p0); } private native void n_afterTextChanged (android.text.Editable p0); public void beforeTextChanged (java.lang.CharSequence p0, int p1, int p2, int p3) { n_beforeTextChanged (p0, p1, p2, p3); } private native void n_beforeTextChanged (java.lang.CharSequence p0, int p1, int p2, int p3); public void onTextChanged (java.lang.CharSequence p0, int p1, int p2, int p3) { n_onTextChanged (p0, p1, p2, p3); } private native void n_onTextChanged (java.lang.CharSequence p0, int p1, int p2, int p3); public boolean onEditorAction (android.widget.TextView p0, int p1, android.view.KeyEvent p2) { return n_onEditorAction (p0, p1, p2); } private native boolean n_onEditorAction (android.widget.TextView p0, int p1, android.view.KeyEvent p2); java.util.ArrayList refList; public void monodroidAddReference (java.lang.Object obj) { if (refList == null) refList = new java.util.ArrayList (); refList.add (obj); } public void monodroidClearReferences () { if (refList != null) refList.clear (); } }
[ "Raviteja@Ravitejas-MacBook-Pro.local" ]
Raviteja@Ravitejas-MacBook-Pro.local
e5682679ffc04542cfe2485f5675577fc4240f3b
17df49e372003560c26ef0d0d4a4d95b9a201860
/src/main/java/com/works/entities/Customer.java
567c7a8a091c241b554e81ed458c6710d5023318
[ "MIT" ]
permissive
uumutaltin/Java-Spring-Security-MySql-RESTApi-Pet-Clinic
1668f8aa386f75d0f1b1bd53267091011c3d1826
3f4e726a822ebfd6aa31707936a7804d492743ad
refs/heads/main
2023-08-23T19:10:28.699404
2021-10-08T07:08:02
2021-10-08T07:08:02
414,633,412
0
0
null
null
null
null
UTF-8
Java
false
false
2,135
java
package com.works.entities; import io.swagger.annotations.ApiModel; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.List; @Entity @Data @ApiModel(value = "Müşteri Model",description = "Yeni Müşteri Ekleme için Kullanılır.") public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "cid", nullable = false) private Integer cid; @NotNull(message = "Customer cname NotNull") @NotEmpty(message = "Customer cname NotEmpty") private String cname; @NotNull(message = "Customer csurname NotNull") @NotEmpty(message = "Customer csurname NotEmpty") private String csurname; @NotNull(message = "Customer mobile_phone NotNull") @NotEmpty(message = "Customer mobile_phone NotEmpty") private String mobile_phone; @NotNull(message = "Customer email NotNull") @NotEmpty(message = "Customer email NotEmpty") @Column(unique = true) private String email; @NotNull(message = "Customer tax NotNull") private int tax; @NotNull(message = "Customer tax_administration NotNull") @NotEmpty(message = "Customer tax_administration NotEmpty") private String tax_administration; @NotNull(message = "Customer ctype NotNull") private int ctype; @NotNull(message = "Customer cnote NotNull") @NotEmpty(message = "Customer cnote NotEmpty") private String cnote; @NotNull(message = "Customer cprovince NotNull") @NotEmpty(message = "Customer cprovince NotEmpty") private String cprovince; @NotNull(message = "Customer cdistrict NotNull") @NotEmpty(message = "Customer cdistrict NotEmpty") private String cdistrict; @NotNull(message = "Customer caddress NotNull") @NotEmpty(message = "Customer caddress NotEmpty") private String caddress; @NotNull(message = "Customer cdiscount NotNull") private int cdiscount; @OneToMany(cascade = CascadeType.REMOVE) @NotNull(message = "Customer pets NotNull") private List<Pet> pets; }
[ "umutaltin60@gmail.com" ]
umutaltin60@gmail.com
cac8c2f67229cd4b628bb574302d8309e8e71692
1663c7dded858b7be875ed3a39014d5d93d45001
/src/controllers/EditServlet.java
75a61f0f8251ed28d57c01091573178de320b8ad
[]
no_license
tasku814/kadai-tasklist
1e54d15e6d3c17fa84bb1b846259f2f051956c9c
70b32658488477ecefa8ce4f298e78bb3f3dbcff
refs/heads/main
2023-03-16T02:46:37.274267
2021-03-12T19:29:50
2021-03-12T19:29:50
347,175,641
0
0
null
null
null
null
UTF-8
Java
false
false
1,750
java
package controllers; import java.io.IOException; import javax.persistence.EntityManager; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import models.Tasklist; import utils.DBUtil; /** * Servlet implementation class EditServlet */ @WebServlet("/edit") public class EditServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public EditServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EntityManager em = DBUtil.createEntityManager(); // 該当のIDのメッセージ1件のみをデータベースから取得 Tasklist t = em.find( Tasklist.class, Integer.parseInt( request.getParameter( "id" ))); em.close(); // メッセージ情報とセッションIDをリクエストスコープに登録 request.setAttribute( "tasks", t ); request.setAttribute( "_token", request.getSession().getId() ); // メッセージIDをセッションスコープに登録 request.getSession().setAttribute( "task_id", t.getId() ); RequestDispatcher rd = request.getRequestDispatcher( "/WEB-INF/views/tasklists/edit.jsp" ); rd.forward( request, response ); } }
[ "kt3934715@gmail.com" ]
kt3934715@gmail.com
eff3e77ad99dc066a0f611d8783303ede56f7a2e
475aefcda4abc0e83d89c0d3b9103463efe23bc6
/src/main/java/com/CabinetMedical/ws/repositories/VisiteRepository.java
792bf0b7644c2cd2311a7b68f5b988ca8eccd26d
[]
no_license
Mohammed-aziar/GestionCabientMedical
7d47de53e70eab6a9debe6dd56a4a228493c69e9
f7e483887449b06ba225ea12350769c27b186ca5
refs/heads/master
2023-05-29T16:10:23.814250
2021-06-16T15:38:23
2021-06-16T15:38:23
361,012,064
0
0
null
null
null
null
UTF-8
Java
false
false
797
java
package com.CabinetMedical.ws.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; import com.CabinetMedical.ws.entities.VisiteEntity; @Repository public interface VisiteRepository extends JpaRepository<VisiteEntity, Long> { VisiteEntity findByVisiteId(Long visiteId); @Query(value="SELECT COUNT(*) FROM visites v WHERE v.patient_id=:patientId",nativeQuery=true) int CountPatientId(@Param("patientId") Long patientId); @Query(value="SELECT * FROM visites v WHERE v.patient_id=:patientId",nativeQuery=true) List<VisiteEntity> findByPatientId(@Param("patientId") Long patientId); }
[ "mohammed.aziar@gmail.com" ]
mohammed.aziar@gmail.com
27fd607d461dad3ebacbae8c8058527560bf8359
86a4f4a2dc3f38c0b3188d994950f4c79f036484
/src/com/cbs/app/view/model/syncbak/SyncbakMarket$1.java
fbab957545f86dfc3271288b4fdbabac5b6dc310
[]
no_license
reverseengineeringer/com.cbs.app
8f6f3532f119898bfcb6d7ddfeb465eae44d5cd4
7e588f7156f36177b0ff8f7dc13151c451a65051
refs/heads/master
2021-01-10T05:08:31.000287
2016-03-19T20:39:17
2016-03-19T20:39:17
54,283,808
0
0
null
null
null
null
UTF-8
Java
false
false
555
java
package com.cbs.app.view.model.syncbak; import android.os.Parcel; import android.os.Parcelable.Creator; final class SyncbakMarket$1 implements Parcelable.Creator<SyncbakMarket> { public final SyncbakMarket createFromParcel(Parcel paramParcel) { return new SyncbakMarket(paramParcel); } public final SyncbakMarket[] newArray(int paramInt) { return new SyncbakMarket[paramInt]; } } /* Location: * Qualified Name: com.cbs.app.view.model.syncbak.SyncbakMarket.1 * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "reverseengineeringer@hackeradmin.com" ]
reverseengineeringer@hackeradmin.com
baaca19c9e6c5c4714dcb033e42e09ad0816d875
ad285105de0ab5042c2a86b8570b2f59658b88c4
/app/build/generated/source/apt/debug/com/zekunwang/happytweets/databinding/ContentProfileBinding.java
5360e552885765ba926a8ebe06f1cbd4bf5a7183
[ "MIT", "Apache-2.0" ]
permissive
ZekunWang/HappyTweets
a7ea084168227fa0b881b49963984ec713dd03a0
bbd7362f14178b8e80bf35a10a1a5baa731f14f8
refs/heads/master
2021-01-09T20:32:53.376322
2016-08-14T23:24:19
2016-08-14T23:24:19
65,523,396
1
1
null
null
null
null
UTF-8
Java
false
false
4,278
java
package com.zekunwang.happytweets.databinding; import com.zekunwang.happytweets.R; import com.zekunwang.happytweets.BR; import android.view.View; public class ContentProfileBinding extends android.databinding.ViewDataBinding { private static final android.databinding.ViewDataBinding.IncludedLayouts sIncludes; private static final android.util.SparseIntArray sViewsWithIds; static { sIncludes = null; sViewsWithIds = new android.util.SparseIntArray(); sViewsWithIds.put(R.id.viewpager, 1); } // views private final android.widget.RelativeLayout mboundView0; public final android.support.v4.view.ViewPager viewpager; // variables // values // listeners // Inverse Binding Event Handlers public ContentProfileBinding(android.databinding.DataBindingComponent bindingComponent, View root) { super(bindingComponent, root, 0); final Object[] bindings = mapBindings(bindingComponent, root, 2, sIncludes, sViewsWithIds); this.mboundView0 = (android.widget.RelativeLayout) bindings[0]; this.mboundView0.setTag(null); this.viewpager = (android.support.v4.view.ViewPager) bindings[1]; setRootTag(root); // listeners invalidateAll(); } @Override public void invalidateAll() { synchronized(this) { mDirtyFlags = 0x2L; } requestRebind(); } @Override public boolean hasPendingBindings() { synchronized(this) { if (mDirtyFlags != 0) { return true; } } return false; } public boolean setVariable(int variableId, Object variable) { switch(variableId) { case BR.user : return true; } return false; } public void setUser(com.zekunwang.happytweets.models.User user) { // not used, ignore } public com.zekunwang.happytweets.models.User getUser() { return null; } @Override protected boolean onFieldChange(int localFieldId, Object object, int fieldId) { switch (localFieldId) { } return false; } @Override protected void executeBindings() { long dirtyFlags = 0; synchronized(this) { dirtyFlags = mDirtyFlags; mDirtyFlags = 0; } // batch finished } // Listener Stub Implementations // callback impls // dirty flag private long mDirtyFlags = 0xffffffffffffffffL; public static ContentProfileBinding inflate(android.view.LayoutInflater inflater, android.view.ViewGroup root, boolean attachToRoot) { return inflate(inflater, root, attachToRoot, android.databinding.DataBindingUtil.getDefaultComponent()); } public static ContentProfileBinding inflate(android.view.LayoutInflater inflater, android.view.ViewGroup root, boolean attachToRoot, android.databinding.DataBindingComponent bindingComponent) { return android.databinding.DataBindingUtil.<ContentProfileBinding>inflate(inflater, com.zekunwang.happytweets.R.layout.content_profile, root, attachToRoot, bindingComponent); } public static ContentProfileBinding inflate(android.view.LayoutInflater inflater) { return inflate(inflater, android.databinding.DataBindingUtil.getDefaultComponent()); } public static ContentProfileBinding inflate(android.view.LayoutInflater inflater, android.databinding.DataBindingComponent bindingComponent) { return bind(inflater.inflate(com.zekunwang.happytweets.R.layout.content_profile, null, false), bindingComponent); } public static ContentProfileBinding bind(android.view.View view) { return bind(view, android.databinding.DataBindingUtil.getDefaultComponent()); } public static ContentProfileBinding bind(android.view.View view, android.databinding.DataBindingComponent bindingComponent) { if (!"layout/content_profile_0".equals(view.getTag())) { throw new RuntimeException("view tag isn't correct on view:" + view.getTag()); } return new ContentProfileBinding(bindingComponent, view); } /* flag mapping flag 0 (0x1L): user flag 1 (0x2L): null flag mapping end*/ //end }
[ "zwang172@gmail.com" ]
zwang172@gmail.com
75b006e2e0c4de1e518fd1c6ddac6e13c0d1cc80
0c3b1207b6cf44007362367271499083922a17d5
/modules/jaxb-xml-binding/geotk-xml-dif/src/main/java/org/geotoolkit/dif/xml/v102/MetadataAssociationType.java
e1835503131dd138f803c4c6e5727070f5c905f5
[]
no_license
ussegliog/geotoolkit
adcf3981a1812105d10d9f1bc0b480b7f47ad4d8
b0e360a7a344a9ab9b142d0714a3d7126dee04cb
refs/heads/master
2020-09-11T04:29:45.417741
2019-10-31T14:26:05
2019-10-31T14:26:05
221,937,196
0
0
null
2019-11-15T14:11:40
2019-11-15T14:11:39
null
UTF-8
Java
false
false
4,612
java
/* * Geotoolkit - An Open Source Java GIS Toolkit * http://www.geotoolkit.org * * (C) 2019, Geomatys * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotoolkit.dif.xml.v102; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * * | DIF 9 | ECHO 10 | UMM | DIF 10 | Notes | * | ------------ | --------------------- | ------------------- | --------------------- | -------------------------- | * | Parent_DIF | CollectionAssociation | MetadataAssociation | Metadata_Association | Added to match UMM | * | - | > ShortName | > EntryID/ShortName | > Entry_ID/Short_Name | | * | - | > VersionId | - | > Entry_ID/Version | Added to support ECHO | * | >type=Parent | > CollectionType | > Type | > Type | Made an enum | * | - | > CollectionUse | - | > Description | not candidate for markdown | * * * * <p>Classe Java pour MetadataAssociationType complex type. * * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType name="MetadataAssociationType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Entry_ID" type="{http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/}EntryIDType"/> * &lt;element name="Type" type="{http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/}MetadataAssociationTypeEnum"/> * &lt;element name="Description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MetadataAssociationType", propOrder = { "entryID", "type", "description" }) public class MetadataAssociationType { @XmlElement(name = "Entry_ID", required = true) protected EntryIDType entryID; @XmlElement(name = "Type", required = true) @XmlSchemaType(name = "string") protected MetadataAssociationTypeEnum type; @XmlElement(name = "Description") protected String description; /** * Obtient la valeur de la propriété entryID. * * @return * possible object is * {@link EntryIDType } * */ public EntryIDType getEntryID() { return entryID; } /** * Définit la valeur de la propriété entryID. * * @param value * allowed object is * {@link EntryIDType } * */ public void setEntryID(EntryIDType value) { this.entryID = value; } /** * Obtient la valeur de la propriété type. * * @return * possible object is * {@link MetadataAssociationTypeEnum } * */ public MetadataAssociationTypeEnum getType() { return type; } /** * Définit la valeur de la propriété type. * * @param value * allowed object is * {@link MetadataAssociationTypeEnum } * */ public void setType(MetadataAssociationTypeEnum value) { this.type = value; } /** * Obtient la valeur de la propriété description. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Définit la valeur de la propriété description. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } }
[ "guilhem.legal@geomatys.com" ]
guilhem.legal@geomatys.com
609f2010e644fa281392cf1dd5b07cc8e1f00ec1
0af8b92686a58eb0b64e319b22411432aca7a8f3
/single-large-project/src/main/java/org/gradle/test/performancenull_260/Productionnull_25921.java
8b6de37d0177fe4e93f537ae7928c86f7b1efeba
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
588
java
package org.gradle.test.performancenull_260; public class Productionnull_25921 { private final String property; public Productionnull_25921(String param) { this.property = param; } public String getProperty() { return property; } private String prop0; public String getProp0() { return prop0; } public void setProp0(String value) { prop0 = value; } private String prop1; public String getProp1() { return prop1; } public void setProp1(String value) { prop1 = value; } }
[ "cedric.champeau@gmail.com" ]
cedric.champeau@gmail.com
3855853918d4acb0a035d089f0f2d5604a9cc01b
4a2d329b8bf67685be72579108b93a8007e94e39
/LeetCode/src/main/java/indi/ours/algorithm/leetcode/algorithms/_812.java
4de4f0dd9508daa194b0b94d33321b86222f1cf1
[ "Apache-2.0" ]
permissive
HbnKing/Algorithm
12d374e2590b16a28820d5dfc74ffa341b440be3
35cd32c15b5eb58be190173e169d9414d2badc91
refs/heads/dev
2021-06-01T14:36:23.043579
2019-07-27T09:15:08
2019-07-27T09:15:08
149,637,477
3
1
Apache-2.0
2020-10-12T23:15:35
2018-09-20T16:18:26
Java
UTF-8
Java
false
false
1,427
java
package indi.ours.algorithm.leetcode.algorithms; /** * @author wangheng * @create 2018-12-18 下午12:34 * @desc * You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points. * * Example: * Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]] * Output: 2 * Explanation: * The five points are show in the figure below. The red triangle is the largest. * * 找出 构成三角形的最大面积 * **/ public class _812 { /** * 穷举法 * @param points * @return */ public double largestTriangleArea(int[][] points) { double max = 0; for(int i= 0 ; i<points.length ;i++){ for(int j = i+1 ; j<points.length;j++){ for(int k = j+1; k<points.length ;k++){ max = Math.max(max,getArea( i, j, k,points)); } } } return max; } public double getArea(int i ,int j ,int k,int[][] points){ //获取这三个点的坐标 int [] p1 = points[i]; int [] p2 = points[j]; int [] p3 = points[k]; double area = 0; area += area(p1, p2); area += area(p2, p3); area += area(p3, p1); return Math.abs(area); } double area(int[] p1, int[] p2) { int w = p2[0] - p1[0]; double h = (p1[1] + p2[1]) / 2.0; return w * h; } }
[ "hbn.king@gmail.com" ]
hbn.king@gmail.com
72717849a9194ee421fad60e40b51da68a349866
a285d476dc6898794bf9128c7505a4a63320e38f
/src/test/java/gbsio/esiclient/internal/domain/response/universe/AncestryImplTest.java
7a4077c9483de5830b7ae2b7dc0273a25304aab0
[ "MIT" ]
permissive
querns/esiclient
da1265ddcfb9fbdeaaf8914859f5f08216ebdca5
33031ba068b186e5e6716b29cc068ac60c9eb770
refs/heads/master
2020-03-27T20:07:10.718855
2018-09-02T00:04:04
2018-09-02T00:28:35
147,040,383
2
1
MIT
2018-09-13T09:55:41
2018-09-01T23:45:02
Java
UTF-8
Java
false
false
1,257
java
package gbsio.esiclient.internal.domain.response.universe; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableList; import gbsio.esiclient.api.domain.response.universe.Ancestry; import gbsio.esiclient.internal.json.JsonTestHarness; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*; class AncestryImplTest { @Test void parse() throws IOException { ImmutableList<Ancestry> list = JsonTestHarness.deserialize( getClass().getClassLoader().getResourceAsStream("json/domain/universe/ancestry.json"), new TypeReference<ImmutableList<Ancestry>>() { } ); assertEquals(1, list.size()); Ancestry ancestry = list.get(0); assertEquals(1, ancestry.getBloodlineID()); assertEquals("Acutely aware of the small population...", ancestry.getDescription()); assertEquals(12, ancestry.getID()); assertEquals("Tube Child", ancestry.getName()); assertTrue(ancestry.getShortDescription().isPresent()); assertEquals("Manufactured citizens of the State.", ancestry.getShortDescription().get()); assertFalse(ancestry.getIconID().isPresent()); } }
[ "querns@gbs.io" ]
querns@gbs.io
818cf93b08892f39d3b4bdc31c44d72c74c7d463
7941d6ed6d1f87954de73876c6d70b2b4b9e8a8c
/src/PART_I_Core/Day32/copy/GroceryListMain.java
84217a778115ff528bda5055c8a4379663606ab3
[]
no_license
Isso-Chan/Java-b13
d91524f41788882b85b8fa7ba69b770cd0042a98
a8d3697c7b8d77aba197077880b9657190da34a0
refs/heads/master
2022-11-14T05:47:48.062951
2020-07-02T11:23:43
2020-07-02T11:23:43
276,617,741
0
0
null
null
null
null
UTF-8
Java
false
false
2,479
java
package PART_I_Core.Day32.copy; import java.util.Scanner; public class GroceryListMain { static GroceryList groceryList=new GroceryList(); static Scanner scanner=new Scanner(System.in); public static void main(String[] args) { boolean quit=false; int choice=0; printInstructions(); while (!quit) { System.out.println("Enter your choice: "); choice=scanner.nextInt(); scanner.nextLine(); switch (choice) { case 0: printInstructions(); break; case 1: groceryList.printGroceryItem(); break; case 2: addItem(); break; case 3: modifyItem(); break; case 4: removeItem(); break; case 5: searchItem(); break; case 6: quit=true; break; default : printInstructions(); } } } public static void addItem() { System.out.println("Enter your grocery list"); groceryList.addGroceryItem(scanner.nextLine()); } public static void modifyItem() { System.out.println("Enter item number: "); int itemNo=scanner.nextInt(); scanner.nextLine();// yukarıda int olduğu için aşağıdaki string satırımı atlıyor malum. System.out.println("Enter replacacement item: "); String newItem=scanner.nextLine(); groceryList.modifyGroceryItem(itemNo-1,newItem);// itemNo sıfırdan başladığı için } public static void removeItem() { System.out.println("Enter item number: "); int itemNo = scanner.nextInt(); scanner.nextLine(); groceryList.removeGroceryItem(itemNo-1); } public static void searchItem() { System.out.println("Item to search for: "); String searchItem = scanner.nextLine(); if(groceryList.findItem(searchItem) != null) { System.out.println("Found " + searchItem + " in your grocery list"); }else { System.out.println(searchItem + " is not in the grocery list"); } } public static void printInstructions() { System.out.println("\nPress"); System.out.println("\t 0 - To print choice options."); System.out.println("\t 1 - To print the list of grocery items."); System.out.println("\t 2 - To add an item to the list."); System.out.println("\t 3 - To modify an item in the list."); System.out.println("\t 4 - To remove an item from the list."); System.out.println("\t 5 - To search an item from the list."); System.out.println("\t 6 - To quit the application."); } }
[ "ismailozcan73@gmail.com" ]
ismailozcan73@gmail.com
88428a5a0a2a02d5fd1194d49c4375974de5f6cf
7e306fc739a653c87ebdadfdef629ef06f1e4cff
/src/test/java/com/demoqa/pageObject/PageObject.java
05ee1d019c4b0c0c0d34fe816f9fcc9375237f1e
[]
no_license
amitaarya2016/demoqa
d7660455c102246079fddffaebbcd4db11703bea
6af2d9d629790e7b3249d9bec418bb0c3dd7e9dd
refs/heads/master
2020-03-29T04:22:34.504263
2018-09-20T03:02:24
2018-09-20T03:02:24
149,528,961
0
0
null
null
null
null
UTF-8
Java
false
false
244
java
package com.demoqa.pageObject; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; /** * @author amitaarya */ public interface PageObject { WebDriverWait getWait(); WebDriver getDriver(); }
[ "amita@influitive.com" ]
amita@influitive.com
73ca25fee7f754cb2cb8af108bc1f533527cafaa
be98b78b41803a65203ac067878ce9fb16d51901
/src/br/com/calculadora/Servidor.java
b14203ba5bf666aa8774609b01e4d4ef87dac45e
[]
no_license
BrunoRayan24/CalculadoraServer
cb4b65e9c2e55d822dbbd8836b984bea1c7c3cea
a999352fdbfd6c216a5c6fac81bda2e5499b6f81
refs/heads/master
2023-02-21T00:46:42.133001
2021-01-14T17:18:00
2021-01-14T17:18:00
329,677,331
0
0
null
null
null
null
UTF-8
Java
false
false
421
java
package br.com.calculadora; import javax.xml.ws.Endpoint; public class Servidor { public static void main(String[] args) { Endpoint.publish("http://127.0.0.1:9876/calc", new CalculadoraServerImpl()); System.out.println("------------------------------"); System.out.println("Servidor Iniciado: "); System.out.println("http://127.0.0.1:9876/calc"); System.out.println("------------------------------"); } }
[ "brunosantos1@unigranrio.br" ]
brunosantos1@unigranrio.br
37b63dcef6c56735f559963b0b9aa8dfface39ea
23872825a62b146cf503df191123468ef272656d
/src/main/java/com/nanokylin/justforwardserver/service/impl/database/MySQLDataBaseHighVersionImpl.java
1920f62895c5a92bea124e28ad20613f2c80c8c7
[]
no_license
DEGINX/JustForwardServer
ced17ad5b222af81927304a19db7a193a3ba92d4
2e4342ce82b0cb48fd088bdb7cb8c5f674ef4cdf
refs/heads/master
2023-01-30T10:14:31.567990
2020-12-16T10:31:36
2020-12-16T10:31:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,491
java
package com.nanokylin.justforwardserver.service.impl.database; import com.nanokylin.justforwardserver.service.DataBaseService; import com.nanokylin.justforwardserver.utils.LogUtil; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class MySQLDataBaseHighVersionImpl implements DataBaseService { @Override public Connection loadDataBase(String dataBaseName) { return null; } @Override public Connection loadDateBase(String dataBaseURL, String username, String password) { LogUtil log = new LogUtil(); log.info("[MYSQL][INFO] 安装的MySQL版本号高于8.0 正在尝试加载8.0以上兼容的JDBC"); try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(dataBaseURL, username, password); log.info("[MYSQL][INFO] 数据库加载成功"); return connection; } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return null; } @Override public void execute(Connection connection, String sql) { Statement statement; try { statement = connection.createStatement(); statement.executeUpdate(sql); statement.close(); connection.close(); } catch (SQLException exception) { exception.printStackTrace(); } } }
[ "3219065882@qq.com" ]
3219065882@qq.com
a7d7df816a2fc96d9ca868bb7ce5f942469bedf2
f1d10f2b2711cd5496b0fcc4298f6327aef95c71
/src/kosta/mvc/dto/MemberDTO.java
74097abbb8287542f6705ae338b5c0b2dea53235
[]
no_license
kkyun0823/ori_auction
29869b0b7d2acfb4886af982d6f4771923eaf139
f7bb37a533b5cb7f60f7918ba68970d1233a4eae
refs/heads/main
2023-05-23T18:17:02.327214
2021-07-10T09:34:01
2021-07-10T09:34:01
384,661,196
0
0
null
null
null
null
UTF-8
Java
false
false
2,718
java
package kosta.mvc.dto; public class MemberDTO { private String id; private String pw; private String name; private String account; private String addr; private String contact; private String email; private int memState; private String registDate; public MemberDTO(){} public MemberDTO(String id, String pw, String name, String account, String addr, String contact, String email, int memState, String registDate) { super(); this.id = id; this.pw = pw; this.name = name; this.account = account; this.addr = addr; this.contact = contact; this.email = email; this.memState = memState; this.registDate = registDate; } /** * 로그인 할때 필요한 생성자 */ public MemberDTO(String id, String pw) { super(); this.id = id; this.pw = pw; } /** * 로그인 할때 필요한 생성자2 */ public MemberDTO(String id, String pw, String name) { super(); this.id = id; this.pw = pw; this.name = name; } /** * 회원정보 수정할 때 필요한 생성자 */ public MemberDTO(String id, String pw, String account, String addr, String contact, String email) { super(); this.id = id; this.pw = pw; this.account = account; this.addr = addr; this.contact = contact; this.email = email; } /** * 회원조회할 때 필요한 생성자(관리자) */ public MemberDTO(String id, String name, String account, String addr, String contact, String email, int memState, String registDate) { super(); this.id = id; this.name = name; this.account = account; this.addr = addr; this.contact = contact; this.email = email; this.memState = memState; this.registDate = registDate; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPw() { return pw; } public void setPw(String pw) { this.pw = pw; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getMemState() { return memState; } public void setMemState(int memState) { this.memState = memState; } public String getRegistDate() { return registDate; } public void setRegistDate(String registDate) { this.registDate = registDate; } }
[ "kkyun0823@naver.com" ]
kkyun0823@naver.com
903e5af1c290c5cab93fe8f007d739c178efaa7e
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Time/4/org/joda/time/format/DateTimeFormatterBuilder_appendMinuteOfHour_704.java
333a456a6250434d0707fdc4c6d30a9afeaa17d4
[]
no_license
hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618255
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
2018-09-26T07:08:45
2018-09-26T07:08:44
null
UTF-8
Java
false
false
4,196
java
org joda time format factori creat complex instanc date time formatt datetimeformatt method call datetim format perform link date time formatt datetimeformatt class provid factori method creat formatt link date time format datetimeformat link iso date time format isodatetimeformat date time formatt builder datetimeformatterbuild construct formatt print pars formatt built append specif field formatt instanc builder formatt print month year januari construct pre date time formatt datetimeformatt month year monthandyear date time formatt builder datetimeformatterbuild append month year text appendmonthofyeartext append liter appendliter append year appendyear formatt toformatt pre date time formatt builder datetimeformatterbuild mutabl thread safe formatt build thread safe immut author brian neill o'neil author stephen colebourn author fredrik borgh date time format datetimeformat iso date time format isodatetimeformat date time formatt builder datetimeformatterbuild instruct printer emit numer minut hour minuteofhour field param min digit mindigit minimum number digit print date time formatt builder datetimeformatterbuild chain date time formatt builder datetimeformatterbuild append minut hour appendminuteofhour min digit mindigit append decim appenddecim date time field type datetimefieldtyp minut hour minuteofhour min digit mindigit
[ "hvdthong@gmail.com" ]
hvdthong@gmail.com
1a411148a28cb61d84ce2b4bd5445fd67efe46d9
d6cc3cc3ccc87d77a2dd0e766be6daeca7a7b748
/src/Command.java
cccb1dd1135d318adca73d37944b5a31bc32d10b
[]
no_license
johnLucious/parking_lot
2c4b70a8902aa75791ad07d42a397f4a670596e1
5eb0515eaf6968ae68f1b921ef198cda929912fd
refs/heads/master
2020-05-09T13:18:31.873921
2019-04-14T15:05:59
2019-04-14T15:05:59
181,146,749
0
0
null
null
null
null
UTF-8
Java
false
false
371
java
public class Command extends Main { private String[] args; private int argc; public Command(String[] args, int argc){ this.args = args; this.argc = argc; } public String getCommand(){ return this.args[0]; } public String[] getArgs(){ return this.args; } public int getArgc() { return this.argc; } }
[ "=" ]
=
36a8cc1b2aac506c6e308e98a67730ef6f1bd397
13b1fb7d7e06c1874513759523b58cb1988501be
/src/main/java/org/psjava/geometry/data/PointByYComparator.java
0b96faaf1fa9451f72434868370f9589f9a3c4cb
[ "MIT" ]
permissive
joelin14/psjava
dba073e510bf37b351d61475d4868fdda0cd3340
6819854679a5f53306e835441e79987fa57ee0b4
refs/heads/master
2021-01-18T10:27:48.744959
2013-10-01T07:26:14
2013-10-01T07:26:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
351
java
package org.psjava.geometry.data; import java.util.Comparator; public class PointByYComparator { public static <T> Comparator<Point2D<T>> create(final Comparator<T> comaprator) { return new Comparator<Point2D<T>>() { @Override public int compare(Point2D<T> p1, Point2D<T> p2) { return comaprator.compare(p1.y(), p2.y()); } }; } }
[ "abbajoa@gmail.com" ]
abbajoa@gmail.com
44bbc211e1d051e3fbf976320776e754de964853
da834b0cedf6cc1f516b910f0716f1ea051818bf
/src/main/java/com/plugram/logger/LogManager.java
a31a8a5e3f0b4211b01b98c881bc6de6efb1ea24
[]
no_license
tango238/Logger
51ce07876b4e302848173d7036b337cd2c7a1fea
f6709820a3002fb0089771ea4e3c46c0fdddd27b
refs/heads/master
2016-09-05T14:36:50.494413
2012-11-03T07:30:41
2012-11-03T07:30:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,447
java
package com.plugram.logger; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; public class LogManager { private static final String DEFAULT_NAME = "default"; private static LogManager manager; private static ConcurrentMap<String, AtomicReference<WeakReference<LoggerContext>>> contexts = new ConcurrentHashMap<String, AtomicReference<WeakReference<LoggerContext>>>(); static { manager = new LogManager(); WeakReference<LoggerContext> ref = new WeakReference<LoggerContext>(new LoggerContext(DEFAULT_NAME)); contexts.putIfAbsent(DEFAULT_NAME, new AtomicReference<WeakReference<LoggerContext>>(ref)); } public static LogManager getManager() { return manager; } public LoggerContext getLoggerContext() { return this.getLoggerContext(DEFAULT_NAME); } public LoggerContext getLoggerContext(String name) { AtomicReference<WeakReference<LoggerContext>> ref = contexts.get(name); if(ref == null){ LoggerContext ctx = new LoggerContext(name); WeakReference<LoggerContext> wr = new WeakReference<LoggerContext>(ctx); AtomicReference<WeakReference<LoggerContext>> r = new AtomicReference<WeakReference<LoggerContext>>(wr); contexts.putIfAbsent(name, r); ref = contexts.get(name); } LoggerContext context = ref.get().get(); context.start(); return context; } }
[ "tanago3@gmail.com" ]
tanago3@gmail.com
c763113e418ec89078b42f898cb1537dffa7cf5d
e0ce65ca68416abe67d41f340e13d7d7dcec8e0f
/src/main/java/org/trypticon/luceneupgrader/lucene5/internal/lucene/store/SimpleFSDirectory.java
09d7cdd3c7a19beb6fed62b9d168e34819b0a189
[ "Apache-2.0" ]
permissive
arandomgal/lucene-one-stop-index-upgrader
943264c22e6cadfef13116f41766f7d5fb2d3a7c
4c8b35dcda9e57f0507de48d8519e9c31cb8efb6
refs/heads/main
2023-06-07T04:18:20.805332
2021-07-05T22:28:46
2021-07-05T22:28:46
383,277,257
0
0
null
null
null
null
UTF-8
Java
false
false
5,514
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.trypticon.luceneupgrader.lucene5.internal.lucene.store; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.channels.ClosedChannelException; // javadoc @link import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.concurrent.Future; public class SimpleFSDirectory extends FSDirectory { public SimpleFSDirectory(Path path, LockFactory lockFactory) throws IOException { super(path, lockFactory); } public SimpleFSDirectory(Path path) throws IOException { this(path, FSLockFactory.getDefault()); } @Override public IndexInput openInput(String name, IOContext context) throws IOException { ensureOpen(); Path path = directory.resolve(name); SeekableByteChannel channel = Files.newByteChannel(path, StandardOpenOption.READ); return new SimpleFSIndexInput("SimpleFSIndexInput(path=\"" + path + "\")", channel, context); } static final class SimpleFSIndexInput extends BufferedIndexInput { private static final int CHUNK_SIZE = 16384; protected final SeekableByteChannel channel; boolean isClone = false; protected final long off; protected final long end; private ByteBuffer byteBuf; // wraps the buffer for NIO public SimpleFSIndexInput(String resourceDesc, SeekableByteChannel channel, IOContext context) throws IOException { super(resourceDesc, context); this.channel = channel; this.off = 0L; this.end = channel.size(); } public SimpleFSIndexInput(String resourceDesc, SeekableByteChannel channel, long off, long length, int bufferSize) { super(resourceDesc, bufferSize); this.channel = channel; this.off = off; this.end = off + length; this.isClone = true; } @Override public void close() throws IOException { if (!isClone) { channel.close(); } } @Override public SimpleFSIndexInput clone() { SimpleFSIndexInput clone = (SimpleFSIndexInput)super.clone(); clone.isClone = true; return clone; } @Override public IndexInput slice(String sliceDescription, long offset, long length) throws IOException { if (offset < 0 || length < 0 || offset + length > this.length()) { throw new IllegalArgumentException("slice() " + sliceDescription + " out of bounds: " + this); } return new SimpleFSIndexInput(getFullSliceDescription(sliceDescription), channel, off + offset, length, getBufferSize()); } @Override public final long length() { return end - off; } @Override protected void newBuffer(byte[] newBuffer) { super.newBuffer(newBuffer); byteBuf = ByteBuffer.wrap(newBuffer); } @Override protected void readInternal(byte[] b, int offset, int len) throws IOException { final ByteBuffer bb; // Determine the ByteBuffer we should use if (b == buffer) { // Use our own pre-wrapped byteBuf: assert byteBuf != null; bb = byteBuf; byteBuf.clear().position(offset); } else { bb = ByteBuffer.wrap(b, offset, len); } synchronized(channel) { long pos = getFilePointer() + off; if (pos + len > end) { throw new EOFException("read past EOF: " + this); } try { channel.position(pos); int readLength = len; while (readLength > 0) { final int toRead = Math.min(CHUNK_SIZE, readLength); bb.limit(bb.position() + toRead); assert bb.remaining() == toRead; final int i = channel.read(bb); if (i < 0) { // be defensive here, even though we checked before hand, something could have changed throw new EOFException("read past EOF: " + this + " off: " + offset + " len: " + len + " pos: " + pos + " chunkLen: " + toRead + " end: " + end); } assert i > 0 : "SeekableByteChannel.read with non zero-length bb.remaining() must always read at least one byte (Channel is in blocking mode, see spec of ReadableByteChannel)"; pos += i; readLength -= i; } assert readLength == 0; } catch (IOException ioe) { throw new IOException(ioe.getMessage() + ": " + this, ioe); } } } @Override protected void seekInternal(long pos) throws IOException { if (pos > length()) { throw new EOFException("read past EOF: pos=" + pos + " vs length=" + length() + ": " + this); } } } }
[ "ying.andrews@gmail.com" ]
ying.andrews@gmail.com
bfff988a060de15f2c1217c9da3c27c2f74d0816
dcb0e6cffe8911990cc679938b0b63046b9078ad
/editor/plugins/org.fusesource.ide.projecttemplates/src/org/fusesource/ide/projecttemplates/impl/simple/EmptyProjectTemplateForFuse71.java
15628fadabaec8aa772d2dabb4a764fe1527bfec
[]
no_license
MelissaFlinn/jbosstools-fuse
6fe7ac5f83d05df05d8884a8576b9af4baac3cd6
d960f4ed562da96a82128e0a9c04e122b9e9e8b0
refs/heads/master
2021-06-25T09:30:28.876445
2019-07-15T09:10:12
2019-07-29T08:12:28
112,379,325
0
0
null
2017-11-28T19:27:42
2017-11-28T19:27:42
null
UTF-8
Java
false
false
1,832
java
/******************************************************************************* * Copyright (c) 2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.fusesource.ide.projecttemplates.impl.simple; import org.fusesource.ide.camel.model.service.core.util.FuseBomFilter; import org.fusesource.ide.foundation.core.util.VersionUtil; import org.fusesource.ide.projecttemplates.adopters.configurators.MavenTemplateConfigurator; import org.fusesource.ide.projecttemplates.adopters.configurators.TemplateConfiguratorSupport; import org.fusesource.ide.projecttemplates.adopters.creators.TemplateCreatorSupport; import org.fusesource.ide.projecttemplates.util.CommonNewProjectMetaData; import org.fusesource.ide.projecttemplates.wizards.pages.model.EnvironmentData; public class EmptyProjectTemplateForFuse71 extends AbstractEmptyProjectTemplate { private static final String MINIMAL_COMPATIBLE_CAMEL_VERSION = "2.21.0.fuse-710"; @Override public TemplateConfiguratorSupport getConfigurator() { return new MavenTemplateConfigurator(FuseBomFilter.BOM_FUSE_71_KARAF); } @Override public TemplateCreatorSupport getCreator(CommonNewProjectMetaData projectMetaData) { return new BlankProjectCreator("7.1"); } @Override public boolean isCompatible(EnvironmentData environment) { return super.isCompatible(environment) && new VersionUtil().isStrictlyGreaterThan(environment.getCamelVersion(), MINIMAL_COMPATIBLE_CAMEL_VERSION); } }
[ "bfitzpat@redhat.com" ]
bfitzpat@redhat.com
a31ece5b8644565d5c78fdfd15647e60116436f1
e3eb00125a35950cb103aca085b1e3fec71fb0e0
/azure-mgmt-eventhub/src/main/java/com/microsoft/azure/management/eventhub/implementation/AuthorizationRuleBaseImpl.java
4edc6e92e89b2399c76e1154114be7ac920611cb
[ "MIT" ]
permissive
AutorestCI/azure-libraries-for-java
cefc78a0c47da086a34f5c3b9b742d91872c5cb0
e9b6d3f111856cb8509a5cfffcdb3366eb9f36c5
refs/heads/master
2021-04-15T09:52:41.051392
2018-03-23T18:18:31
2018-03-23T18:18:31
126,526,915
2
0
MIT
2018-10-10T16:48:13
2018-03-23T18:51:17
Java
UTF-8
Java
false
false
4,217
java
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.eventhub.implementation; import com.microsoft.azure.management.apigeneration.LangDefinition; import com.microsoft.azure.management.eventhub.AccessRights; import com.microsoft.azure.management.eventhub.AuthorizationRule; import com.microsoft.azure.management.eventhub.EventHubAuthorizationKey; import com.microsoft.azure.management.eventhub.KeyType; import com.microsoft.azure.management.resources.fluentcore.model.implementation.IndexableRefreshableWrapperImpl; import rx.Observable; import rx.functions.Func1; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Base implementation for authorization rule. * (Internal use only) * * @param <RuleT> rule fluent model * @param <RuleImpl> implementation of rule fluent model */ @LangDefinition abstract class AuthorizationRuleBaseImpl<RuleT extends AuthorizationRule<RuleT>, RuleImpl extends IndexableRefreshableWrapperImpl<RuleT, AuthorizationRuleInner>> extends NestedResourceImpl<RuleT, AuthorizationRuleInner, RuleImpl> implements AuthorizationRule<RuleT> { protected AuthorizationRuleBaseImpl(String name, AuthorizationRuleInner inner, EventHubManager manager) { super(name, inner, manager); } @Override public Observable<EventHubAuthorizationKey> getKeysAsync() { return this.getKeysInnerAsync() .map(new Func1<AccessKeysInner, EventHubAuthorizationKey>() { @Override public EventHubAuthorizationKey call(AccessKeysInner inner) { return new EventHubAuthorizationKeyImpl(inner); } }); } @Override public EventHubAuthorizationKey getKeys() { return getKeysAsync().toBlocking().last(); } @Override public Observable<EventHubAuthorizationKey> regenerateKeyAsync(KeyType keyType) { return this.regenerateKeysInnerAsync(keyType) .map(new Func1<AccessKeysInner, EventHubAuthorizationKey>() { @Override public EventHubAuthorizationKey call(AccessKeysInner inner) { return new EventHubAuthorizationKeyImpl(inner); } }); } @Override public EventHubAuthorizationKey regenerateKey(KeyType keyType) { return regenerateKeyAsync(keyType).toBlocking().last(); } @Override public List<AccessRights> rights() { if (this.inner().rights() == null) { return Collections.unmodifiableList(new ArrayList<AccessRights>()); } return Collections.unmodifiableList(this.inner().rights()); } @SuppressWarnings("unchecked") public RuleImpl withListenAccess() { if (this.inner().rights() == null) { this.inner().withRights(new ArrayList<AccessRights>()); } if (!this.inner().rights().contains(AccessRights.LISTEN)) { this.inner().rights().add(AccessRights.LISTEN); } return (RuleImpl) this; } @SuppressWarnings("unchecked") public RuleImpl withSendAccess() { if (this.inner().rights() == null) { this.inner().withRights(new ArrayList<AccessRights>()); } if (!this.inner().rights().contains(AccessRights.SEND)) { this.inner().rights().add(AccessRights.SEND); } return (RuleImpl) this; } @SuppressWarnings("unchecked") public RuleImpl withManageAccess() { withListenAccess(); withSendAccess(); if (!this.inner().rights().contains(AccessRights.MANAGE)) { this.inner().rights().add(AccessRights.MANAGE); } return (RuleImpl) this; } protected abstract Observable<AccessKeysInner> getKeysInnerAsync(); protected abstract Observable<AccessKeysInner> regenerateKeysInnerAsync(KeyType keyType); protected abstract Observable<AuthorizationRuleInner> getInnerAsync(); public abstract Observable<RuleT> createResourceAsync(); }
[ "noreply@github.com" ]
AutorestCI.noreply@github.com
53ec510f850a248f2917b79a4038e86c62f5eb05
66d52af3d50f77a33da90eacd618ee0310906c84
/pushClient/src/kr/co/adflow/push/MainActivity.java
9e2626a2637d00f3edfb20799f469ba13fcb7389
[]
no_license
adflowweb/mqtt
48bc8dfb6cc78525c92bca5097211eeaca1fd63f
6a2c55da97e0c08b632060be6d0fadac662be7ef
refs/heads/master
2021-06-08T22:04:09.715838
2015-10-26T08:02:22
2015-10-26T08:02:22
14,191,191
4
0
null
null
null
null
UTF-8
Java
false
false
9,484
java
package kr.co.adflow.push; import kr.co.adflow.push.handler.PushHandler; import kr.co.adflow.receiver.PushBroadcastReceiver; import kr.co.adflow.service.PushService; import kr.co.adflow.sqlite.PushDBHelper; import kr.co.adflow.sqlite.User; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.provider.Settings.Secure; import android.util.Log; import com.shortcutBadger.ShortcutBadgeException; import com.shortcutBadger.ShortcutBadger; import com.worklight.androidgap.WLDroidGap; /** * @author nadir93 * @date 2014. 6. 19. */ public class MainActivity extends WLDroidGap { // Debug TAG public static final String DEBUGTAG = "메인액티비티"; @Override public void onPause() { Log.d(DEBUGTAG, "onPause시작()"); super.onPause(); PushApp.activityPaused(); // refresh badge PushDBHelper pushDb = PushService.pushHandler.pushdb; Log.d(DEBUGTAG, "pushDb=" + pushDb); if (pushDb != null) { int badgeCount = pushDb.getUnreadCount(); try { ShortcutBadger.setBadge(this, badgeCount); Log.d(TAG, "뱃지를달았습니다.badgeCount=" + badgeCount); } catch (ShortcutBadgeException e) { e.printStackTrace(); } } Log.d(DEBUGTAG, "onPause종료()"); } @Override public void onResume() { Log.d(DEBUGTAG, "onResume시작()"); Bundle extras = getIntent().getExtras(); Log.d(DEBUGTAG, "intent::" + getIntent()); Log.d(DEBUGTAG, "extras::" + extras); // if (extras != null) { // Log.d(DEBUGTAG, "image::" + extras.get("image")); // } super.onResume(); PushApp.activityResumed(); // refresh super.loadUrl("javascript:andResumeFunction();"); Log.d(DEBUGTAG, "andResumeFunction호출됨"); Log.d(DEBUGTAG, "onResume종료()"); } @Override protected void onRestart() { Log.d(DEBUGTAG, "onRestart시작()"); super.onRestart(); Log.d(DEBUGTAG, "onRestart종료()"); } @Override protected void onStart() { Log.d(DEBUGTAG, "onStart시작()"); String deviceID = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID); Log.d(DEBUGTAG, "deviceID::" + deviceID); super.onStart(); Log.d(DEBUGTAG, "onStart종료()"); } @Override protected void onStop() { Log.d(DEBUGTAG, "onStop시작()"); super.onStop(); Log.d(DEBUGTAG, "onStop종료()"); } @Override public void onCreate(Bundle savedInstanceState) { Log.d(DEBUGTAG, "onCreate시작(bundle=" + savedInstanceState + ")"); super.onCreate(savedInstanceState); // this.appView.setWebViewClient(new WebViewClient() { // // public void onPageFinished(WebView view, String url) { // // do your stuff here // pageLoad = true; // Log.d(DEBUGTAG, "onPageFinished"); // } // }); onNewIntent(getIntent()); Log.d(DEBUGTAG, "onCreate종료()"); } @Override public void onNewIntent(Intent intent) { Log.d(DEBUGTAG, "onNewIntent시작(intent=" + intent + ")"); Bundle extras = intent.getExtras(); if (extras != null) { if (extras != null) { // Log.d(DEBUGTAG, "image::" + extras.get("image")); // super.loadUrl("javascript:$.mobile.changePage('#education',{transition:'slide'});"); Log.d(DEBUGTAG, "카테고리=" + extras.get("category")); super.loadUrl("javascript:refreshFunction('" + extras.get("category") + "');"); // super.loadUrl("javascript:loadEducation('" // + extras.get("image") + "');"); Log.d(DEBUGTAG, "리프레쉬호출됨"); // super.loadUrl("javascript:alert('hello');"); // webView.loadUrl("javascript:alert('hello');") } } Log.d(DEBUGTAG, "onNewIntent종료()"); } /** * onWLInitCompleted is called when the Worklight runtime framework * initialization is complete */ @Override public void onWLInitCompleted(Bundle savedInstanceState) { Log.d(DEBUGTAG, "onWLInitCompleted시작(bundle=" + savedInstanceState + ")"); super.loadUrl(getWebMainFilePath()); try { // /////임시코드 final PushDBHelper pushdb = new PushDBHelper(this); // pushdb.onUpgrade(pushdb.getWritableDatabase(), 0, 1); // for 이찬호 // User user = pushdb.getUser("chan"); // Log.d(TAG, "user" + user); // // if (user == null) { // try { // user = new User(); // user.setUserID("chan"); // // user.setPassword("passw0rd"); // // user.setTokenID("chantest"); // user.setCurrentUser(true); // pushdb.addUser(user); // Log.d(TAG, "임시유저가등록되었습니다. user=" + user); // } catch (Exception e) { // Log.e(TAG, "예외상황발생", e); // } // } // for 이찬호 end // for 1731124 User user = pushdb.getUser("nadir93"); Log.d(TAG, "user" + user); if (user == null) { try { user = new User(); user.setUserID("nadir93"); // user.setPassword("passw0rd"); user.setTokenID("08be01ba2e1f4e2e8216725"); user.setCurrentUser(true); pushdb.addUser(user); Log.d(TAG, "임시유저가등록되었습니다. user=" + user); } catch (Exception e) { Log.e(TAG, "예외상황발생", e); } } // for nadir93 end // 알람설정 Log.d(TAG, "헬스체크알람을설정합니다."); AlarmManager service = (AlarmManager) this .getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(this, PushBroadcastReceiver.class); i.setAction("kr.co.adflow.action.healthCheck"); PendingIntent pending = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); service.setInexactRepeating(AlarmManager.RTC_WAKEUP, 0, 1000 * PushHandler.alarmInterval, pending); Log.d(TAG, "헬스체크알람이설정되었습니다"); } catch (Exception e) { Log.e(DEBUGTAG, "에러발생", e); } // /////임시코드종료 Log.d(DEBUGTAG, "onWLInitCompleted종료()"); } @Override public void onDestroy() { Log.d(DEBUGTAG, "onDestroy시작()"); // System.out // .println("stopMqttClientService!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); // // use this to start and trigger a service // Intent i = new Intent(this, MqttClientService.class); // // potentially add data to the intent // i.putExtra("KEY1", "Value to be used by the service"); // stopService(i); super.onDestroy(); Log.d(DEBUGTAG, "onDestroy종료()"); } // // Debug TAG // public static final String TAG = "액티비티"; // // @Override // protected void onCreate(Bundle savedInstanceState) { // Log.d(TAG, "onCreate시작(bundle=" + savedInstanceState + ")"); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // if (savedInstanceState == null) { // getSupportFragmentManager().beginTransaction() // .add(R.id.container, new PlaceholderFragment()).commit(); // } // // // /////임시코드 // final PushDBHelper pushdb = new PushDBHelper(this); // pushdb.onUpgrade(pushdb.getWritableDatabase(), 0, 1); // final User user = new User(); // try { // // user.setUserID("nadir93"); // user.setPassword("passw0rd"); // user.setTokenID("08be01ba2e1f4e2e8216725"); // user.setCurrentUser(true); // pushdb.addUser(user); // Log.d(TAG, "임시유저가등록되었습니다. user=" + user); // // Button button = (Button) findViewById(R.id.button1); // // button.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View view) { // // user.setCurrentUser(false); // pushdb.updateUser(user); // user.setUserID("testUser"); // user.setCurrentUser(true); // user.setTokenID("1234567890"); // pushdb.addUser(user); // // // Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri // // .parse("http://www.mkyong.com")); // // startActivity(browserIntent); // } // }); // } catch (Exception e) { // Log.e(TAG, "예외상황발생", e); // } // // /////임시코드종료 // // // 알람설정 // Log.d(TAG, "헬스체크알람을설정합니다."); // AlarmManager service = (AlarmManager) this // .getSystemService(Context.ALARM_SERVICE); // Intent i = new Intent(this, PushBroadcastReceiver.class); // i.setAction("kr.co.adflow.action.healthCheck"); // PendingIntent pending = PendingIntent.getBroadcast(this, 0, i, // PendingIntent.FLAG_CANCEL_CURRENT); // service.setInexactRepeating(AlarmManager.RTC_WAKEUP, 0, // 1000 * PushHandler.alarmInterval, pending); // Log.d(TAG, "헬스체크알람이설정되었습니다"); // // Log.d(TAG, "onCreate종료()"); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // int id = item.getItemId(); // if (id == R.id.action_settings) { // return true; // } // return super.onOptionsItemSelected(item); // } // // /** // * A placeholder fragment containing a simple view. // */ // public static class PlaceholderFragment extends Fragment { // // public PlaceholderFragment() { // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View rootView = inflater.inflate(R.layout.fragment_main, container, // false); // return rootView; // } // } }
[ "nadir93@gmail.com" ]
nadir93@gmail.com
7dc20118e5d077860f6dd598c1d21b10cd32003d
be38173350bae8027707ce6c065bb995b90ce497
/staticpicverify_demo1_dwp/src/com/servlet/VerifyCodeServlet.java
a8b1a4fc4f720307ffcd7e6d22f2c0181d948653
[]
no_license
vanlyy/verifycode_component
47a7070fad9820891885f575e4e799c52136cd45
3105ffaa95bfb4161ffe51d327db3a48b06b3c57
refs/heads/master
2022-06-25T06:45:33.688451
2020-03-03T10:24:33
2020-03-03T10:24:33
244,604,651
0
0
null
2022-06-21T02:54:36
2020-03-03T10:17:48
Java
UTF-8
Java
false
false
1,021
java
package com.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.util.VerifyCodeUtils; public class VerifyCodeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String code = req.getParameter("code"); String key = (String) req.getSession().getAttribute("CODE"); if(code != null && code.equalsIgnoreCase(key)){ req.getSession().removeAttribute("CODE"); resp.getWriter().println(true); }else{ resp.getWriter().println(false); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doGet(req, resp); } }
[ "383878958@qq.com" ]
383878958@qq.com
8b092a7c1493eb1607c4d40ad056b4fa893aabfc
3874610de9c5a7371432322d175d84bc403ebbc1
/app/src/test/java/com/example/note_team_android_android/ExampleUnitTest.java
964a62b1a254ab1dc261ce9ee5b22cc58c1897f2
[]
no_license
jspreetkaur/Note_Team_Android_Android
67d9e2a80cf762ae8cf4496eefb7a39813cbe639
511ff725d797cf681cb18e1cd9b3783861899d9c
refs/heads/main
2023-06-09T22:22:41.787816
2021-06-18T12:19:26
2021-06-18T12:19:26
377,545,147
0
0
null
null
null
null
UTF-8
Java
false
false
398
java
package com.example.note_team_android_android; 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); } }
[ "jassaulakh.00@gmail.com" ]
jassaulakh.00@gmail.com
947b482e453aae761bcb3b84eaa229b476263f41
4a3fb28c181be627a7b7cb58de0ad23989a47d63
/src/test/java/hu/akarnokd/reactive4javaflow/tck/LimitTckTest.java
e2f760b4e2c8683978bcfccac745348bf9fde71c
[ "Apache-2.0" ]
permissive
akarnokd/Reactive4JavaFlow
b2d4ffcf035c9148d60a4375c7a9404a867319cf
a976aca7f8c16a097374df033d283780c7c37829
refs/heads/master
2023-02-04T08:36:10.625961
2022-12-01T08:29:56
2022-12-01T08:29:56
98,419,292
50
5
Apache-2.0
2023-01-30T04:03:08
2017-07-26T12:16:51
Java
UTF-8
Java
false
false
1,030
java
/* * Copyright 2017 David Karnok * * 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 hu.akarnokd.reactive4javaflow.tck; import hu.akarnokd.reactive4javaflow.Folyam; import org.reactivestreams.Publisher; import org.testng.annotations.Test; import java.util.concurrent.Flow; @Test public class LimitTckTest extends BaseTck<Integer> { @Override public Flow.Publisher<Integer> createFlowPublisher(long elements) { return Folyam.range(0, (int)elements * 2).limit(elements) ; } }
[ "akarnokd@gmail.com" ]
akarnokd@gmail.com
ec4ad30aae6ae65aac7c4745b4a9bdc1d4c5c816
9d1842674eae22b4bc07805b52a677671b6d9d2c
/mavenproject1-web/src/main/java/mb/MbKorisnik.java
eea0493f8d15b3c4fc7cbf6307189e26831de777
[ "MIT" ]
permissive
jelena927/tripping-tyrion
858a1858c44ff07e318af8a53df99bd2ec308bd3
85ea4edc1717cb4e9d9585e2e42a0b09094e6eb2
refs/heads/master
2021-01-19T03:13:01.896462
2015-03-11T23:09:50
2015-03-11T23:09:50
21,765,251
0
0
null
null
null
null
UTF-8
Java
false
false
2,142
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 mb; import ejb.KorisnikServiceBeanLocal; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import model.Korisnik; import model.Student; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import sequrity.LoginService; /** * * @author admin */ @ManagedBean(name = "mbKorisnik") @SessionScoped public class MbKorisnik { @EJB private KorisnikServiceBeanLocal korisnikServiceBean; public MbKorisnik(){ } public Korisnik nadjiPoMailu(String email){ try { return korisnikServiceBean.findUserByLoginName(email); } catch (Exception ex) { Logger.getLogger(MbKorisnik.class.getName()).log(Level.SEVERE, null, ex); } return null; } public void dodajStudenta(Student s){ try { korisnikServiceBean.dodajStudenta(s); } catch (Exception ex) { Logger.getLogger(MbKorisnik.class.getName()).log(Level.SEVERE, null, ex); } } public String koJeKorisnik(){ return SecurityContextHolder.getContext().getAuthentication().getName(); } public boolean daLiJeProfesor(){ String role = vratiTipKorisnika(); return role.contains(LoginService.ROLE_PROFESOR); } public String vratiTipKorisnika(){ Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext().getAuthentication().getAuthorities(); String role = ""; for(SimpleGrantedAuthority a: authorities){ role += a.getAuthority() + " "; } return role; } public Korisnik vratiKorisnika(){ return nadjiPoMailu(koJeKorisnik()); } }
[ "jelena927@gmail.com" ]
jelena927@gmail.com
f7fc6b6fea74ca22996ddf973c209619a21472d9
b61be34cfea5eabbf41b9ce03e523e70d431dc8e
/JUnit5Examples/src/test/java/com/howtodoinjava/junit5/examples/BeforeEachTest.java
5ed8926891ced3fb764b2220f9c95cfd305148a2
[ "Apache-2.0" ]
permissive
lokeshgupta1981/Junit5Examples
2ccc2e1189ee97664925851644db5ec8b9b33f9d
8d4148ef628a95b57fcdaf39d9a972793ba8fc9b
refs/heads/master
2022-10-17T23:51:37.833207
2022-10-07T12:08:46
2022-10-07T12:08:46
212,970,301
26
46
null
null
null
null
UTF-8
Java
false
false
856
java
package com.howtodoinjava.junit5.examples; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.RepetitionInfo; import org.junit.jupiter.api.TestInfo; public class BeforeEachTest { @DisplayName("Add operation test") @RepeatedTest(5) void addNumber(TestInfo testInfo, RepetitionInfo repetitionInfo) { System.out.println("Running test -> " + repetitionInfo.getCurrentRepetition()); Assertions.assertEquals(2, Calculator.add(1, 1), "1 + 1 should equal 2"); } @BeforeAll public static void init(){ System.out.println("BeforeAll init() method called"); } @BeforeEach public void initEach(){ System.out.println("BeforeEach initEach() method called"); } }
[ "howtodoinjava@gmail.com" ]
howtodoinjava@gmail.com
e4b28170a27fbc71e976166f27df651c78a60e6c
58dc57e2ad09efbce09ddfba86cde52289372fe5
/app/src/main/java/com/example/worldtest/ui/dashboard/finddiscover/NineGridLayoutManager.java
e097f4c9febda89a15bb670d83c3021b0eeeb0db
[]
no_license
jinyu9/world
a164f7ecdc7dc87a5e182a25e05182da116620d2
e67efab3b043a327982cf4bc783cec49a3083dd5
refs/heads/master
2021-05-23T00:48:08.411879
2020-05-06T02:01:53
2020-05-06T02:01:53
258,774,373
0
2
null
2020-04-30T10:16:54
2020-04-25T12:49:43
Java
UTF-8
Java
false
false
6,992
java
package com.example.worldtest.ui.dashboard.finddiscover; import android.content.Context; import android.graphics.Rect; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import androidx.recyclerview.widget.RecyclerView; /** * <p> * Package Name:org.loader.layoutmanager * </p> * <p> * Class Name:NineGridLayoutManager * <p> * Description:自定义九宫格LayoutManager类 * </p> * * @Author Martin * @Version 1.0 2018/10/29 9:42 AM Release * @Reviser: * @Modification Time:2018/10/29 9:42 AM */ public class NineGridLayoutManager extends RecyclerView.LayoutManager { private int gridSpacing;//gap private int mSpanCount = 3; //默认为3 private int maxImageSize = 9; public static final int STATE_ONE = 1;//1 public static final int STATE_FOUR = 4;//2*2 private int singleImageWidth; // 单张图片时的最大宽度,单位dp private int singleImageHeight; // 单张图片时的最大高度,单位dp private Pool<Rect> mCacheBorders; //用于规定Item显示的区域 private int itemWidth; private int itemHeight; public NineGridLayoutManager(Context context) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); gridSpacing = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, dm); singleImageWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 180, dm); singleImageHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 140, dm); mCacheBorders = new Pool<>(new Pool.New<Rect>() { @Override public Rect get() { return new Rect(); } }); } @Override public RecyclerView.LayoutParams generateDefaultLayoutParams() { return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } @Override public boolean isAutoMeasureEnabled() { return false; } /** * 测量RecyclerView控件的宽高 * @param recycler * @param state * @param widthSpec * @param heightSpec */ @Override public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) { super.onMeasure(recycler, state, widthSpec, heightSpec); if (getItemCount() <= 0 || state.isPreLayout()) { return; } int width = View.MeasureSpec.getSize(widthSpec);//不能直接用getWidth 可能获取 0 itemWidth = (width - getPaddingLeft() - getPaddingRight() - gridSpacing * (mSpanCount - 1)) / mSpanCount; itemHeight = itemWidth;//高度没问题 int childCount = getItemCount(); if (childCount < 0) { return; } int height = 0; if (childCount == 1) { height = singleImageHeight; } else if (childCount > 0 && childCount <= 3) { height = 1 * itemHeight; } else if (childCount > 3 && childCount <= 6) { height = 2 * itemHeight; } else if (childCount >6 && childCount <= 9){ height = 3 * itemHeight; } height += getPaddingTop()+getPaddingBottom();//TODO:解决 Padding问题 heightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY); super.onMeasure(recycler, state, widthSpec, heightSpec); } @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { super.onLayoutChildren(recycler, state); if (getItemCount() <= 0 || state.isPreLayout()) {//预布局状态不考虑 return; } if (state.getItemCount() == 0) { /* * 没有Item可布局,就回收全部临时缓存(参考自带的LinearLayoutManager) * 这里没有item,是指adapter里面的数据集 * 可能临时被清空了,但不确定何时还会继续添加回来。 */ removeAndRecycleAllViews(recycler); return; } //界面上的所有item都detach掉, 并缓存在scrap中,以便下次直接拿出来显示 detachAndScrapAttachedViews(recycler); layoutChunk(); fill(recycler); } /** * 测量 */ private void layoutChunk() { int childCount = getItemCount(); childCount = Math.min(childCount, maxImageSize); // 计算一下最大的条目数量 if (childCount <= 0) { return; } int cl = getPaddingLeft(); int ct = getPaddingTop(); switch (getItemCount()) { case STATE_ONE: for (int i = 0; i < getItemCount(); i++) { Rect item = mCacheBorders.get(i); item.set(cl, ct, cl + singleImageWidth, ct + singleImageHeight); } break; case STATE_FOUR: for (int i = 0; i < getItemCount(); i++) { Rect item = mCacheBorders.get(i); item.set(cl, ct, cl + itemWidth, ct + itemHeight); // 累加宽度 cl += itemWidth + gridSpacing; // 如果是换行 if ((i + 1) % 2 == 0) {//2*2 // 重置左边的位置 cl = getPaddingLeft(); // 叠加高度 ct += itemHeight + gridSpacing; } } break; default: for (int i = 0; i < getItemCount(); i++) { Rect item = mCacheBorders.get(i); item.set(cl, ct, cl + itemWidth, ct + itemHeight); // 累加宽度 cl += itemWidth + gridSpacing; // 如果是换行 if ((i + 1) % 3 == 0) {//3列 // 重置左边的位置 cl = getPaddingLeft(); // 叠加高度 ct += itemHeight + gridSpacing; } } break; } } /** * 填充 * * @param recycler */ private void fill(RecyclerView.Recycler recycler) { int itemSpecW; int itemSpecH; for (int i = 0; i < getItemCount(); i++) { Rect frame = mCacheBorders.get(i); View scrap = recycler.getViewForPosition(i); addView(scrap); itemSpecW = View.MeasureSpec.makeMeasureSpec(frame.width(), View.MeasureSpec.EXACTLY); itemSpecH = View.MeasureSpec.makeMeasureSpec(frame.height(), View.MeasureSpec.EXACTLY); scrap.measure(itemSpecW, itemSpecH); layoutDecorated(scrap, frame.left, frame.top, frame.right, frame.bottom); } } }
[ "1239886850@qq.com" ]
1239886850@qq.com
ec476ac3642e8eaaf2c661d99adefa168f13d1da
f8153963af4f5fd50d3b4483cf7e6534360d106e
/kun-metadata/kun-metadata-web/src/main/java/com/miotech/kun/metadata/web/controller/MSEController.java
b24de50f0bfe98931a39a06b9321c3d42cd73f38
[ "Apache-2.0" ]
permissive
hypmiotech/kun-scheduler
1c8409cd20f014ec1041d320657b46cabe751673
a53ced5b75ba49972350cc1b38f8bfac9ad1874d
refs/heads/master
2023-07-27T19:42:49.988414
2021-09-03T09:55:53
2021-09-03T09:55:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,081
java
package com.miotech.kun.metadata.web.controller; import com.google.inject.Inject; import com.google.inject.Singleton; import com.miotech.kun.commons.web.annotation.RequestBody; import com.miotech.kun.commons.web.annotation.RouteMapping; import com.miotech.kun.metadata.core.model.event.MetadataStatisticsEvent; import com.miotech.kun.metadata.databuilder.utils.JSONUtils; import com.miotech.kun.metadata.web.service.MSEService; import com.miotech.kun.workflow.core.model.taskrun.TaskRun; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class MSEController { private static final Logger logger = LoggerFactory.getLogger(MSEController.class); private MSEService mseService; @Inject public MSEController(MSEService mseService) { this.mseService = mseService; } @RouteMapping(url = "/mse/_execute", method = "POST") public TaskRun execute(@RequestBody MetadataStatisticsEvent mse) { logger.info("Prepare to execute mse task: {}", JSONUtils.toJsonString(mse)); return mseService.execute(mse); } }
[ "xinwei.zhang@mioying.com" ]
xinwei.zhang@mioying.com
b5951ef9cb18beb9be81dcb33e92016470827760
bd0e1885b04a5eabb35790384fcf8309d867d8f3
/common-kafka/src/main/java/br/com/alura/ecommerce/GsonSerializer.java
a0a8d402026aa871632cab2592f3d3bc7203218e
[]
no_license
augustoluiz/kafka-ecommerce
d7ab638b693cb6b4fe428ea4211717e4292e9542
12caa880f07118f9ce9d994eacb0c6ac648ea2f1
refs/heads/main
2023-02-11T13:43:55.457997
2021-01-05T03:03:45
2021-01-05T03:03:45
324,643,961
0
0
null
null
null
null
UTF-8
Java
false
false
383
java
package br.com.alura.ecommerce; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.kafka.common.serialization.Serializer; public class GsonSerializer<T> implements Serializer<T> { private final Gson gson = new GsonBuilder().create(); @Override public byte[] serialize(String s, T t) { return gson.toJson(t).getBytes(); } }
[ "augustogu7@yahoo.com.br" ]
augustogu7@yahoo.com.br
58b13f6017dfcbfb70f8cbf4e44b18faa2e92100
04b1803adb6653ecb7cb827c4f4aa616afacf629
/ui/android/junit/src/org/chromium/ui/AsyncViewProviderTest.java
37e04ef6b858fdbc70d0a8f4341d86624188c4da
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
Java
false
false
5,218
java
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.ui; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLooper; import org.chromium.base.ThreadUtils; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.ui.shadows.ShadowAsyncLayoutInflater; import java.util.concurrent.atomic.AtomicInteger; /** * Tests logic in the AsyncViewProvider class. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {ShadowAsyncLayoutInflater.class}) public class AsyncViewProviderTest { private LinearLayout mRoot; private AsyncViewStub mAsyncViewStub; private AsyncViewProvider<View> mAsyncViewProvider; private final AtomicInteger mEventCount = new AtomicInteger(); private static final int MAIN_LAYOUT_RESOURCE_ID = org.chromium.test.ui.R.layout.main_view; private static final int INFLATE_LAYOUT_RESOURCE_ID = org.chromium.test.ui.R.layout.inflated_view; private static final int STUB_ID = org.chromium.test.ui.R.id.view_stub; private static final int INFLATED_VIEW_ID = org.chromium.test.ui.R.id.inflated_view; private static final int PREINFLATED_VIEW_ID = org.chromium.test.ui.R.id.pre_inflated_view; @Before public void setUp() { mRoot = (LinearLayout) LayoutInflater.from(RuntimeEnvironment.application) .inflate(MAIN_LAYOUT_RESOURCE_ID, null); mAsyncViewStub = mRoot.findViewById(STUB_ID); mAsyncViewStub.setLayoutResource(INFLATE_LAYOUT_RESOURCE_ID); mAsyncViewStub.setShouldInflateOnBackgroundThread(true); mAsyncViewProvider = AsyncViewProvider.of(mAsyncViewStub, INFLATED_VIEW_ID); mAsyncViewStub.setId(STUB_ID); mEventCount.set(0); } @Test public void testCreatesUnloadedProviderIfNotInflated() { AsyncViewProvider provider = AsyncViewProvider.of(mAsyncViewStub, INFLATED_VIEW_ID); assertNull(provider.get()); } @Test public void testCreatesLoadedProviderIfInflated() { mAsyncViewStub.inflate(); ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); AsyncViewProvider provider = AsyncViewProvider.of(mAsyncViewStub, INFLATED_VIEW_ID); assertNotNull(provider.get()); } @Test public void testCreatesUnloadedProviderUsingResourceIds() { AsyncViewProvider provider = AsyncViewProvider.of(mRoot, STUB_ID, INFLATED_VIEW_ID); assertNull(provider.get()); } @Test public void testCreatesLoadedProviderUsingResourceIds() { mAsyncViewStub.inflate(); ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); AsyncViewProvider provider = AsyncViewProvider.of(mRoot, STUB_ID, INFLATED_VIEW_ID); assertNotNull(provider.get()); } @Test public void testCreatesLoadedProviderUsingResourceIdsWithoutAsyncViewStub() { AsyncViewProvider provider = AsyncViewProvider.of(mRoot, 0, PREINFLATED_VIEW_ID); assertNotNull(provider.get()); assertTrue(provider.get() instanceof ImageView); } @Test public void testRunsCallbackImmediatelyIfLoaded() { mAsyncViewStub.inflate(); ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); AsyncViewProvider<View> provider = AsyncViewProvider.of(mAsyncViewStub, INFLATED_VIEW_ID); assertEquals(mEventCount.get(), 0); provider.whenLoaded((View v) -> { mEventCount.incrementAndGet(); }); assertEquals(mEventCount.get(), 1); provider.whenLoaded((View v) -> { mEventCount.incrementAndGet(); }); assertEquals(mEventCount.get(), 2); } @Test public void testCallsListenersOnUiThread() { mAsyncViewProvider.whenLoaded((View v) -> { assertTrue(ThreadUtils.runningOnUiThread()); mEventCount.incrementAndGet(); }); mAsyncViewStub.inflate(); ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); // ensure callback gets called. assertEquals(mEventCount.get(), 1); } @Test public void testCallsListenersInOrder() { mAsyncViewProvider.whenLoaded( (View v) -> { assertEquals(mEventCount.incrementAndGet(), 1); }); mAsyncViewProvider.whenLoaded( (View v) -> { assertEquals(mEventCount.incrementAndGet(), 2); }); mAsyncViewProvider.whenLoaded( (View v) -> { assertEquals(mEventCount.decrementAndGet(), 1); }); assertEquals(mEventCount.get(), 0); mAsyncViewStub.inflate(); ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); assertEquals(mEventCount.get(), 1); } }
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
11d7b540830dcad96c29cc179be4dc089406f217
0f0a9ab0ee4b3b53b5088c1e26f067004573f79f
/src/main/java/nz/ac/victoria/ecs/kpsmart/util/ArrayUtils.java
b69434d3abf06f0289bbb4c1f37421cad272ccde
[]
no_license
danielhodder/SWEN301-Project
d6002a080923531df2e904f13c2bc53b5ea0d3de
cdadbacbd61f7715d603df9375e7e1189148f28a
refs/heads/master
2020-04-08T13:53:07.680004
2012-06-10T10:58:00
2012-06-10T10:58:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
218
java
package nz.ac.victoria.ecs.kpsmart.util; public class ArrayUtils { public static <T> boolean contains(T[] array, T element) { for (T elem : array) if (elem.equals(element)) return true; return false; } }
[ "danielhodder@gmail.com" ]
danielhodder@gmail.com
6885b74f9c5d6887b82eb86d62b54d34b35b749a
18ad29d3547d10a45211e99796acde41c8b264cb
/src/main/java/io/cryostat/util/RelativeURIException.java
017ab2809667e05177128c3fbcb6bfed9e28b8ef
[ "UPL-1.0" ]
permissive
geored/cryostat
fa6bb43d51fcb5c05598c1bddbbd3cd2bb549d27
450c822ef563018da75abd3e21e2757ddd8292ed
refs/heads/main
2023-08-26T15:08:25.955205
2021-10-13T18:21:22
2021-10-13T18:21:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,209
java
/* * Copyright The Cryostat Authors * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or data * (collectively the "Software"), free of charge and under any and all copyright * rights in the Software, and any and all patent rights owned or freely * licensable by each licensor hereunder covering either (i) the unmodified * Software as contributed to or provided by such licensor, or (ii) the Larger * Works (as defined below), to deal in both * * (a) the Software, and * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software (each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * The above copyright notice and either this complete permission notice or at * a minimum a reference to the UPL must be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.cryostat.util; import java.net.URI; import java.net.URISyntaxException; @SuppressWarnings("serial") public class RelativeURIException extends URISyntaxException { public RelativeURIException(URI u) { super(u.toString(), "Not a valid absolute URI"); } }
[ "noreply@github.com" ]
geored.noreply@github.com
cc6452cfefa9d57d7343fb8ecc9309df438e1f9b
1cd161604a3cbbd34f3c2259f2b217328590085e
/src/main/java/com/avonte/votingpolldemo/repository/OptionRepository.java
6f3e562dd75025e213a23ef7afa4d7d9842083cf
[]
no_license
avonteCannon/Angular-Poll-API
231fab74a4e30ec00713a37a034d2161fe0c4cbb
1338137d1ee6ec8504ee4af44928dfcf73fc15cc
refs/heads/master
2020-05-25T06:41:39.966618
2019-05-21T15:35:43
2019-05-21T15:35:43
187,671,777
0
0
null
null
null
null
UTF-8
Java
false
false
224
java
package com.avonte.votingpolldemo.repository; import com.avonte.votingpolldemo.Option; import org.springframework.data.repository.CrudRepository; public interface OptionRepository extends CrudRepository<Option, Long> { }
[ "acannon007@my.wilmu.edu" ]
acannon007@my.wilmu.edu
935d09f3ea180c7b73f84765ea56884cdcf43549
be3a0ed58af309b2d8f16bb622aba9f9333e88b9
/src/main/java/ru/oneicon/oi_spring_rest/exceptions/IconNotFoundException.java
b38662d06b8941320e504d4aacea698c4cd7e884
[]
no_license
alexl81/oi_spring_rest
5657882efa544077ef4059f146c3cd8292171163
dd1ed56eeb420ce51fb618fd93c818b0ff84a61d
refs/heads/master
2023-04-08T09:12:02.298698
2021-04-08T22:01:49
2021-04-08T22:01:49
355,333,135
0
0
null
null
null
null
UTF-8
Java
false
false
192
java
package ru.oneicon.oi_spring_rest.exceptions; public class IconNotFoundException extends RuntimeException { public IconNotFoundException(String message) { super(message); } }
[ "lapinalexandr@yandex.ru" ]
lapinalexandr@yandex.ru
4bf441c2438c8e07391fda818913e4087f2f963b
0219f308a7bb522cc197dc96ea9944e4b2112664
/spring-cloud-services/oms-provider-balance/src/main/java/com/lt/cloud/config/Settings.java
0f3d7c4d8120a4f1d6bd533f5ee6e99d01b81960
[]
no_license
mumushuiding/fznews
b683ac47dea52a539a685e27792569a96c3db2f4
f3984bbd309b48a614884708bd074f078ea45627
refs/heads/master
2020-04-13T03:37:54.191007
2018-12-27T09:17:06
2018-12-27T09:17:06
162,937,513
0
0
null
null
null
null
UTF-8
Java
false
false
202
java
package com.lt.cloud.config; public class Settings { public static final int NONE=0;//未平帐 public static final int COMPLETE=1;//已平帐 public static final int PART=0;//部分平帐 }
[ "lt@DESKTOP-15CCFE4" ]
lt@DESKTOP-15CCFE4
4522e2b96c624d80f6f68f72e055a7a6674cb39b
454c9827e6c9d3e001c239f80ee3a0dedf70501a
/kie-server-parent/kie-server-tests/kie-server-integ-tests-common/src/main/java/org/kie/server/integrationtests/category/Unstable.java
7b586f22b20c645e6affc735673b4b5cf4bb8dd2
[ "Apache-2.0" ]
permissive
jesuino/droolsjbpm-integration
cf53a3d75068f31a14c79946b46869da6bef0e3c
56f4eb229a25b0564d44a6b804c7951720a0d0f0
refs/heads/master
2021-11-22T13:00:07.013303
2020-09-29T09:08:43
2020-09-29T09:15:11
139,637,162
1
0
Apache-2.0
2021-08-16T20:31:06
2018-07-03T21:08:05
Java
UTF-8
Java
false
false
856
java
/* * Copyright 2016 JBoss by Red Hat. * * 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.kie.server.integrationtests.category; /** * Marks tests which are unstable and may cause false positives. * Instability can be caused by external factors - slow database connection, slow network and such. */ public interface Unstable { }
[ "swiderski.maciej@gmail.com" ]
swiderski.maciej@gmail.com
3af0a20cfe03e795b88b25f044f1e5eecc7fe0ad
88fa9edb8577e895a976ca84cb03d1b6e55dc867
/src/main/java/com/niit/tlc/crm/service/CustomerService.java
703b4165e4030aac59f3b5367fc4117ebcd12e37
[]
no_license
barwal1996/crmMVC
6a9ce2ef2aec61f13e260519be2af8aa5c695879
cbec85f64c2d92dddba28ff46aabc770f54db8c9
refs/heads/master
2022-12-23T05:39:56.195307
2020-04-01T11:42:22
2020-04-01T11:42:22
252,158,529
0
0
null
2022-12-16T15:31:33
2020-04-01T11:43:01
Java
UTF-8
Java
false
false
313
java
package com.niit.tlc.crm.service; import java.util.List; import com.niit.tlc.crm.Model.Customer; public interface CustomerService { public void saveCustomer(Customer theCustomer); public List<Customer> getCustomers(); public Customer getCustomer(int theId); public void deleteCustomer(int theId); }
[ "tamit700@gmail.com" ]
tamit700@gmail.com
b339a4fad33559bc5d4a400d9fe849a136fb15b1
6dd0204fe4aac0d3538fcbfc168f73ca299f3025
/src/com/pallav/karrierexample/LoginDataBaseAdapter.java
785ba5af77db0848d588bf0fbf0f2d26519b75d1
[]
no_license
pallav17/Android_sample
02da72d81ba2f67cf068a5e81c54b91fef4ed961
0b8fd309313f99854c0ae95c3946be2f6e9388e6
refs/heads/master
2020-05-16T22:56:25.146133
2015-07-06T21:35:35
2015-07-06T21:35:35
38,647,515
0
0
null
null
null
null
UTF-8
Java
false
false
8,670
java
package com.pallav.karrierexample; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import android.widget.Toast; public class LoginDataBaseAdapter { static final String DATABASE_NAME = "login.db"; static final int DATABASE_VERSION = 1; public static final int NAME_COLUMN = 1; // TODO: Create public field for each column in your table. // SQL Statement to create a new database. static final String DATABASE_CREATE = "create table LOGIN " + "( ID integer primary key autoincrement, USERNAME text unique,PASSWORD text, LATITUDE text, LONGITUDE text, ADDRESS text)"; // Variable to hold the database instance public SQLiteDatabase db; // Context of the application using the database. private final Context context; // Database open/upgrade helper private DataBaseHelper dbHelper; public String password; public String userName,address; public LoginDataBaseAdapter(Context _context) { context = _context; dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION); } public LoginDataBaseAdapter open() throws SQLException { db = dbHelper.getWritableDatabase(); return this; } public void close() { db.close(); } public SQLiteDatabase getDatabaseInstance() { return db; } public boolean checkEvent(String userName) { SQLiteDatabase db = this.getDatabaseInstance(); Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null); if(cursor.moveToFirst()) return true; //row exists else return false; } public void insertEntry(String userName,String password) { // Assign values for each row. if(checkEvent(userName)) { Toast.makeText(context,"Account already exists",Toast.LENGTH_LONG).show(); } else { ContentValues newValues = new ContentValues(); newValues.put("USERNAME", userName); newValues.put("PASSWORD",password); db.insert("LOGIN", null, newValues); Toast.makeText(context, "Account Successfully Created ", Toast.LENGTH_LONG).show(); } } //} public void insertDetails(Double latitude,Double longitude, String address) { ContentValues newDetails = new ContentValues(); newDetails.put("LONGITUDE",longitude); newDetails.put("ADDRESS",address); newDetails.put("LATITUDE", latitude); db.insert("LOGIN",null, newDetails); Toast.makeText(context, "Details inserted succesfully", Toast.LENGTH_LONG).show(); } public String getSinlgeEntry(String userName) { Cursor cursor=db.query("LOGIN", null, "USERNAME ='"+userName+"'", null, null, null, null); String password = ""; if(cursor.getCount() > 0) // UserName Not Exist { cursor.moveToFirst(); password = cursor.getString(cursor.getColumnIndex("PASSWORD")); return password; } return "NOT EXIST"; } public boolean updateData(String userName,String password, Double latitude, Double longitude, String address) { db = dbHelper.getWritableDatabase(); // Define the updated row content. ContentValues updatedValues = new ContentValues(); // Assign values for each row. updatedValues.put("USERNAME", userName); updatedValues.put("PASSWORD",password); updatedValues.put("LATITUDE",latitude); updatedValues.put("LONGITUDE",longitude); updatedValues.put("ADDRESS",address); String where="USERNAME = ?"; //int i = db.update("LOGIN",updatedValues, where, new String[]{userName}); Toast.makeText(context, "Account Successfully updated", Toast.LENGTH_LONG).show(); // return db.update("LOGIN",updatedValues, where, new String[]{userName})!= 0; return db.update("LOGIN",updatedValues, null,null)!= 0; } /* public class PostDataAsyncTask extends AsyncTask<String, String, String> { protected void onPreExecute() { super.onPreExecute(); // do stuff before posting data } @Override protected String doInBackground(String... strings) { try { // 1 = post text data, 2 = post file int actionChoice = 2; // post a text data if(actionChoice==1){ postText(); } // post a file else{ postFile(); } } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(String lenghtOfFile) { // do stuff after posting data } } // this will post our text data private void postText(){ try{ // url where the data will be posted String postReceiverUrl = "http://192.168.0.102/post_data_receiver.php"; // HttpClient HttpClient httpClient = new DefaultHttpClient(); // post header HttpPost httpPost = new HttpPost(postReceiverUrl); // add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("Username", userName)); nameValuePairs.add(new BasicNameValuePair("password", password)); nameValuePairs.add(new BasicNameValuePair("latitude", lat)); nameValuePairs.add(new BasicNameValuePair("longitude", lon)); nameValuePairs.add(new BasicNameValuePair("address", address)); // execute HTTP post request HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String responseStr = EntityUtils.toString(resEntity).trim(); // you can add an if statement here and do other actions based on the response } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void postFile(){ try{ // the file to be posted String textFile = Environment.getExternalStorageDirectory() + "/sample.txt"; // the URL where the file will be posted String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php"; Log.v(null, "postURL: " + postReceiverUrl); // new HttpClient HttpClient httpClient = new DefaultHttpClient(); // post header HttpPost httpPost = new HttpPost(postReceiverUrl); File file = new File(textFile); FileBody fileBody = new FileBody(file); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("file", fileBody); httpPost.setEntity(reqEntity); // execute HTTP post request HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String responseStr = EntityUtils.toString(resEntity).trim(); // you can add an if statement here and do other actions based on the response } } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }*/ }
[ "pallav.shah78@gmail.com" ]
pallav.shah78@gmail.com
7c1dd73ff30ac3a320902c836e09351480e92fa3
edea52735f46a3cdb0a8c396c8bf324720f58777
/2013-OOProgrammingWithJava-PART1/week4-074.Multiplier/src/Multiplier.java
7f2e9d54f8a68bff83489e2c26524f04a2dae207
[]
no_license
AndreiCatinas/mooc.fi
78aa600ede32eb301c145a9a75b99240eeea0113
8ffb3c4b5aeeff26755ce0729b8951f3786ade33
refs/heads/master
2021-07-08T17:30:03.366117
2017-10-03T15:11:17
2017-10-03T15:11:17
105,665,851
0
0
null
null
null
null
UTF-8
Java
false
false
428
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. */ /** * * @author Andrei */ public class Multiplier { private int nb; public Multiplier(int number) { this.nb = number; } public int multiply(int otherNumber) { return this.nb * otherNumber; } }
[ "andrey.catinas@yahoo.com" ]
andrey.catinas@yahoo.com
109510fb6ba74cc4b1079c2068126926abb27066
3b3563b6b980d9829b12bcab9eb2d5af257a8c41
/AndroidTrainingFramework-AF/externals/AndroidFramework/java/installer/Downloader.java
e38de0e814ff0f9fd37e53851bbd54852f8ccaf8
[]
no_license
dunkbing/l3arn_cpp
fe1ea628fe413bba4a51f8cfa8b37c3b9d16c581
a0e1bba83934b0d0e571e661927c006c35fb1ce9
refs/heads/master
2023-07-14T16:24:55.734138
2021-08-26T13:17:38
2021-08-26T13:17:38
344,770,327
0
0
null
null
null
null
UTF-8
Java
false
false
7,120
java
//#if USE_DOWNLOAD_MANAGER package APP_PACKAGE.installer.utils; import android.util.Log; import java.util.Vector; import java.util.ArrayList; import APP_PACKAGE.GLUtils.ZipFile; import APP_PACKAGE.installer.GameInstaller; import APP_PACKAGE.installer.ToastMessages; import java.net.URL; public class Downloader implements Defs { public String m_strDataLink = ""; public String m_strOutputPath = ""; public long m_RequiredSize = 0; public int m_lGlobalOffset = 0; public boolean m_isDownloadCompleted; public boolean m_isDownloadFailed; public static boolean m_isPaused; ArrayList<Section> m_pSections; Vector<PackFile> m_RequiredResources; private int m_TotalSections = 0; private int m_UsedThreads = 0; private final int MIN_SIZE_PER_SECTION = 1<<20; public Downloader(String strDataLink, String strOutputPath, Vector<PackFile> rRes, int gbOff, long reqSize) { m_lGlobalOffset = gbOff; m_RequiredResources = rRes; m_strDataLink = strDataLink; m_strOutputPath = strOutputPath; m_RequiredSize = reqSize; try { initialize(); } catch (Exception e) { ERR("Downloader","Initialize error!"); DBG_EXCEPTION(e); ERR_TOAST(ToastMessages.Downloader.InitializeError); m_isDownloadFailed = true; } } public void retryDownload( Vector<PackFile> rRes) { m_RequiredResources = rRes; m_isDownloadFailed = false; //m_CurrentFileIdx = 0; try { initialize(); } catch (Exception e) { ERR("GameInstaller","Retry Initialize error!"); DBG_EXCEPTION(e); ERR_TOAST(ToastMessages.Downloader.InitializeRetryError); m_isDownloadFailed = true; } } public void setGlobalOffset(int gbOff) { m_lGlobalOffset = gbOff; } public void initialize() throws Exception { if(m_RequiredResources != null && m_RequiredResources.size() > 0) { setFileForDownload(); m_isDownloadCompleted = false; m_isPaused = false; } else throw new Exception(); } public void setFileForDownload() { m_UsedThreads = 0; long sectionSize = m_RequiredSize / MAX_DOWNLOAD_THREADS; if (MAX_SECTION_SIZE * 1024 * 1024 < sectionSize) sectionSize = MAX_SECTION_SIZE * 1024 * 1024; splitSections(sectionSize); } public String getOutputFileName() { return m_strOutputPath + "/" + JOINED_FILE_NAME; } public void start() { if (m_isDownloadFailed) { return; } try { int threadsToStart = (m_TotalSections < MAX_DOWNLOAD_THREADS)? m_TotalSections:MAX_DOWNLOAD_THREADS; for (int i = 0; i < threadsToStart; i++) { DBG("Downloader", "Start new thread: " + (m_UsedThreads + 1) + " out of " + m_TotalSections + " sections needed"); m_pSections.get(i).start(); m_UsedThreads++; } } catch (Exception e) { DBG_EXCEPTION(e); ERR_TOAST(ToastMessages.Downloader.StartThreadError); m_isDownloadFailed = true; } } public void update() { if (m_isDownloadFailed) { this.stopDownload(); return; } int finishedThreads = 0; int failedSections = 0; for (int i = 0; i < m_TotalSections; i++) { if (m_pSections.get(i).isUncompleted()) { if (m_pSections.get(i).hasRetriesLeft()) { m_pSections.get(i).stopThread(); m_pSections.set(i, new Section(m_pSections.get(i))); m_pSections.get(i).start(); DBG("Downloader", "Restart Section: " + i + " out of " + m_TotalSections + " sections needed"); } else { failedSections++; } } else if (m_pSections.get(i).isFinished()) { finishedThreads++; } } if (failedSections > 0 && failedSections + finishedThreads == m_TotalSections) { m_isDownloadFailed = true; this.stopDownload(); return; } if (m_UsedThreads - (failedSections + finishedThreads) < MAX_DOWNLOAD_THREADS && m_UsedThreads < m_TotalSections) { DBG("Downloader", "Start new thread: " + (m_UsedThreads + 1) + " out of " + m_TotalSections + " sections needed"); m_pSections.get(m_UsedThreads).start(); m_UsedThreads++; } if ((failedSections + finishedThreads) < m_TotalSections) return; DBG("Downloader","file Downloading completed!"); m_isDownloadCompleted = true; } public void stopDownload() { try { for (int i = 0; i < m_pSections.size(); i++) { DBG("Downloader", "Stop section thread: " + (i + 1) + " out of " + m_pSections.size()); if (m_pSections.get(i) != null) m_pSections.get(i).stopThread(); } } catch (Exception e) { DBG_EXCEPTION(e); ERR_TOAST(ToastMessages.Downloader.StopError); m_isDownloadFailed = true; } } public long getDownloadedSize() { long totalSize = 0; for (int i = 0; i < m_TotalSections; i++) { totalSize += m_pSections.get(i).getSize(); } return totalSize; } public int getDownloadedFiles() { int totalFiles = 0; for (int i = 0; i < m_TotalSections; i++) { totalFiles += m_pSections.get(i).getFilesCompleted(); } return totalFiles; } public void pause() { m_isPaused = true; } public void resume() { m_isPaused = false; } public void splitSections(long maxChunkSize) { m_pSections = new ArrayList<Section>(); m_TotalSections = 0; if (m_RequiredResources.size() == 0) return; Section tmpSection; Vector<PackFile> sectionPackFiles = new Vector<PackFile>(); int lastID = m_RequiredResources.get(0).getID(); int totalSizeCompressed = m_RequiredResources.get(0).getZipLength(); sectionPackFiles.add(m_RequiredResources.get(0)); // final HttpClient chttp = new HttpClient(); // m_strDataLink = chttp.GetRedirectedUrl(m_strDataLink); // chttp.close(); String name = ""; // Horrible code: Find sequential chunks of needed files for (int i=1; i<m_RequiredResources.size(); i++) { // Files are sequential if (lastID + 1 == m_RequiredResources.get(i).getID() && totalSizeCompressed < maxChunkSize) { sectionPackFiles.add(m_RequiredResources.get(i)); totalSizeCompressed += m_RequiredResources.get(i).getZipLength(); } else { tmpSection = new Section(m_strDataLink, m_strOutputPath, sectionPackFiles, m_lGlobalOffset, m_pSections.size()); m_pSections.add(tmpSection); m_TotalSections++; sectionPackFiles = new Vector<PackFile>(); sectionPackFiles.add(m_RequiredResources.get(i)); totalSizeCompressed = m_RequiredResources.get(i).getZipLength(); } lastID = m_RequiredResources.get(i).getID(); } tmpSection = new Section(m_strDataLink, m_strOutputPath, sectionPackFiles, m_lGlobalOffset, m_pSections.size()); m_pSections.add(tmpSection); m_TotalSections++; for (int w=0; w < m_TotalSections; w++) { DBG("Downloader", "Section[" + w + "]:"); for (int y=0; y < m_pSections.get(w).getRequiredResources().size(); y++) { DBG("Downloader", "Section[" + w + "]:" + m_pSections.get(w).getRequiredResources().get(y).getName() + ", " + m_pSections.get(w).getRequiredResources().get(y).getZipLength() + ", " + m_pSections.get(w).getRequiredResources().get(y).getOffset() + ", " + m_pSections.get(w).getRequiredResources().get(y).getLength()); } } } } //#endif
[ "dangbinh4869@gmail.com" ]
dangbinh4869@gmail.com
fc0ac9bfc32a0532819c5cea2e3830d4bf19deba
9c0b2f34d4abdf668051c4b157ab8955fb30e24b
/week_6/day_1/lab/Bear.java
e9e45c7f5dab78bf78fbedf93c7ec50afb977419
[]
no_license
anattrass/cx3_8
12e60469a845ed55e3e6c429eed1c88fa0730ef7
36aca0b98d6858b5b8aab3fbbb8ed4ac9655199e
refs/heads/master
2020-05-21T06:17:43.314577
2017-03-11T09:21:58
2017-03-11T09:21:58
84,586,637
0
0
null
null
null
null
UTF-8
Java
false
false
622
java
class Bear { private String name; private int age; private double weight; public Bear(String name, int age, double weight) { this.name = name; this.age = age; this.weight = weight; } public String getName() { return this.name; } public void setName(String newName) { this.name = newName; } public int getAge() { return this.age; } public double getWeight() { return this.weight; } public boolean readyToHibernate() { // if (this.weight > 80){ // return true; // } // else { // return false; // } return this.weight >= 80; } }
[ "nattrassadam@gmail.com" ]
nattrassadam@gmail.com
00789ed7316b36fc4c3542bd94b5be391669f4fe
6800cd3a9d335d25e4fe5dcfb4217c07c61e4d40
/JavaCourse/Sum Calculator/src/com/company/SimpleCalculator.java
351832d9b1be6465cbba6bf54dde822b2d71dba3
[]
no_license
jurek21211/courses
e02fea62f9f502922d06a2dac6383c69a6f35714
754ae03cb8ef96935e9b1304738d85e0b6f9732a
refs/heads/master
2022-06-20T03:36:13.538982
2020-05-06T08:04:24
2020-05-06T08:04:24
261,690,435
0
0
null
null
null
null
UTF-8
Java
false
false
901
java
package com.company; public class SimpleCalculator { private double firstNumber, secondNumber; public double getFirstNumber(){ return this.firstNumber; } public double getSecondNumber(){ return this.secondNumber; } public void setFirstNumber(double number){ this.firstNumber = number; } public void setSecondNumber(double number) { this.secondNumber = number; } public double getAdditionResult(){ return this.firstNumber + this.secondNumber; } public double getSubtractionResult(){ return this.firstNumber - this.secondNumber; } public double getMultiplicationResult(){ return this.firstNumber * this.secondNumber; } public double getDivisionResult(){ if (this.secondNumber == 0) return 0; return this.firstNumber / this.secondNumber; } }
[ "juras1996@gmail.com" ]
juras1996@gmail.com
599c92cac9b184e605c15aba14fbbb2de9046794
cab255250481e7c66ec6a111a456f09e3e4267d6
/app/src/androidTest/java/com/coursera/bicoloreye/maps4me/ExampleInstrumentedTest.java
70db25ec68da5dee11dd24a72c10d74abc026234
[]
no_license
bicolorman/Maps4Me
8226389435cde78754dd8718afff8ce38310cc29
5df6aa8871e5f9183e4c57996f26c698ec288f34
refs/heads/master
2023-03-08T15:30:07.433790
2021-02-09T20:36:03
2021-02-09T20:36:03
337,435,110
0
0
null
null
null
null
UTF-8
Java
false
false
776
java
package com.coursera.bicoloreye.maps4me; 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.coursera.bicoloreye.maps4me", appContext.getPackageName()); } }
[ "garrick.oscar@gmail.com" ]
garrick.oscar@gmail.com
d2e3aaf13cb986f27573cf7da5106a516f1100e2
4820a8a9d64f1da34e4e5fe0421bab487df21af2
/app/src/main/java/com/example/LivFit/login.java
74f12726019ea1facbc97f1dc3134945dfe6d295
[]
no_license
DayanMarasinghe/LivFit_Health_Application
c81bbfc814caa651b13c7e240af383cb1be546a4
312e71257901037ee9e04dbfe78d260b26bc4bb0
refs/heads/master
2023-04-22T08:33:51.431826
2021-05-12T14:28:44
2021-05-12T14:28:44
349,654,600
1
1
null
2021-05-12T14:28:45
2021-03-20T07:14:55
Java
UTF-8
Java
false
false
6,024
java
package com.example.LivFit; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.basgeekball.awesomevalidation.AwesomeValidation; import com.basgeekball.awesomevalidation.ValidationStyle; import com.basgeekball.awesomevalidation.utility.RegexTemplate; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.Objects; public class login extends AppCompatActivity { private EditText username , password; private TextView forgetPW; private Button logBtn; private AwesomeValidation awesomeValidation; private DatabaseReference databaseReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); username = findViewById(R.id.etEnterUsername); password = findViewById(R.id.etPass); forgetPW = findViewById(R.id.tvForgotPW); logBtn = findViewById(R.id.btnLoginIn); //checking the SDK version to create notification channel if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ NotificationChannel channel = new NotificationChannel("Forget password notification", "LivFit Notify", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC); //validation patterns awesomeValidation.addValidation(this,R.id.etEnterUsername, RegexTemplate.NOT_EMPTY,R.string.emptyUsernameLogin); awesomeValidation.addValidation(this,R.id.etPass, RegexTemplate.NOT_EMPTY,R.string.emptyPassword); logBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //checking form validation if(awesomeValidation.validate()){ //getting database instance databaseReference = FirebaseDatabase.getInstance().getReference().child("User").child("user1"); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { String DBpassword = snapshot.child("pword").getValue().toString().trim(); String checkingPW = password.getText().toString().trim(); //checking if the password matches if(DBpassword.compareTo(checkingPW) == 0){ //if passwords matches getting daily data String calGoal = snapshot.child("calGoal").getValue().toString(); String calConsumption = snapshot.child("calConsumption").getValue().toString(); String calBurned = snapshot.child("calBurned").getValue().toString(); String watercount = snapshot.child("waterCount").getValue().toString(); Toast.makeText(getApplicationContext(),"Logged In" , Toast.LENGTH_SHORT).show(); //send data to the dashboard through intent Intent logDashIntent = new Intent(login.this,Dashboard.class); logDashIntent.putExtra("KeyDashCalGoal" , calGoal); logDashIntent.putExtra("KeyDashCalConsumption" , calConsumption); logDashIntent.putExtra("KeyDashCalBurned" , calBurned); logDashIntent.putExtra("KeyDashWaterCount" , watercount); startActivity(logDashIntent); } else{ Toast.makeText(getApplicationContext(),"Please enter correct password",Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } else{ Toast.makeText(getApplicationContext(),"Please enter login credential correctly",Toast.LENGTH_SHORT).show(); } } }); forgetPW.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //notify user String message = "We sent you a password reset link to your mail"; NotificationCompat.Builder builder = new NotificationCompat.Builder(login.this,"Forget password notification"); builder.setContentTitle("You have one new notification from LivFit"); builder.setContentText(message); builder.setSmallIcon(R.drawable.livfit_logo); builder.setAutoCancel(true); NotificationManagerCompat managerCompat = NotificationManagerCompat.from(login.this); managerCompat.notify(123,builder.build()); } }); } }
[ "ishini.kiridenaedu@gmail.com" ]
ishini.kiridenaedu@gmail.com
762b4a12105291e5bd64f4fff5d637b7f88b08fa
73b5d880fa06943c20ff0a9aee9d0c1d1eeebe10
/tinyos-1.x/tools/java/net/tinyos/matlab/MatlabControl.java
c29f1d73afd5ef1bee60dfc212e7791a1244e159
[ "Intel" ]
permissive
x3ro/tinyos-legacy
101d19f9e639f5a9d59d3edd4ed04b1f53221e63
cdc0e7ba1cac505fcace33b974b2e0aca1ccc56a
refs/heads/master
2021-01-16T19:20:21.744228
2015-06-30T20:23:05
2015-06-30T20:23:05
38,358,728
0
1
null
null
null
null
UTF-8
Java
false
false
8,859
java
/* MatlabControl.java * * "Copyright (c) 2001 and The Regents of the University * of California. All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice and the following * two paragraphs appear in all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * * $\Id$ */ /** * This class interfaces with the current Matlab session, allowing you * to call matlab commands from Java objects * * @author <a href="mailto:kamin@cs.berkeley.edu">Kamin Whitehouse</a> */ package net.tinyos.matlab; import java.lang.System.*; import com.mathworks.jmi.*; public class MatlabControl { Matlab matlab = null; //this is the com.mathworks.jmi.Matlab class,which has functionality allowing one to interact with the matlab session. boolean useCb=false; Object returnVal; String callbackFunction; /***************CONSTRUCTORS****************/ /*** usually, the default constructor with no arguments is fine. * Sometimes, a callback function is useful. A callback function * is allows the user to pass the command and its arguments to a * matlab function, which will figure out the best way to executue * it, instead of trying to execute it directly from java. This * is often useful for handling/printing errors as well as dealing * with native matlab data types, like cell arrays. The cell * array is not really converted to a java type, only the handle * of the cell array is converted to a java type, so often a * matlab callback function is useful for dealing specially with * cell arrays, etc. ***/ public MatlabControl() { this(false); } public MatlabControl(boolean useCallback) { this(useCallback,new String("matlabControlcb")); } public MatlabControl(boolean useCallback, String CallBackFunction) { try { if (matlab == null) matlab = new Matlab();//this command links to the current matlab session } catch (Exception e) { System.out.println(e.toString()); } returnVal = new String("noReturnValYet"); this.useCb=useCallback; callbackFunction=CallBackFunction; } /***************USER-LEVEL FUNCTIONS****************/ /***call these from any java thread (as long as the thread * originated from within matlab) ***/ /**Evaluate a string, Matlab script, or Matlab function**/ public void eval(String Command) { Matlab.whenMatlabReady(new MatlabEvalCommand(Command,useCb)); } /**Evaluate a Matlab function that requires arguments. Each element of the "args" vector is an argument to the function "Command"**/ public void feval(String Command, Object[] args) { Matlab.whenMatlabReady(new MatlabFevalCommand(Command, args,useCb)); } /**Evaluate a Matlab function that requires arguments and provide return arg. * Each element of the "args" vector is an argument to the function "Command"**/ public Object blockingFeval(String Command, Object[] args) throws InterruptedException { returnVal = new String("noReturnValYet"); Matlab.whenMatlabReady(new MatlabBlockingFevalCommand(Command, args, useCb, this)); if (returnVal.equals(new String("noReturnValYet"))) { synchronized(returnVal){ returnVal.wait(); } } return returnVal; } /**Echoing the eval statement is useful if you want to see in * matlab each time that a java function tries to execute a matlab * command **/ public void setEchoEval(boolean echo){ Matlab.setEchoEval(echo); } /**********TEST FUNCTIONS***********************/ /***call these functions from within Matlab itself. These are examples of the general execution order: 1. instantiate java object from matlab 2. spawn a new Java thread 3. call matlab functions from new java thread example: ****/ public void testEval(final String Command) { class Caller extends Thread{ public void run(){ try{ eval(Command); } catch(Exception e){ // System.out.println(e.toString()); } } } Caller c = new Caller(); c.start(); } public void testFeval(final String Command, final Object[] args) { class Caller extends Thread{ public void run(){ try{ feval(Command, args); } catch(Exception e){ // System.out.println(e.toString()); } } } Caller c = new Caller(); c.start(); } public void testBlockingFeval(final String Command, final Object[] args) { class Caller extends Thread{ public void run(){ try{ Object rets[] = new Object[1]; rets[0] = blockingFeval(Command, args); feval(new String("disp"),rets ); } catch(Exception e){ // System.out.println(e.toString()); } } } Caller c = new Caller(); c.start(); } /******** INTERNAL FUNCTIONS AND CLASSES *******/ public void setReturnVal(Object val) { synchronized(returnVal){ Object oldVal = returnVal; returnVal = val; oldVal.notifyAll(); } } /** This class is used to execute a string in Matlab **/ protected class MatlabEvalCommand implements Runnable { String command; boolean useCallback,eval; Object[] args; public MatlabEvalCommand(String Command, boolean useCallback) { command = Command; this.useCallback = useCallback; eval=true; args=null; } protected Object useMatlabCommandCallback(String command, Object[] args){ int numArgs = (args==null)? 0 : args.length; Object newArgs[] = new Object[numArgs+1] ; newArgs[0]=command; for(int i=0;i<numArgs;i++){ newArgs[i+1] = args[i]; } try{ return matlab.mtFevalConsoleOutput(new String("matlabControlcb"), newArgs, 0); } catch(Exception e){ // System.out.println(e.toString()); return null; } } public void run() { try { if(useCallback){ useMatlabCommandCallback(command, args); } else if(eval){ matlab.evalConsoleOutput(command); } else{ matlab.fevalConsoleOutput(command, args, 0, null); } } catch (Exception e) { System.out.println(e.toString()); } } } /** This class is used to execute a function in matlab and pass paramseters**/ protected class MatlabFevalCommand extends MatlabEvalCommand { public MatlabFevalCommand(String Command, Object[] Args, boolean useCallback) { super(Command, useCallback); args = Args; eval=false; } } /** This class is used to execute a function in matlab and pass paramseters * and it also return arguments**/ protected class MatlabBlockingFevalCommand extends MatlabFevalCommand { MatlabControl parent; public MatlabBlockingFevalCommand(String Command, Object[] Args, boolean useCallback, MatlabControl parent) { super(Command, Args, useCallback); this.parent=parent; } public void run() { try { if(useCallback){ parent.setReturnVal(useMatlabCommandCallback(command, args)); } else{ parent.setReturnVal(matlab.mtFevalConsoleOutput(command, args, 0)); } } catch (Exception e) { // System.out.println(e.toString()); } } } }
[ "lucas@x3ro.de" ]
lucas@x3ro.de
c764928e36260c90a35ef7a5c8902d2c4caad681
1f19cd8f3caccf899c46373e0fb6d4173923354c
/eas-webapi/src/main/java/cn/kl/eas/web/utils/MergeEntityUtil.java
4d983dc1b0c568304a98b7dfefaa37f47ecf1216
[]
no_license
liukaijiedegit/kl_eas
76d3b1e863875791e9b9dc54aa091d74b1552c1a
e78a9eb552ffde407a3e28154171f94bb49dae56
refs/heads/master
2021-01-19T23:47:39.685646
2017-08-24T08:11:41
2017-08-24T08:11:41
101,269,075
0
0
null
null
null
null
UTF-8
Java
false
false
1,080
java
package cn.kl.eas.web.utils; import java.lang.reflect.Field; /** * Created by kl272 on 2017/6/17. * <p> * 将前端传递的 Entity 合并到数据库已有的记录实例中,同时实体类使用 DynamicUpdate 注解 * <p> * 这样可以避免前后端传递太多数据,同时,更新时不必更新没变的字段 */ public class MergeEntityUtil { public static Object merge(Object free, Object persistence, Class cls) throws IllegalAccessException { if (!free.getClass().getName().equals(cls.getName()) || !persistence.getClass().getName().equals(cls.getName())) return null; Field[] fields = cls.getDeclaredFields(); Field.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; Object freeVal = field.get(free); Object perVal = field.get(persistence); if (freeVal != null && !freeVal.equals(perVal)) field.set(persistence, field.get(free)); } return persistence; } }
[ "495806899@qq.com" ]
495806899@qq.com
24e7f0474b3a9da181b70103087ff72a6e9544ad
074ec437c875ea8c6c1490f97782b5cb9b2e3da5
/src/main/java/sda/sping/test1/repositories/AccountRepository.java
3633972bef254bb6a25ee794f6858ed158d46b83
[]
no_license
nikolay1962/SpringTest1
7065ddf518e452e1702b79ae4db494d37d5613c7
9b528aae5948cd63ced5febbb7c2cc6f0ca09a99
refs/heads/master
2020-04-08T16:41:05.272630
2018-11-28T16:14:05
2018-11-28T16:14:05
159,529,927
0
0
null
null
null
null
UTF-8
Java
false
false
319
java
package sda.sping.test1.repositories; import org.springframework.data.repository.CrudRepository; import sda.sping.test1.dto.Account; public interface AccountRepository extends CrudRepository<Account, Integer> { Iterable<Account> getAccountsByCurrency(String currency); Account getAccountById(Integer id); }
[ "nisha@hot.ee" ]
nisha@hot.ee
ea2730d0d7611f81494c9571587ef3659b9af95e
33c2a318221ea7c1fb7f0b7fafae99d82de5addc
/wx_MyGis/src/cn/gis/utils/C3P0Utils.java
f97b3bf4dd2fb503f12034a2a1d4b27e38e80f21
[]
no_license
Snake8859/MyGIS
7b324ae0cb760a06b0799feedbf98e710cc62546
7b8e9b0b122728039cb0d51732800cd2fd8bb479
refs/heads/master
2022-12-10T05:24:57.917845
2020-09-05T09:12:36
2020-09-05T09:12:36
293,040,780
0
0
null
null
null
null
UTF-8
Java
false
false
820
java
package cn.gis.utils; import java.sql.Connection; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * C3P0提供核心工具类:ComboPooledDataSource,如果要使用连接池,必须创建该类的实例对象 * @author Administrator * */ public class C3P0Utils { //使用默认配置 private static ComboPooledDataSource dataSource =new ComboPooledDataSource(); //使用命名配置 //private static ComboPooledDataSource dataSource1 =new ComboPooledDataSource("oracle"); /** * 获得数据源(连接池) */ public static DataSource getDataSource(){ return dataSource; } /** * 获得连接 */ public static Connection getConnection(){ try { return dataSource.getConnection(); } catch (Exception e) { throw new RuntimeException(e); } } }
[ "snake8859@qq.com" ]
snake8859@qq.com
86ba8f8d18443745891c718f62c7ab1ac55a3b48
c1751c2df1a8a45bb5566304ea3e0af8462b50ee
/ProyectoFinal/src/main/java/com/ipn/mx/modelo/dao/VariantesApoyosDAO.java
e2ec994596b75647c63cc16d140398e5446a96a9
[]
no_license
ricardomachorro/poryectoFinalWEB3CM4
cfc95f518047e0c747f6b72c68fff9680b4759bb
f3e5f62e8d123f217be90a16bbec1510480b76f6
refs/heads/main
2023-02-19T20:43:24.920974
2021-01-24T22:50:48
2021-01-24T22:50:48
327,456,771
1
0
null
null
null
null
UTF-8
Java
false
false
4,607
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 com.ipn.mx.modelo.dao; import com.ipn.mx.modelo.dto.VariantesApoyosDTO; import com.ipn.mx.modelo.entidades.VariantesApoyos; import com.ipn.mx.utilerias.HibernateUtil; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.Query; /** * * @author Ricardo Alberto */ public class VariantesApoyosDAO { public void create(VariantesApoyosDTO dto) throws SQLException { Session sesion=HibernateUtil.getSessionFactory().getCurrentSession(); Transaction transaction=sesion.getTransaction(); try{ transaction.begin(); sesion.save(dto.getEntidad()); transaction.commit(); }catch(HibernateException he){ if(transaction!=null && transaction.isActive()){ transaction.rollback(); } } } public void update(VariantesApoyosDTO dto) throws SQLException { Session sesion=HibernateUtil.getSessionFactory().getCurrentSession(); Transaction transaction=sesion.getTransaction(); try{ transaction.begin(); sesion.update(dto.getEntidad()); transaction.commit(); }catch(HibernateException he){ if(transaction!=null && transaction.isActive()){ transaction.rollback(); } } } public void delete(VariantesApoyosDTO dto) throws SQLException { Session sesion=HibernateUtil.getSessionFactory().getCurrentSession(); Transaction transaction=sesion.getTransaction(); try{ transaction.begin(); sesion.delete(dto.getEntidad()); transaction.commit(); }catch(HibernateException he){ if(transaction!=null && transaction.isActive()){ transaction.rollback(); } } } public VariantesApoyosDTO read(VariantesApoyosDTO dto) throws SQLException { Session sesion=HibernateUtil.getSessionFactory().getCurrentSession(); Transaction transaction=sesion.getTransaction(); try{ transaction.begin(); dto.setEntidad(sesion.get(dto.getEntidad().getClass(),dto.getEntidad().getIDVarianteApoyo())); transaction.commit(); }catch(HibernateException he){ if(transaction!=null && transaction.isActive()){ transaction.rollback(); } } return dto; } public List readAll() throws SQLException { Session sesion=HibernateUtil.getSessionFactory().getCurrentSession(); Transaction transaction=sesion.getTransaction(); List lista=new ArrayList(); try{ transaction.begin(); //select * from usuario as u order by u.idUsuario; //int x; //Usuario u // Query q= sesion.createQuery("from VariantesApoyos v order by v.IDVarianteApoyo"); for(VariantesApoyos e:(List<VariantesApoyos>) q.list()){ VariantesApoyosDTO dto=new VariantesApoyosDTO(); dto.setEntidad(e); lista.add(dto); } transaction.commit(); }catch(HibernateException he){ if(transaction!=null && transaction.isActive()){ transaction.rollback(); } } return lista; } public static void main (String args[]){ VariantesApoyosDTO mun=new VariantesApoyosDTO(); VariantesApoyosDAO dao=new VariantesApoyosDAO(); try { List<VariantesApoyosDTO> apo=dao.readAll(); for(int i=0;i<apo.size();i++){ System.out.println(apo.get(i).getEntidad()); } } catch (SQLException ex) { Logger.getLogger(VariantesApoyosDAO.class.getName()).log(Level.SEVERE, null, ex); } } }
[ "ricardoalbeto.machorrovences@gmail.com" ]
ricardoalbeto.machorrovences@gmail.com
55aef7d89dde212af5fb878db0bed7f7d2df6538
ceb9c563ad38cddee684236f8da63cdaac1ca51b
/src/org/ofbiz/greenfire/greenfire/BookDataBackup.java
3ff1ab6f0687bd9c14be97c13d342653df2761c5
[]
no_license
ptayadeSPELTechnologies/greenfire
75bdc70759a5f8b9ab077f2d55b18a53d6f08b7f
e00512a96ed0d98450ef4d6e8f4669d3d40e7970
refs/heads/master
2021-01-10T18:36:45.282502
2016-04-26T09:27:03
2016-04-26T09:27:03
57,116,943
0
0
null
null
null
null
UTF-8
Java
false
false
7,917
java
package org.ofbiz.greenfire.greenfire; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericValue; import org.ofbiz.service.LocalDispatcher; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class BookDataBackup { public static String doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // Set the response message's MIME type response.setContentType("text/html;charset=UTF-8"); // Allocate a output writer to write the response message into the network socket PrintWriter out = response.getWriter(); String path="hot-deploy/greenfire/webapp/greenfire/xml_files/"; try{ //LocalDispatcher dispather=(LocalDispatcher) request.getAttribute("dispatcher"); GenericDelegator delegator= (GenericDelegator) request.getAttribute("delegator"); Map<?, ?> field=(Map<?, ?>) UtilMisc.toMap("userID","01"); GenericValue values=delegator.findOne("MercytheUser",false ,field); int chapter_unlocked=Integer.parseInt(values.get("chaptersUnlocked").toString()); String html="<input type='hidden' id='chapterunlock' value='"+chapter_unlocked+"'/>"; DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); System.out.println(chapter_unlocked); if(chapter_unlocked<9){ for(int i=1;i<chapter_unlocked+1;i++) { File inputFile = new File(path+"chapter"+i+".xml"); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); System.out.println("Root element:" + doc.getDocumentElement().getNodeName()); String title = doc.getElementsByTagName("Title").item(0).getTextContent(); NodeList nList = doc.getElementsByTagName("Data"); String str=nList.item(0).getTextContent(); String[] arr=str.split("</break>"); str="<div class='title2 custompage'>"+title+"</div>"; /* str+="<audio controls>" +"<source src='' type='audio/wav' />" +"<p>Your user agent does not support the HTML5 Audio element.</p>"+ "</audio>"+*/ for (int temp = 0; temp < arr.length; temp++) { str+=" <div class='custompage'>"+ "<div class='title'>Chapter: "+i+" </div><div><p>"+ arr[temp]+ "</div></div>"; } html+=str; } /* * Code for reading the question, if all chapters are unlocked do not read the chapter */ if(chapter_unlocked<8){ File questionFile = new File(path+"question"+chapter_unlocked+".xml"); Document doc = dBuilder.parse(questionFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); //get title String title = doc.getElementsByTagName("Title").item(0).getTextContent(); //add title to the main question title heading String str=""; if(chapter_unlocked==7) str="<div class='title2 custompage'>Last Question</div>"; str+="<div class='question'>"; //page opening div / main div //Add question title to top right corner of book str+="<div class='title3'>"+title+"</div>"; //Add question content to page str+="<div class='qtextdiv'>"+doc.getElementsByTagName("Data").item(0).getTextContent()+"</div>"; str+="<div class='white seperator'></br> </div>"; str+="<div> Expected output: <div class='qdiv'>"+doc.getElementsByTagName("ExpectedOutput").item(0).getTextContent()+"</div></div>"; str+="<div class='white seperator'></br> </div>"; str+="<div class='qdiv'>"+doc.getElementsByTagName("Code").item(0).getTextContent()+"</div></br>"; str+="<a href='tutorial"+chapter_unlocked+"' >Go to tutorial "+chapter_unlocked+"</a>"; str+="</div>"; //end of page opening div html+=str; //append to html // writing question code loquacious File code = new File(path+"question_examples.xml"); doc = dBuilder.parse(code); doc.getDocumentElement().normalize(); String codeData=doc.getElementsByTagName("Data").item(chapter_unlocked-1).getTextContent(); //main page div str="<div class='editor custompage'>"; // "<div class='title'>Code: "+chapter_unlocked+" </div>"; //add code title to left hand corner //code for loquacious str+="<div class='miniLoq'>"+ "<form>"+ "<table class='miniLoqTable' align='center' border='0' class='loq'>"+ "<tr>"+ " <th class='bar1' ><p class='logo'>Loquacious</p></th>"+ "</tr>"+ "<tr>"+ "<td class='bar' align='center'>"+ "<textarea onkeyup='pressListener(event)' onmouseup='this.onkeyup()' id='loquacious' cols='45' rows='12' class='locbox'>"+codeData+"</textarea>"+ "</td>"+ "</tr>"+ "<tr>"+ "<td class='bar'>"+ "</br>"+ "<button type='button' onclick='runit();' class='button'>Run</button> "+ "<button type='button' onclick='' class='button'>Reset</button> "+ "<button type='button' onclick='sayitMod()' class='button'>Say</button> "+ "<button type='button' onclick='overview()' class='button'>Overview</button> "+ "</td>"+ "</tr>"+ "<tr>"+ "<td class='bar'>"+ "<p id='dvContent'></p>"+ "</td>"+ "</tr> "+ "<tr>"+ "<td class='bar'>"+ "<div class='message' id='status' style='overflow:scroll; height:100px;'></div> "+ "</td>"+ "</tr> "+ "<tr >"+ "<td >"+ "<div id='output' style='overflow:scroll; height:160px;'>"+ "</div>"+ "</td>"+ "</tr> "+ "<tr>"+ "<td>"+ "<div id='mycanvas'></div> "+ "</td>"+ "</tr> "+ "</table> "+ "</form> "+ "</div></div>"; html+=str; } String str= "<form name= 'solution'>"+ "<input type='hidden' id='desiredoutput' value=''/>"+ "<input type='hidden' id='clickedLinkName' value='question"+chapter_unlocked+"'/>"+ "<input type='hidden' id='testingOutput' value=''/>"+ " </form>"; html+=str; out.println(html); } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); // Always close the output writer } return "success"; } }
[ "Priyanka Tayade" ]
Priyanka Tayade
65f483d22c704009663e2e09b181c4b076f420aa
1de99cb05f98fd3c3d4801eaf503e0262e8eaf55
/src/main/java/com/itstyle/seckill/distributedlock/redis/RedissLockDemo.java
dcd70996ffa9553e8b978bb6d9428e89397076be
[ "Apache-2.0" ]
permissive
tanbinh123/spring-boot-seckill-1
47732e687db4158491bdab89cba4861409476c10
8835e9042aed6cfa4554a39bf3716ebfe5d8e3a6
refs/heads/master
2023-03-15T10:09:39.650489
2020-12-09T13:39:48
2020-12-09T13:39:48
475,395,657
1
0
Apache-2.0
2022-03-29T10:42:43
2022-03-29T10:42:43
null
UTF-8
Java
false
false
5,552
java
package com.itstyle.seckill.distributedlock.redis; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.redisson.RedissonMultiLock; import org.redisson.RedissonRedLock; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; /** * redis分布式锁Demo * @author 科帮网 By https://blog.52itstyle.com */ public class RedissLockDemo { /** * 可重入锁(Reentrant Lock) * Redisson的分布式可重入锁RLock Java对象实现了java.util.concurrent.locks.Lock接口,同时还支持自动过期解锁 * @param redisson */ public void testReentrantLock(RedissonClient redisson) { RLock lock = redisson.getLock("anyLock"); try { // 1. 最常见的使用方法 // lock.lock(); // 2. 支持过期解锁功能,10秒钟以后自动解锁, 无需调用unlock方法手动解锁 // lock.lock(10, TimeUnit.SECONDS); // 3. 尝试加锁,最多等待3秒,上锁以后10秒自动解锁 boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS); if (res) { // 成功 // do your business } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } /** * Redisson同时还为分布式锁提供了异步执行的相关方法 * @param redisson */ public void testAsyncReentrantLock(RedissonClient redisson) { RLock lock = redisson.getLock("anyLock"); try { lock.lockAsync(); lock.lockAsync(10, TimeUnit.SECONDS); Future<Boolean> res = lock.tryLockAsync(3, 10, TimeUnit.SECONDS); if (res.get()) { // do your business } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } finally { lock.unlock(); } } /** * 公平锁(Fair Lock) * Redisson分布式可重入公平锁也是实现了java.util.concurrent.locks.Lock接口的一种RLock对象。 * 在提供了自动过期解锁功能的同时,保证了当多个Redisson客户端线程同时请求加锁时,优先分配给先发出请求的线程。 * @param redisson */ public void testFairLock(RedissonClient redisson){ RLock fairLock = redisson.getFairLock("anyLock"); try{ // 最常见的使用方法 fairLock.lock(); // 支持过期解锁功能, 10秒钟以后自动解锁,无需调用unlock方法手动解锁 fairLock.lock(10, TimeUnit.SECONDS); // 尝试加锁,最多等待100秒,上锁以后10秒自动解锁 boolean res = fairLock.tryLock(100, 10, TimeUnit.SECONDS); if (res) { // do your business } } catch (InterruptedException e) { e.printStackTrace(); } finally { fairLock.unlock(); } // Redisson同时还为分布式可重入公平锁提供了异步执行的相关方法: // RLock fairLock = redisson.getFairLock("anyLock"); // fairLock.lockAsync(); // fairLock.lockAsync(10, TimeUnit.SECONDS); // Future<Boolean> res = fairLock.tryLockAsync(100, 10, TimeUnit.SECONDS); } /** * 联锁(MultiLock) * Redisson的RedissonMultiLock对象可以将多个RLock对象关联为一个联锁,每个RLock对象实例可以来自于不同的Redisson实例 * @param redisson1 * @param redisson2 * @param redisson3 */ public void testMultiLock(RedissonClient redisson1,RedissonClient redisson2, RedissonClient redisson3){ RLock lock1 = redisson1.getLock("lock1"); RLock lock2 = redisson2.getLock("lock2"); RLock lock3 = redisson3.getLock("lock3"); RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3); try { // 同时加锁:lock1 lock2 lock3, 所有的锁都上锁成功才算成功。 lock.lock(); // 尝试加锁,最多等待100秒,上锁以后10秒自动解锁 boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS); if (res) { // do your business } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } /** * 红锁(RedLock) * Redisson的RedissonRedLock对象实现了Redlock介绍的加锁算法。该对象也可以用来将多个RLock对象关联为一个红锁,每个RLock对象实例可以来自于不同的Redisson实例 * @param redisson1 * @param redisson2 * @param redisson3 */ public void testRedLock(RedissonClient redisson1,RedissonClient redisson2, RedissonClient redisson3){ RLock lock1 = redisson1.getLock("lock1"); RLock lock2 = redisson2.getLock("lock2"); RLock lock3 = redisson3.getLock("lock3"); RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3); try { // 同时加锁:lock1 lock2 lock3, 红锁在大部分节点上加锁成功就算成功。 lock.lock(); // 尝试加锁,最多等待100秒,上锁以后10秒自动解锁 boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS); if (res) { // do your business } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } //读写锁(ReadWriteLock)、信号量(Semaphore)、可过期性信号量(PermitExpirableSemaphore)、闭锁(CountDownLatch) }
[ "345849402@qq.com" ]
345849402@qq.com
fdac57e562f3b7cd3bac6f66e57b45659ddfc857
f9223e4396087838070aa3b6effd41bff9d72949
/interlok-core/src/test/java/com/adaptris/core/services/exception/ExceptionAsStringReportTest.java
1c5bac81d99a4e9a38b55d1ea5894f8d834ab4bd
[ "Apache-2.0" ]
permissive
ajay-cz/interlok
edac603c068a86a655435f75e8aec21967528143
0dae3c0e0e7093070f8947804a437b86e81d61b3
refs/heads/master
2022-10-10T18:32:41.087637
2020-05-11T09:53:08
2020-05-11T09:53:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,357
java
/* * Copyright 2018 Adaptris Ltd. * * 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.adaptris.core.services.exception; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import com.adaptris.core.AdaptrisMessage; import com.adaptris.core.AdaptrisMessageFactory; import com.adaptris.core.CoreConstants; import com.adaptris.core.CoreException; import com.adaptris.core.ServiceException; import com.adaptris.core.common.MetadataDataOutputParameter; import com.adaptris.interlok.InterlokException; import com.adaptris.interlok.config.DataOutputParameter; import com.adaptris.interlok.types.InterlokMessage; public class ExceptionAsStringReportTest extends ExceptionServiceExample { @Override public boolean isAnnotatedForJunit4() { return true; } @Test public void testDoService_Payload() throws Exception { AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage(); msg.addObjectHeader(CoreConstants.OBJ_METADATA_EXCEPTION, new Exception("This is the exception")); ExceptionReportService service = new ExceptionReportService(new ExceptionAsString()); execute(service, msg); assertTrue(msg.getContent().contains("This is the exception")); } @Test public void testDoService_Payload_Exception() throws Exception { AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage(); msg.addObjectHeader(CoreConstants.OBJ_METADATA_EXCEPTION, new Exception("This is the exception")); ExceptionReportService service = new ExceptionReportService( new ExceptionAsString().withTarget(new DataOutputParameter<String>() { @Override public void insert(String data, InterlokMessage msg) throws InterlokException { throw new CoreException(); } })); try { execute(service, msg); fail(); } catch (ServiceException expected) { } } @Test public void testDoService_Metadata() throws Exception { AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage(); msg.addObjectHeader(CoreConstants.OBJ_METADATA_EXCEPTION, new Exception("This is the exception")); ExceptionReportService service = new ExceptionReportService( new ExceptionAsString().withTarget(new MetadataDataOutputParameter("exceptionKey")).withIncludeStackTrace(false)); execute(service, msg); assertTrue(msg.getMetadataValue("exceptionKey").contains("This is the exception")); } @Override protected Object retrieveObjectForSampleConfig() { return new ExceptionReportService(new ExceptionAsString()); } @Override protected String createBaseFileName(Object o) { return super.createBaseFileName(o) + "-" + ((ExceptionReportService) o).getExceptionSerializer().getClass().getSimpleName(); } }
[ "lewin.chan@adaptris.com" ]
lewin.chan@adaptris.com
79667c1813e09c8f71880226db102d1bcfb7a3cf
9c7ea25a118e94970809a7b879c9f8db2964a40f
/target/generated-sources/xjc/atis_partial_03_00_74/ContactInformation.java
7f9c7402c52a37865053467841d575f222758d71
[]
no_license
vramku/onebusaway-tcip-api-v40
c29d6133654fcf17fe4b85f060f91ec358e6446b
cc3792c1176b033e0a505eb597bc733ff16a16fd
refs/heads/master
2020-12-26T04:48:19.209063
2016-05-19T20:54:17
2016-05-19T20:54:17
37,859,287
0
0
null
2015-06-22T14:15:47
2015-06-22T14:15:46
null
UTF-8
Java
false
false
8,616
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.06.24 at 02:32:24 PM EDT // package atis_partial_03_00_74; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ContactInformation complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ContactInformation"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="emails" minOccurs="0"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence maxOccurs="10"&gt; * &lt;element name="email" type="{http://www.atis-partial-03-00-74}Email"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;element name="phones" minOccurs="0"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence maxOccurs="10"&gt; * &lt;element name="phone" type="{http://www.atis-partial-03-00-74}PhoneInformation"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;element name="deviceIdentity" type="{http://www.atis-partial-03-00-74}Device-Identity" minOccurs="0"/&gt; * &lt;element name="furtherData" type="{http://www.atis-partial-03-00-74}ReferenceID" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ContactInformation", propOrder = { "emails", "phones", "deviceIdentity", "furtherData" }) public class ContactInformation { protected ContactInformation.Emails emails; protected ContactInformation.Phones phones; protected String deviceIdentity; protected String furtherData; /** * Gets the value of the emails property. * * @return * possible object is * {@link ContactInformation.Emails } * */ public ContactInformation.Emails getEmails() { return emails; } /** * Sets the value of the emails property. * * @param value * allowed object is * {@link ContactInformation.Emails } * */ public void setEmails(ContactInformation.Emails value) { this.emails = value; } /** * Gets the value of the phones property. * * @return * possible object is * {@link ContactInformation.Phones } * */ public ContactInformation.Phones getPhones() { return phones; } /** * Sets the value of the phones property. * * @param value * allowed object is * {@link ContactInformation.Phones } * */ public void setPhones(ContactInformation.Phones value) { this.phones = value; } /** * Gets the value of the deviceIdentity property. * * @return * possible object is * {@link String } * */ public String getDeviceIdentity() { return deviceIdentity; } /** * Sets the value of the deviceIdentity property. * * @param value * allowed object is * {@link String } * */ public void setDeviceIdentity(String value) { this.deviceIdentity = value; } /** * Gets the value of the furtherData property. * * @return * possible object is * {@link String } * */ public String getFurtherData() { return furtherData; } /** * Sets the value of the furtherData property. * * @param value * allowed object is * {@link String } * */ public void setFurtherData(String value) { this.furtherData = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence maxOccurs="10"&gt; * &lt;element name="email" type="{http://www.atis-partial-03-00-74}Email"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "email" }) public static class Emails { @XmlElement(required = true) protected List<String> email; /** * Gets the value of the email property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the email property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEmail().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getEmail() { if (email == null) { email = new ArrayList<String>(); } return this.email; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence maxOccurs="10"&gt; * &lt;element name="phone" type="{http://www.atis-partial-03-00-74}PhoneInformation"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "phone" }) public static class Phones { @XmlElement(required = true) protected List<PhoneInformation> phone; /** * Gets the value of the phone property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the phone property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPhone().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PhoneInformation } * * */ public List<PhoneInformation> getPhone() { if (phone == null) { phone = new ArrayList<PhoneInformation>(); } return this.phone; } } }
[ "visar.ramku@nyct.com" ]
visar.ramku@nyct.com
b69216d3d82cc6e31afed9792fad6715bc76f0ed
734d21637209d39d0c4ec79a663dbeaa8415eca6
/src/apps/_game/Fireworks.java
854d5cacd291db26be01fd359cfdcb0b9340d0a3
[]
no_license
kilobyte3/AirShip_racing
496192a2279479fed8383b2da6de7f1dbe093949
96bbd4dcb4c7a569f0ac9fb5d814f3b993e74d27
refs/heads/master
2022-08-16T08:13:52.707029
2022-07-21T15:44:33
2022-07-21T15:44:33
80,950,212
0
0
null
null
null
null
ISO-8859-2
Java
false
false
3,356
java
package apps._game; import apps._game.playground.MapConstruction; import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import java.util.Random; /** * tüzijáték effekt * * 2008. március 12., 20:38 * @author Kis Balázs kilobyte@freemail.hu */ public class Fireworks { /** * belső osztály, egy pont leirására */ private class Point { private double x,y, addX,addY, addYr; private int timeToLive; private final Color color; /** * pont generálása */ private Point(int x, int y, Color color) { Random generator = new Random(); this.x = x; this.y = y; double d = (generator.nextDouble() * 6) + 2; addX = (generator.nextDouble() * d) - (d/2); addY = (generator.nextDouble() * d) - (d/2); addYr = (generator.nextDouble() * 0.3) + 0.1; this.color = color; timeToLive = generator.nextInt(10)+20; } /** * kirajzolás adott felületre */ private void draw(Graphics at) { at.setColor(color); if (timeToLive > 0 && timeToLive < 15) { at.drawRect((int)Math.round(x),(int)Math.round(y), 0,0); } if (timeToLive >= 15 && timeToLive < 30) { at.drawRect((int)Math.round(x),(int)Math.round(y), 1,1); } } /** * fizika működtetése */ private void update() { x = x + addX; y = y + addY; addY = addY + addYr; timeToLive--; } } private ArrayList<Point> pontok; /** * konstruktor, inicializálás */ public Fireworks() { pontok = new <Point>ArrayList(); } /** * tüzijáték előállitása */ public void generate() { Random generator = new Random(); Color color = null; switch(generator.nextInt(6)) { case 0 : color = new Color(255,0,0); break; case 1 : color = new Color(0,255,0); break; case 2 : color = new Color(0,0,255); break; case 3 : color = new Color(255,255,255); break; case 4 : color = new Color(255,255,0); break; case 5 : color = new Color(255,0,255); break; } int x = generator.nextInt(MapConstruction.ARENA_WIDTH); int y = generator.nextInt(MapConstruction.ARENA_HEIGHT); for(int i = 0; i <= 64; i++) { pontok.add(new Point(x,y, color)); } } /** * összes pont éltetése */ public void update() { for(int i = 0; i < pontok.size(); i++) { pontok.get(i).update(); if (pontok.get(i).x > MapConstruction.ARENA_WIDTH || pontok.get(i).x < 0 || pontok.get(i).y > MapConstruction.ARENA_HEIGHT || pontok.get(i).timeToLive <= 0) { pontok.remove(i); i--; } } } /** * megjelenités adott felületre */ public void draw(Graphics at) { for(Point pont : pontok) { pont.draw(at); } } }
[ "kilobyte@freemail.hu" ]
kilobyte@freemail.hu
ced258623531a36507b3b8f373137d26ef7dfdf7
707a18c86807934510df748d14aee9ea5a82fad3
/ReactiveCascade/cascade/src/main/java/com/futurice/cascade/reactive/ReactiveValue.java
9cfbd7b10e2d529ca6c973c863f3b5bf7a852498
[ "MIT" ]
permissive
luisramalho/cascade
5972736acdbbb61ca50fccf7b3443c0d4a247b39
f14d93ec565ac3ff1efed23ab7b0c2ad592b94da
refs/heads/master
2021-01-23T00:44:52.262194
2015-09-18T07:22:01
2015-09-18T07:22:01
44,107,647
0
0
null
2015-10-12T13:00:33
2015-10-12T13:00:33
null
UTF-8
Java
false
false
6,965
java
/* The MIT License (MIT) Copyright (c) 2015 Futurice Oy and individual contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.futurice.cascade.reactive; import android.support.annotation.CallSuper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.futurice.cascade.i.IActionOne; import com.futurice.cascade.i.IActionOneR; import com.futurice.cascade.i.IOnErrorAction; import com.futurice.cascade.i.IThreadType; import com.futurice.cascade.i.NotCallOrigin; import com.futurice.cascade.i.nonnull; import com.futurice.cascade.i.nullable; import java.util.concurrent.atomic.AtomicReference; import static com.futurice.cascade.Async.dd; import static com.futurice.cascade.Async.vv; /** * Thread-safe reactive display of a variable getValue. Add one or more {@link IActionOne} * actions to update the display when the variable fires. Usually these can be added as Lambda expressions * referencing the UI element you would like to track the variable's getValue in an eventually-consistent * manner. * <p> * Note the all <code>get()</code>-style actions will return the latest getValue. Therefore asynchronous * calls may not result in all values * </p> * <p> * Bindings are thread safe. All mReactiveTargets will refire concurrently if the {@link com.futurice.cascade.i.IThreadType} * allows, but individual mReactiveTargets will never be called concurrently or out-of-sequence. Multiple * changes to the bound getValue within a short time relative to the current speed of the * {@link com.futurice.cascade.i.IThreadType} may coalesce into a single headFunctionalChainLink refire of only * the most recent getValue. Bound functions must be idempotent. Repeat firing of the same getValue * is filter under most but not all circumstances. This possibility is related to the use of * {@link java.lang.ref.WeakReference} of the previously fired getValue of each headFunctionalChainLink to minimize * memory load. * </p> */ @NotCallOrigin public class ReactiveValue<T> extends Subscription<T, T> implements IReactiveValue<T> { private final AtomicReference<T> valueAR = new AtomicReference<>(); /** * Create a new AtomicValue * * @param name * @param initialValue */ public ReactiveValue( @NonNull @nonnull final String name, @NonNull @nonnull final T initialValue) { this(name, initialValue, null, null, null); } /** * Create a new AtomicValue * * @param name * @param initialValue * @param threadType * @param inputMapping * @param onError */ public ReactiveValue( @NonNull @nonnull final String name, @NonNull @nonnull final T initialValue, @Nullable @nullable final IThreadType threadType, @Nullable @nullable final IActionOneR<T, T> inputMapping, @Nullable @nullable final IOnErrorAction onError) { super(name, null, threadType, inputMapping != null ? inputMapping : out -> out, onError); set(initialValue); } /** * Run all reactive functional chains bound to this {@link ReactiveValue}. * <p> * Normally you do not need to call this, it is called for you. Instead, call * {@link #set(Object)} to assert a new value. * <p> * You can also link this to receive multiple reactive updates as a * down-chain {@link IReactiveSource#subscribe(IActionOne)} * to receive and store reactive values. * <p> * You can also link into a active chain to receive individually constructed and fired updates using * <code> * <pre> * myAltFuture.subscribe(value -> myAtomicValue.set(value)) * </pre> * </code> * * Both of these methods will automatically call <code>fire()</code> for you. * * You may want to <code>fire()</code> manually on app startup after all your initial reactive chains are constructed. * This will heat up the reactive chain to initial state by flushing current values through the system. * * All methods and receivers within a reactive chain are <em>supposed</em> to be idempotent to * multiple firing events. This * does not however mean the calls are free or give a good user experience and value as in the * case of requesting data multiple times from a server. You have been warned. */ @NotCallOrigin @CallSuper public void fire() { fire(valueAR.get()); } @CallSuper @NonNull @nonnull @Override // IAtomicValue, IGettable public T get() { return valueAR.get(); } @CallSuper @Override // IAtomicValue public boolean set(@NonNull @nonnull final T value) { final T previousValue = valueAR.getAndSet(value); final boolean valueChanged = !(value == previousValue || value.equals(previousValue) || (previousValue != null && previousValue.equals(value))); if (valueChanged) { vv(this, mOrigin, "Successful set(" + value + "), about to fire()"); fire(value); } else { // The value has not changed vv(this, mOrigin, "set() value=" + value + " was already the value, so no change"); } return valueChanged; } @CallSuper @Override // IAtomicValue public boolean compareAndSet(@NonNull @nonnull final T expected, @NonNull @nonnull final T update) { final boolean success = this.valueAR.compareAndSet(expected, update); if (success) { vv(this, mOrigin, "Successful compareAndSet(" + expected + ", " + update + ")"); fire(update); } else { dd(this, mOrigin, "Failed compareAndSet(" + expected + ", " + update + "). The current value is " + get()); } return success; } @NonNull @nonnull @Override // Object public String toString() { return get().toString(); } }
[ "paul.houghton@futurice.com" ]
paul.houghton@futurice.com
45f17d191a3621a0332b64df46adae0bbf896ab0
b879233613fd9cd311612faa9923c8aa3b82bdfe
/Model/Part.java
c96b6574cbd1ccd8d66750bb08c0c3841cb22d9a
[]
no_license
Issamna/Inventory-Systems
b3ba2bac2ca384bf47b5e79c02a5af78ad4fd5a0
ba1582d62fc8b16a7bda94667ff1ec85ce2558c3
refs/heads/master
2021-01-15T04:05:42.638012
2020-02-25T00:21:38
2020-02-25T00:21:38
242,872,834
2
0
null
null
null
null
UTF-8
Java
false
false
1,937
java
/* C482 Performance Assessment Issam Ahmed 000846138 2/11/2020 */ package Model; import javafx.beans.binding.Bindings; import javafx.beans.property.*; public abstract class Part { private IntegerProperty id; private StringProperty name; private DoubleProperty price; private IntegerProperty stock; private IntegerProperty min; private IntegerProperty max; //constructor public Part(IntegerProperty id, StringProperty name, DoubleProperty price, IntegerProperty stock,IntegerProperty min, IntegerProperty max){ this.id = id; this.name = name; this.price = price; this.stock = stock; this.min = min; this.max = max; } //Mutator (setters) public void setId(IntegerProperty id){ this.id = id; } public void setName(StringProperty name){ this.name = name; } public void setPrice(DoubleProperty price){ this.price = price; } public void setStock(IntegerProperty stock){ this.stock = stock; } public void setMin(IntegerProperty min){ this.min = min; } public void setMax(IntegerProperty max){ this.max = max; } //Accessors (getters) public IntegerProperty getId(){ return id; } public StringProperty getName(){ return name; } public DoubleProperty getPrice(){ return price; } //getter to get price as string format for table column public StringProperty getPriceString(){ String priceFormat = Bindings.format("%.2f", price).get(); return new SimpleStringProperty("$"+ priceFormat); } public IntegerProperty getStock(){ return stock; } public IntegerProperty getMin(){ return min; } public IntegerProperty getMax(){ return max; } }
[ "noreply@github.com" ]
Issamna.noreply@github.com
60bf3f28a808c99f9a761512b50ce456953cbb0e
0cdab0464b878574b8cd78ab53c898304892a3ac
/src/main/java/org/apache/ibatis/cache/package-info.java
25109ac95805a4c7bc4b12e33b7e4f6d74ad8b08
[ "Apache-2.0" ]
permissive
yeecode/MyBatisCN
e600f660b0975c6d58996cd5e578d615dffe0d1f
489e130b318d4e46f0b2e70a5ed71b25914bda20
refs/heads/master
2023-08-17T02:58:42.922095
2022-01-18T13:26:05
2022-01-18T13:26:05
218,516,578
366
287
Apache-2.0
2023-07-22T20:12:22
2019-10-30T11:55:10
Java
UTF-8
Java
false
false
725
java
/** * Copyright 2009-2015 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. */ /** * Base package for caching stuff */ package org.apache.ibatis.cache;
[ "yeecode@126.com" ]
yeecode@126.com
3ac0c11a64991966f51806e6f674e0e38ce0f3cc
8d2fc3f02e1f895e1c6c7769d9f98e0acfa6926e
/src/com/livecron/ventana/layout/GridPaneEjemplo.java
836186043c65bf457260f9a617cd03a04aed94c2
[]
no_license
jjohxx/proyecto_javafx
ff2bcacc89b7cb23daee7520dcf0310e7d753611
5bfeaaca26b3782a125d9013e73c68fb851cf217
refs/heads/master
2022-12-26T03:17:01.687254
2020-09-19T01:16:23
2020-09-19T01:16:23
296,188,014
1
0
null
null
null
null
UTF-8
Java
false
false
1,706
java
package com.livecron.ventana.layout; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class GridPaneEjemplo extends Application { private Stage ventanaPrincipal; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { ventanaPrincipal = primaryStage; ventanaPrincipal.setTitle("GridPane Ejemplo"); GridPane grid = new GridPane(); grid.setPadding(new Insets(10, 10, 10, 10)); grid.setHgap(8); grid.setVgap(10); Label nombreDeUsuarioLabel = new Label("Nombre de usuario :"); GridPane.setConstraints(nombreDeUsuarioLabel, 0, 0); TextField nombreDeUsuarioEntrada = new TextField("Anonimo"); GridPane.setConstraints(nombreDeUsuarioEntrada, 1, 0); Label contraseniaLabel = new Label("Contraseña :"); GridPane.setConstraints(contraseniaLabel, 0, 1); PasswordField contraseniaEntrada = new PasswordField(); GridPane.setConstraints(contraseniaEntrada, 1, 1); Button botonIngresar = new Button("Ingresar"); GridPane.setConstraints(botonIngresar, 1, 2); grid.getChildren().addAll(nombreDeUsuarioLabel, nombreDeUsuarioEntrada, contraseniaLabel, contraseniaEntrada, botonIngresar); ventanaPrincipal.setScene(new Scene(grid, 400, 400)); ventanaPrincipal.show(); } }
[ "johxgks@gmail.com" ]
johxgks@gmail.com
e944c520362b3d55c1b4de2b064fefe60b10a1a0
66e50993a2e8cbe349c6160f19eeab0c613e5640
/src/test/java/com/levep/example/TestDataConfiguration.java
012fbae57decc90bec7d272a3c759c8d94cf92df
[]
no_license
cy6erGn0m/java-junior-example
97c90e1cc8a827c980dbc08a399cbe5ca5d5fb99
fc070287c18e1e0f3915144a270a45211d92957b
refs/heads/master
2020-04-17T09:31:08.626456
2019-02-22T19:08:32
2019-02-22T19:08:32
166,461,156
0
0
null
null
null
null
UTF-8
Java
false
false
1,405
java
package com.levep.example; import com.levelp.example.ApplicationConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "com.levelp.example") @ComponentScan( basePackages = "com.levelp.example", excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = { ApplicationConfiguration.class }) ) public class TestDataConfiguration { @Bean(name = "entityManagerFactory") public EntityManagerFactory entityManagerFactory() { return Persistence.createEntityManagerFactory("TestPersistenceUnit"); } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory factory) { return new JpaTransactionManager(factory); } }
[ "cy6ergn0m@gmail.com" ]
cy6ergn0m@gmail.com
e7378756bb6ec075d6b78ac257645c8a9797e5a5
20eb62855cb3962c2d36fda4377dfd47d82eb777
/newEvaluatedBugs/Jsoup_7_buggy/mutated/240/Tokeniser.java
f7e864fdcad58f2dd76c9543bdb9d8ae37fa500d
[]
no_license
ozzydong/CapGen
356746618848065cce4e253e5d3c381baa85044a
0ba0321b6b1191443276021f1997833342f02515
refs/heads/master
2023-03-18T20:12:02.923428
2020-08-21T03:08:28
2020-08-21T03:08:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,538
java
package org.jsoup.parser; import org.jsoup.helper.Validate; import org.jsoup.nodes.Entities; import java.util.Arrays; /** * Readers the input stream into tokens. */ final class Tokeniser { static final char replacementChar = '\uFFFD'; // replaces null character private static final char[] notCharRefCharsSorted = new char[]{'\t', '\n', '\r', '\f', ' ', '<', '&'}; static { Arrays.sort(notCharRefCharsSorted); } private final CharacterReader reader; // html input private final ParseErrorList errors; // errors found while tokenising private TokeniserState state = TokeniserState.Data; // current tokenisation state private Token emitPending; // the token we are about to emit on next read private boolean isEmitPending = false; private String charsString = null; // characters pending an emit. Will fall to charsBuilder if more than one private StringBuilder charsBuilder = new StringBuilder(1024); // buffers characters to output as one token, if more than one emit per read StringBuilder dataBuffer = new StringBuilder(1024); // buffers data looking for </script> Token.Tag tagPending; // tag we are building up Token.StartTag startPending = new Token.StartTag(); Token.EndTag endPending = new Token.EndTag(); Token.Character charPending = new Token.Character(); Token.Doctype doctypePending = new Token.Doctype(); // doctype building up Token.Comment commentPending = new Token.Comment(); // comment building up private String lastStartTag; // the last start tag emitted, to test appropriate end tag private boolean selfClosingFlagAcknowledged = true; Tokeniser(CharacterReader reader, ParseErrorList errors) { this.reader = reader; this.errors = errors; } Token read() { if (!selfClosingFlagAcknowledged) { error("Self closing flag not acknowledged"); selfClosingFlagAcknowledged = true; } while (!isEmitPending) state.read(this, reader); // if emit is pending, a non-character token was found: return any chars in buffer, and leave token for next read: if (charsBuilder.length() > 0) { String str = charsBuilder.toString(); charsBuilder.delete(0, charsBuilder.length()); charsString = null; return charPending.data(str); } else if (charsString != null) { Token token = charPending.data(charsString); charsString = null; return token; } else { isEmitPending = false; return emitPending; } } void emit(Token token) { Validate.isFalse(isEmitPending, "There is an unread token pending!"); emitPending = token; isEmitPending = true; if (token.type == Token.TokenType.StartTag) { Token.StartTag startTag = (Token.StartTag) token; lastStartTag = startTag.tagName; if (startTag.selfClosing) selfClosingFlagAcknowledged = false; } else if (token.type == Token.TokenType.EndTag) { Token.EndTag endTag = (Token.EndTag) token; if (endTag.attributes != null) error("Attributes incorrectly present on end tag"); } } void emit(final String str) { // buffer strings up until last string token found, to emit only one token for a run of character refs etc. // does not set isEmitPending; read checks that if (charsString == null) { charsString = str; } else { if (charsBuilder.length() == 0) { // switching to string builder as more than one emit before read charsBuilder.append(charsString); } charsBuilder.append(str); } } void emit(char[] chars) { emit(String.valueOf(chars)); } void emit(int[] codepoints) { emit(new String(codepoints, 0, codepoints.length)); } void emit(char c) { emit(String.valueOf(c)); } TokeniserState getState() { return state; } void transition(TokeniserState state) { this.state = state; } void advanceTransition(TokeniserState state) { reader.advance(); this.state = state; } void acknowledgeSelfClosingFlag() { selfClosingFlagAcknowledged = true; } final private int[] codepointHolder = new int[1]; // holder to not have to keep creating arrays final private int[] multipointHolder = new int[2]; int[] consumeCharacterReference(Character additionalAllowedCharacter, boolean inAttribute) { if (reader.isEmpty()) return null; if (additionalAllowedCharacter != null && additionalAllowedCharacter == reader.current()) return null; if (reader.matchesAnySorted(notCharRefCharsSorted)) return null; final int[] codeRef = codepointHolder; reader.mark(); if (reader.matchConsume("#")) { // numbered boolean isHexMode = reader.matchConsumeIgnoreCase("X"); String numRef = isHexMode ? reader.consumeHexSequence() : reader.consumeDigitSequence(); if (numRef.length() == 0) { // didn't match anything characterReferenceError("numeric reference with no numerals"); reader.rewindToMark(); return null; } if (!reader.matchConsume(";")) characterReferenceError("missing semicolon"); // missing semi int charval = -1; try { int base = isHexMode ? 16 : 10; charval = Integer.valueOf(numRef, base); } catch (NumberFormatException e) { } // skip if (charval == -1 || (charval >= 0xD800 && charval <= 0xDFFF) || charval > 0x10FFFF) { characterReferenceError("character outside of valid range"); codeRef[0] = replacementChar; return codeRef; } else { // todo: implement number replacement table // todo: check for extra illegal unicode points as parse errors codeRef[0] = charval; return codeRef; } } else { // named // get as many letters as possible, and look for matching entities. String nameRef = reader.consumeLetterThenDigitSequence(); boolean looksLegit = reader.matches(';'); // found if a base named entity without a ;, or an extended entity with the ;. boolean found = (Entities.isBaseNamedEntity(nameRef) || (Entities.isNamedEntity(nameRef) && looksLegit)); if (!found) { reader.rewindToMark(); if (looksLegit) // named with semicolon characterReferenceError(String.format("invalid named referenece '%s'", nameRef)); return null; } if (inAttribute && (reader.matchesLetter() || reader.matchesDigit() || reader.matchesAny('=', '-', '_'))) { // don't want that to match reader.rewindToMark(); return null; } if (!reader.matchConsume(";")) characterReferenceError("missing semicolon"); // missing semi int numChars = Entities.codepointsForName(nameRef, multipointHolder); if (numChars == 1) { codeRef[0] = multipointHolder[0]; return codeRef; } else if (numChars ==2) { return multipointHolder; } else { Validate.fail("Unexpected characters returned for " + nameRef); return multipointHolder; } } } Token.Tag createTagPending(boolean start) { tagPending = start ? startPending.reset() : endPending.reset(); return tagPending; } void emitTagPending() { tagPending.finaliseTag(); emit(tagPending); emit(tagPending); } void createCommentPending() { commentPending.reset(); } void emitCommentPending() { emit(commentPending); } void createDoctypePending() { doctypePending.reset(); } void emitDoctypePending() { emit(doctypePending); } void createTempBuffer() { Token.reset(dataBuffer); } boolean isAppropriateEndTagToken() { return lastStartTag != null && tagPending.name().equalsIgnoreCase(lastStartTag); } String appropriateEndTagName() { if (lastStartTag == null) return null; return lastStartTag; } void error(TokeniserState state) { if (errors.canAddError()) errors.add(new ParseError(reader.pos(), "Unexpected character '%s' in input state [%s]", reader.current(), state)); } void eofError(TokeniserState state) { if (errors.canAddError()) errors.add(new ParseError(reader.pos(), "Unexpectedly reached end of file (EOF) in input state [%s]", state)); } private void characterReferenceError(String message) { if (errors.canAddError()) errors.add(new ParseError(reader.pos(), "Invalid character reference: %s", message)); } private void error(String errorMsg) { if (errors.canAddError()) errors.add(new ParseError(reader.pos(), errorMsg)); } boolean currentNodeInHtmlNS() { // todo: implement namespaces correctly return true; // Element currentNode = currentNode(); // return currentNode != null && currentNode.namespace().equals("HTML"); } /** * Utility method to consume reader and unescape entities found within. * @param inAttribute * @return unescaped string from reader */ String unescapeEntities(boolean inAttribute) { StringBuilder builder = new StringBuilder(); while (!reader.isEmpty()) { builder.append(reader.consumeTo('&')); if (reader.matches('&')) { reader.consume(); int[] c = consumeCharacterReference(null, inAttribute); if (c == null || c.length==0) builder.append('&'); else { builder.appendCodePoint(c[0]); if (c.length == 2) builder.appendCodePoint(c[1]); } } } return builder.toString(); } }
[ "justinwm@163.com" ]
justinwm@163.com
0e865349ae2fc84af0673977f6f1c1bfaca4a371
eb6097f4924e8a2e03f40dbd01cd73465a7175b7
/chatcommon/src/main/java/com/crazymakercircle/im/common/codec/ProtobufDecoder.java
c7117986bd19dee1f128590dc46ef5f3a5526b76
[]
no_license
J-doIt/Java-high-concurrency-core-Programming-Volume-2-source-code-master
8ae4ba6abce791a2505c946ca032ad52ad3c23b7
e28307d5c71e2d2d568329135dfff9d67a4faf7e
refs/heads/main
2023-09-01T09:27:02.546020
2021-10-14T15:41:29
2021-10-14T15:41:29
417,183,435
1
1
null
null
null
null
UTF-8
Java
false
false
1,806
java
package com.crazymakercircle.im.common.codec; import com.crazymakercircle.im.common.bean.msg.ProtoMsg; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import lombok.extern.slf4j.Slf4j; import java.util.List; /** * 解码器 */ @Slf4j public class ProtobufDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // 标记一下当前的readIndex的位置 in.markReaderIndex(); // 判断包头长度 if (in.readableBytes() < 2) {// 不够包头 return; } // 读取传送过来的消息的长度。 int length = in.readUnsignedShort(); // 长度如果小于0 if (length < 0) {// 非法数据,关闭连接 ctx.close(); } if (length > in.readableBytes()) {// 读到的消息体长度如果小于传送过来的消息长度 // 重置读取位置 in.resetReaderIndex(); return; } byte[] array; int offset = 0; if (in.hasArray()) { //堆缓冲 // offset = in.arrayOffset() + in.readerIndex(); ByteBuf slice = in.slice(); array = slice.array(); } else { //直接缓冲 array = new byte[length]; in.readBytes(array, 0, length); } // 字节转成对象 ProtoMsg.Message outmsg = ProtoMsg.Message.parseFrom(array); if (outmsg != null) { // 获取业务消息头 out.add(outmsg); } } }
[ "j_doit@163.com" ]
j_doit@163.com
7bea9a86d0e8b80379ee22f701c2cfe2631ef113
c680404b8ccadf7d87d53188118005e4be483a90
/app/src/main/java/com/example/a11n015/webservi/Hero.java
8a6a94356192f772b2cfc6da71473d2ca25d2d1e
[]
no_license
CesarStapler/WebServi
49462f6df625f8e74f9dcedf39e53e81472c38ed
a93e57fd1ace55a254d05d149f3b3d1be334c47c
refs/heads/master
2020-04-09T03:17:46.146773
2018-12-01T18:52:14
2018-12-01T18:52:14
159,976,771
0
0
null
null
null
null
UTF-8
Java
false
false
1,232
java
package com.example.a11n015.webservi; public class Hero { private String name; private String realname; private String team; private String firstapparance; private String createdby; private String publisher; private String imageur1; private String bio; public Hero(String name, String realname, String team, String firstapparance, String createdby, String publisher, String imageur1, String bio) { this.name = name; this.realname = realname; this.team = team; this.firstapparance = firstapparance; this.createdby = createdby; this.publisher = publisher; this.imageur1 = imageur1; this.bio = bio; } public String getName() { return name; } public String getRealname() { return realname; } public String getTeam() { return team; } public String getFirstapparance() { return firstapparance; } public String getCreatedby() { return createdby; } public String getPublisher() { return publisher; } public String getImageur1() { return imageur1; } public String getBio() { return bio; } }
[ "43658422+CesarStapler@users.noreply.github.com" ]
43658422+CesarStapler@users.noreply.github.com
39978f4ade5bd9eeced4409c762eefdbd0aaafff
5771d855d3856ae5b89ffa06b49b49394816ae7b
/src/main/java/pkk/interview/service/PersonServiceImpl.java
f1260162216174d257f39d90f45cfa5a3415aaf8
[]
no_license
assent222/mvc-rest-hateoas-integration
8c27d1278bf66e744fd25a786e17f6650a97a972
3b1ef2c17c4556dc32f64840b54a55f930e11456
refs/heads/master
2021-01-11T16:34:04.954419
2017-01-26T11:57:45
2017-01-26T11:57:45
80,110,744
0
0
null
null
null
null
UTF-8
Java
false
false
1,174
java
package pkk.interview.service; import org.springframework.stereotype.Service; import pkk.interview.domain.Person; import java.util.*; /** * Created by root on 26.01.2017. */ @Service public class PersonServiceImpl implements PersonService { private Map<Integer, Person> repository = new HashMap<>(); private int cnt; public PersonServiceImpl() { repository.put(1, new Person(1, "Ivan")); repository.put(2, new Person(2, "Petr")); repository.put(3, new Person(3, "Karl")); cnt = 3; } @Override public List<Person> findAll() { return Collections.unmodifiableList(new ArrayList<>(repository.values())); } @Override public Person find(Integer id) { return repository.get(id); } @Override public Person create(Person entity) { entity.setId(cnt++); repository.put(cnt, entity); return entity; } @Override public Person update(Person entity) { repository.put(entity.getId(), entity); return entity; } @Override public Person delete(Person entity) { return repository.remove(entity.getId()); } }
[ "assent222@gmail.com" ]
assent222@gmail.com
9ef2d7ac68709ccea491b491e6f11c5776cf0f1c
a6522923e0e1db198430d1f27fef5cd11cdfbc0b
/app/src/main/java/com/irfan/ilham/tugasakhir/ManageCategoryActivity.java
b7033699cff84504f4f70e80588bcddc6224a63d
[]
no_license
smkn4malang/smkcoding_Vishare
ec6b38e971620a7af49ff1e8dc4a83138e1c7620
7c9f7a56f0df01f557fd64f6b8f28ac46a467291
refs/heads/master
2020-03-27T06:55:06.276577
2018-10-19T02:04:35
2018-10-19T02:04:35
146,146,613
3
0
null
null
null
null
UTF-8
Java
false
false
8,987
java
package com.irfan.ilham.tugasakhir; import android.content.DialogInterface; import android.content.Intent; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import static com.irfan.ilham.tugasakhir.R.style.AlertDialogCustom; public class ManageCategoryActivity extends AppCompatActivity { private RecyclerView listUser; private DatabaseReference mDatabase; private Button add; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manage_category); listUser = findViewById(R.id.manageKategoriRecycleView); add = findViewById(R.id.addKategoriManager); listUser.setHasFixedSize(true); listUser.setLayoutManager(new LinearLayoutManager(ManageCategoryActivity.this)); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { add(); } }); } @Override protected void onStart() { super.onStart(); mDatabase = FirebaseDatabase.getInstance().getReference("Kategori"); FirebaseRecyclerAdapter<KategoriItems, ManageCategoryActivity.ViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<KategoriItems, ViewHolder>(KategoriItems.class, R.layout.item_category_manager, ManageCategoryActivity.ViewHolder.class, mDatabase) { @Override protected void populateViewHolder(ViewHolder viewHolder, KategoriItems model, int position) { viewHolder.setNama(model.getNamaKategori()); final String Uid = model.getNamaKategori(); viewHolder.update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { update(Uid); } }); viewHolder.delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { delete(Uid); } }); } }; listUser.setAdapter(firebaseRecyclerAdapter); } public static class ViewHolder extends RecyclerView.ViewHolder { View mView; TextView delete, update; public ViewHolder(View itemView) { super(itemView); mView = itemView; update = mView.findViewById(R.id.updateBtnKategoriItem); delete = mView.findViewById(R.id.deleteBtnKategoriItem); } public void setNama(String nama) { TextView nama_view = mView.findViewById(R.id.namaKategoriItem); nama_view.setText(nama); } } @Override public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(this, AdminHomeActivity.class)); finish(); } private void update(final String Uid) { mDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (final DataSnapshot ds : dataSnapshot.getChildren()) { String key = ds.child("namaKategori").getValue().toString(); final String key2 = ds.getKey().toString(); if (key.equals(Uid)) { AlertDialog.Builder builder = new AlertDialog.Builder(ManageCategoryActivity.this, R.style.Theme_AppCompat_DayNight_Dialog_Alert); LayoutInflater layoutInflater = LayoutInflater.from(ManageCategoryActivity.this); final View myView = layoutInflater.inflate(R.layout.dialog_add_kategori, null); TextView tv = myView.findViewById(R.id.AddKategoriDialog); tv.setText(key); builder.setView(myView); builder.setPositiveButton("Edit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String namaKategori; EditText namaInput = myView.findViewById(R.id.AddKategoriDialog); namaKategori = namaInput.getText().toString().trim(); FirebaseDatabase.getInstance().getReference("Kategori").child(key2).child("namaKategori").setValue(namaKategori); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void delete(final String Uid) { mDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (final DataSnapshot ds : dataSnapshot.getChildren()) { String key = ds.child("namaKategori").getValue().toString(); if (key.equals(Uid)) { AlertDialog.Builder builder = new AlertDialog.Builder(ManageCategoryActivity.this, R.style.Theme_AppCompat_DayNight_Dialog_Alert); LayoutInflater layoutInflater = LayoutInflater.from(ManageCategoryActivity.this); builder.setTitle("Delete!"); builder.setMessage("Are you sure to delete " + Uid + " ?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ds.getRef().removeValue(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void add() { AlertDialog.Builder builder = new AlertDialog.Builder(ManageCategoryActivity.this, R.style.Theme_AppCompat_DayNight_Dialog_Alert); LayoutInflater layoutInflater = LayoutInflater.from(ManageCategoryActivity.this); final View myView = layoutInflater.inflate(R.layout.dialog_add_kategori, null); builder.setView(myView); builder.setPositiveButton("Add", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String namaKategori; EditText namaInput = myView.findViewById(R.id.AddKategoriDialog); namaKategori = namaInput.getText().toString().trim(); FirebaseDatabase.getInstance().getReference("Kategori").push().child("namaKategori").setValue(namaKategori); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }
[ "irfanswag94@gmail.com" ]
irfanswag94@gmail.com
da5be4a657fae626247143841ce6739a96c8b8c5
f04324aafad85857bab6b9717828fdc8eb844ee8
/src/test/java/bdd/ups/runner/UpsTestRunner.java
fb6f9d3cf07e15cadb3d091faefc8e14884bcc2c
[]
no_license
prioti27/UPSTracking
8c7cf64e4996acac8fd6ac73667ece8613c03c87
0666c151e8a265373032bf680ba7f8f4ae396039
refs/heads/master
2023-05-11T04:51:49.370244
2020-05-16T12:39:52
2020-05-16T12:39:52
264,433,383
0
0
null
2023-05-09T18:22:37
2020-05-16T12:36:04
HTML
UTF-8
Java
false
false
792
java
package bdd.ups.runner; import java.io.File; import org.testng.annotations.AfterClass; import com.cucumber.listener.Reporter; import cucumber.api.CucumberOptions; import cucumber.api.testng.AbstractTestNGCucumberTests; @CucumberOptions(features={"src/test/resources/Features"},glue={"bdd.ups.stepDef","bdd.ups.utilities"}, tags={"@Tracking"}, plugin = {"pretty", "html:target/cucumber-htmlreport", "json:target/cucumber-jsonreport/cucumber-report.json", "com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report.html"}, monochrome = true) public class UpsTestRunner extends AbstractTestNGCucumberTests{ @AfterClass public static void generateExtentReport(){ Reporter.loadXMLConfig(new File("config/config.xml")); } }
[ "tprioti@aol.com" ]
tprioti@aol.com
7ac41b1102da1a2a95507742dc3fcfa6cbfba753
112068e97e02e9ac2a2b4f3b91e4ba5a821581a1
/src/main/java/model/MainModel.java
648c55d8ae6de7bb942f9f166e42292e0502428e
[]
no_license
Ozinskiy/MVC_example
784f3ecbd737bec2e5eb578f7613c88fa67dc6da
e30fdaa5dcea2d5fe5603e74b08f2f096b11014f
refs/heads/master
2023-04-13T11:10:59.302176
2021-04-19T11:46:05
2021-04-19T11:46:05
359,438,494
0
0
null
null
null
null
UTF-8
Java
false
false
1,478
java
package model; import bean.User; import model.service.UserService; import model.service.UserServiceImpl; import java.util.List; public class MainModel implements Model{ private UserService userService = new UserServiceImpl(); private ModelData modelData = new ModelData(); @Override public ModelData getModelData() { return modelData; } @Override public void loadUsers() { List<User> users = getAllUsers(); modelData.setUsers(users); modelData.setDisplayDeletedUserList(false); } public void loadDeletedUsers() { List<User> users = userService.getAllDeletedUsers(); modelData.setUsers(users); modelData.setDisplayDeletedUserList(true); } public void loadUserById(long userId) { User user = userService.getUsersById(userId); modelData.setActiveUser(user); } @Override public void deleteUserById(long id) { userService.deleteUser(id); List<User> users = getAllUsers(); modelData.setUsers(users); } private List<User> getAllUsers() { List<User> allUsers = userService.getUsersBetweenLevels(1, 100); allUsers = userService.filterOnlyActiveUsers(allUsers); return allUsers; } public void changeUserData(String name, long id, int level) { userService.createOrUpdateUser(name, id, level); List<User> users = getAllUsers(); modelData.setUsers(users); } }
[ "victor.gusev94@yandex.ru" ]
victor.gusev94@yandex.ru
76934cb415462c4fded03e8418e4c04de47ee5c5
b3375bb3c1c32f09759da3469fa2ea1f188918b6
/src/test/java/ca/gedge/manatee/TestReceiverA.java
8b39f28b875b3f87cd825e5f8b9344dce037ce9d
[ "MIT" ]
permissive
thegedge/manatee
83d87b9e9f2d14e5caa9c4a3c481ce3534523dec
2db4f9a753162ed97bcd71c83b9b4522a8fe8e74
refs/heads/main
2021-08-02T00:15:59.354793
2021-07-26T17:22:34
2021-07-26T17:22:34
7,361,598
0
0
MIT
2021-07-26T17:22:35
2012-12-29T00:58:11
Java
UTF-8
Java
false
false
1,977
java
/* * Copyright (C) 2012 Jason Gedge <http://www.gedge.ca> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package ca.gedge.manatee; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; public class TestReceiverA implements MessageReceiver { final Map<String, List<Object[]>> calls = new Hashtable<String, List<Object[]>>(); public TestReceiverA() { calls.put(TestSender.MESSAGE_A, new ArrayList<Object[]>()); calls.put(TestSender.MESSAGE_B, new ArrayList<Object[]>()); calls.put(TestSender.MESSAGE_AB, new ArrayList<Object[]>()); } @ReceiverMethod(senderClass=TestSender.class, message=TestSender.MESSAGE_A) public void messageA() { calls.get(TestSender.MESSAGE_A).add(new Object[0]); } @ReceiverMethod(senderClass=TestSender.class, message=TestSender.MESSAGE_AB) public void messageAB(String a, Integer b) { calls.get(TestSender.MESSAGE_AB).add(new Object[]{a, b}); } }
[ "inferno1386@gmail.com" ]
inferno1386@gmail.com
105774d4ee0d25e37f498b765c1ba7aaa93a7b48
e0fe6141ec1fa4e25c000df8c6a14d63c0fd151d
/src/main/java/ru/itis/darZam/models/Cash.java
ed7821f89d33b642ade027851832057836cadf64
[]
no_license
daniszam/bankservice
d5dc9ec24b1d27b1675814da61993e15f2be5ce0
eb51cbe4b0381f7b4c62f8586b178dbbb9fe8a6b
refs/heads/master
2020-04-01T23:43:10.718895
2019-05-17T19:28:58
2019-05-17T19:28:58
153,770,173
0
0
null
null
null
null
UTF-8
Java
false
false
603
java
package ru.itis.darZam.models; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.Table; import java.sql.Date; import java.util.Set; @NoArgsConstructor @Data @Entity @Table(name = "cash") public class Cash extends Balance { @Builder public Cash(String name, Icon icon, Float balance, Long id, User user, Float upSum, Set<Transaction> transactions, Date upDate, Set<Credit> credits){ super(id, upDate, balance, name, icon, user, upSum, transactions, credits); } }
[ "daniszamaliev@gmail.com" ]
daniszamaliev@gmail.com
ecfc4bdf846ab4d0a165d4f942bfdc8e80487005
9f8522ee553ed70476a06aa32ff5a99a3b5265b2
/app/src/main/java/com/chicv/pda/adapter/TransferLoseAdapter.java
39ac473883b2e8a8509bd89c54d84d13bd4e2dcc
[]
no_license
htybay/pda
83a209e3563c66737760ef4368f159d00ccdc165
89c76401c71c4b4685ad08ed16846a75e82e112c
refs/heads/master
2022-02-24T21:03:45.507879
2019-10-29T09:18:05
2019-10-29T09:18:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
935
java
package com.chicv.pda.adapter; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.chicv.pda.R; import com.chicv.pda.bean.TransferPickGoods; import com.chicv.pda.utils.BarcodeUtils; /** * @author lilaoda * date: 2019/5/26 0026 * email:liheyu999@163.com * description: 调拨丢失 */ public class TransferLoseAdapter extends BaseQuickAdapter<TransferPickGoods, BaseViewHolder> { public TransferLoseAdapter() { super(R.layout.item_transfer_lose); } @Override protected void convert(BaseViewHolder helper, TransferPickGoods item) { String wpCode = BarcodeUtils.generateWPBarcode(item.getGoodsId()); helper.setText(R.id.text_product_num, wpCode); helper.setText(R.id.text_rule, item.getBatchCode()); helper.setBackgroundRes(R.id.ll_root, item.isIsPick() ? R.color.blue_light : R.color.white); } }
[ "liheyu@chicv.com" ]
liheyu@chicv.com
6737f2c01c6f5920f4a1f52e576a1f05f31bf018
5bc86505b2895d50fd1024eadbaa894eed3d11e8
/src/main/java/com/chuangshu/livable/base/dto/BaseDTO.java
7d4d443e756a1f6234875f82af082fd98ffc3687
[]
no_license
wws0516/livable
a587860c60488d7b5dc0514b03e2112a6ba5cb8b
4e5fcfff083acde1d3498969fdca4def488acd3b
refs/heads/master
2022-07-18T11:05:24.340870
2020-06-02T11:09:25
2020-06-02T11:09:25
221,178,745
1
0
null
null
null
null
UTF-8
Java
false
false
326
java
package com.chuangshu.livable.base.dto; import net.sf.json.JSONObject; import java.io.Serializable; public abstract class BaseDTO implements Serializable { private static final long serialVersionUID = 4035984879657965692L; @Override public String toString() { return JSONObject.fromObject(this).toString(); } }
[ "769015616@qq.com" ]
769015616@qq.com
4740a8e0758712f4360aa27df84dfbc21ec8b976
1690695c7863ec512c4903d7e4688bd417ee8cfb
/easeui/src/cn/ucai/easeui/widget/EaseSwitchButton.java
a3336ec4aed6bd06248128a72780e929fe43c5dd
[ "Apache-2.0" ]
permissive
caonimammp/superwechat
5b056b6acfe0e26a5e5878b2133906d7dfe66a42
cbd3e731f182121b92541b1573614964cee56e4b
refs/heads/master
2021-01-21T11:50:30.339502
2017-06-06T13:24:39
2017-06-06T13:24:39
91,757,563
0
0
null
null
null
null
UTF-8
Java
false
false
2,162
java
package cn.ucai.easeui.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; public class EaseSwitchButton extends FrameLayout{ private ImageView openImage; private ImageView closeImage; public EaseSwitchButton(Context context, AttributeSet attrs, int defStyle) { this(context, attrs); } public EaseSwitchButton(Context context) { this(context, null); } public EaseSwitchButton(Context context, AttributeSet attrs) { super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs, cn.ucai.easeui.R.styleable.EaseSwitchButton); Drawable openDrawable = ta.getDrawable(cn.ucai.easeui.R.styleable.EaseSwitchButton_switchOpenImage); Drawable closeDrawable = ta.getDrawable(cn.ucai.easeui.R.styleable.EaseSwitchButton_switchCloseImage); int switchStatus = ta.getInt(cn.ucai.easeui.R.styleable.EaseSwitchButton_switchStatus, 0); ta.recycle(); LayoutInflater.from(context).inflate(cn.ucai.easeui.R.layout.ease_widget_switch_button, this); openImage = (ImageView) findViewById(cn.ucai.easeui.R.id.iv_switch_open); closeImage = (ImageView) findViewById(cn.ucai.easeui.R.id.iv_switch_close); if(openDrawable != null){ openImage.setImageDrawable(openDrawable); } if(closeDrawable != null){ closeImage.setImageDrawable(closeDrawable); } if(switchStatus == 1){ closeSwitch(); } } /** * is switch open */ public boolean isSwitchOpen(){ return openImage.getVisibility() == View.VISIBLE; } public void openSwitch(){ openImage.setVisibility(View.VISIBLE); closeImage.setVisibility(View.INVISIBLE); } public void closeSwitch(){ openImage.setVisibility(View.INVISIBLE); closeImage.setVisibility(View.VISIBLE); } }
[ "kkkkkkkkkkkop.qq.com" ]
kkkkkkkkkkkop.qq.com
3eb9238e050de379802128448a60705bdcb716c2
e5a8e19672b065a2e4c416ab3cfa47dd88e4d07f
/src/model/Venda.java
207f6de0d329a0ac24cc75febd836a522dee5683
[]
no_license
walteraragao/unigranrio-devweb-ap3
282d02dc01441d7fc69150821ee8651c64191743
eec7ee6083da11eec52ae5b02d7403b1e8c25bc5
refs/heads/master
2023-01-07T14:53:16.690751
2020-11-05T17:20:47
2020-11-05T17:20:47
310,369,338
0
0
null
null
null
null
UTF-8
Java
false
false
2,737
java
package model; import java.util.Date; import model.enums.StatusVendaEnum; public class Venda { private Integer codigo; private Motocicleta motocicleta; private Cliente cliente; private StatusVendaEnum statusVendaEnum; private double subtotal; private double desconto; private double total; private Date dataVenda; public Venda() { // TODO Auto-generated constructor stub } public Venda(Integer codigo, Motocicleta motocicleta, Cliente cliente, StatusVendaEnum statusVendaEnum, double subtotal, double desconto, double total, Date dataVenda) { super(); this.codigo = codigo; this.motocicleta = motocicleta; this.cliente = cliente; this.statusVendaEnum = statusVendaEnum; this.subtotal = subtotal; this.desconto = desconto; this.total = total; this.dataVenda = dataVenda; } @Override public String toString() { return "Venda [codigo=" + codigo + ", motocicleta=" + motocicleta + ", cliente=" + cliente + ", statusVendaEnum=" + statusVendaEnum + ", subtotal=" + subtotal + ", desconto=" + desconto + ", total=" + total + ", dataVenda=" + dataVenda + "]"; } public Integer getCodigo() { return codigo; } public void setCodigo(Integer codigo) { this.codigo = codigo; } public Motocicleta getMotocicleta() { return motocicleta; } public void setMotocicleta(Motocicleta motocicleta) { this.motocicleta = motocicleta; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public StatusVendaEnum getStatusVendaEnum() { return statusVendaEnum; } public void setStatusVendaEnum(StatusVendaEnum statusVendaEnum) { this.statusVendaEnum = statusVendaEnum; } public double getSubtotal() { return subtotal; } public void setSubtotal(double subtotal) { this.subtotal = subtotal; } public double getDesconto() { return desconto; } public void setDesconto(double desconto) { this.desconto = desconto; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } public Date getDataVenda() { return dataVenda; } public void setDataVenda(Date dataVenda) { this.dataVenda = dataVenda; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Venda other = (Venda) obj; if (codigo == null) { if (other.codigo != null) return false; } else if (!codigo.equals(other.codigo)) return false; return true; } }
[ "BP12242@adgroup.michelin.com" ]
BP12242@adgroup.michelin.com
d86b2fd271abdf382a10b70225aa60a567c714ab
4833796ee2fc22c0f9ee9e6283c3c42ba21884f4
/icss-trans/src/main/java/com/lantone/icss/trans/langtong/model/response/kl/ListExamineDetailWrapper.java
7a185d52abb255376016405715b20f6b15c124ca
[]
no_license
gongyi666/icss
9a45b00632d87f70817765b03db0d5f647b84c34
959b92f06aa5cc974157ef60b1d3e5d56b49edee
refs/heads/master
2020-12-03T05:08:39.331169
2017-06-29T05:37:44
2017-06-29T05:37:44
95,735,766
0
0
null
null
null
null
UTF-8
Java
false
false
2,105
java
package com.lantone.icss.trans.langtong.model.response.kl; import java.io.Serializable; public class ListExamineDetailWrapper implements Serializable{ private static final long serialVersionUID = 1L; //检查检验ID private String examineId; //序号 private String exdNum; //检查项目ID private String itemId; //检查项目名称 private String itemName; //单价 private String exdPrice; //数量 private String exdQuantity; //执行医生 private String sffId; //执行科室 private String depId; //优惠单价 private String exdFavorablePrice; //优惠金额 private String exdFavorFee; //单位 private String itemUnit; public String getExamineId() { return examineId; } public void setExamineId(String examineId) { this.examineId = examineId; } public String getExdNum() { return exdNum; } public void setExdNum(String exdNum) { this.exdNum = exdNum; } public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getExdPrice() { return exdPrice; } public void setExdPrice(String exdPrice) { this.exdPrice = exdPrice; } public String getExdQuantity() { return exdQuantity; } public void setExdQuantity(String exdQuantity) { this.exdQuantity = exdQuantity; } public String getSffId() { return sffId; } public void setSffId(String sffId) { this.sffId = sffId; } public String getDepId() { return depId; } public void setDepId(String depId) { this.depId = depId; } public String getExdFavorablePrice() { return exdFavorablePrice; } public void setExdFavorablePrice(String exdFavorablePrice) { this.exdFavorablePrice = exdFavorablePrice; } public String getExdFavorFee() { return exdFavorFee; } public void setExdFavorFee(String exdFavorFee) { this.exdFavorFee = exdFavorFee; } public String getItemUnit() { return itemUnit; } public void setItemUnit(String itemUnit) { this.itemUnit = itemUnit; } }
[ "gaodm@zjlantone.com" ]
gaodm@zjlantone.com
9b3ca687035adc06f4a27cd7ff711e7190d16707
ae66fa93ff303134655bedfd383ec22d2f6ebd61
/arquivos05/src/application/Program.java
f9c79cc5b97c790d5d5c3fc8ac747b4559739474
[ "MIT" ]
permissive
AgnyFonseca/Workspace-Java
145ef621fb32d136400545d55b3680a8eb7cd784
485af4fd3727c5dffba25d27af807f3f928c19a5
refs/heads/master
2023-06-26T20:34:02.869647
2021-08-06T17:34:13
2021-08-06T17:34:13
391,588,380
0
0
null
null
null
null
UTF-8
Java
false
false
750
java
package application; import java.io.File; import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a folder path: "); String strPath = sc.nextLine(); File path = new File(strPath); File[] folders = path.listFiles(File::isDirectory); System.out.println("FOLDERS:"); for (File folder : folders) { System.out.println(folder); } File[] files = path.listFiles(File::isFile); System.out.println("FILES:"); for (File file : files) { System.out.println(file); } boolean success = new File(strPath + "\\subdir").mkdir(); System.out.println("Directory created successfully: " + success); sc.close(); } }
[ "agnyfonseca@outlook.com" ]
agnyfonseca@outlook.com
0de78d58b1c6ed98bd1d6c2d8ab6ecb12c0b28a1
4f76388d76aab2bfbf8ed1898b5d9c211bdb9b5f
/hroauth/src/main/java/com/george/hroauth/config/AuthorizationServerConfig.java
e79a292a2bec96e57b3f37fa9e5f6c51fa432893
[]
no_license
georgemmp/ms-spring-boot
6d1a36c7e7f2f875be4699483df7e44261d640d4
fa9c5948eb1a4570709f9eb07562eecd844f0ea4
refs/heads/master
2023-02-04T13:28:06.175992
2020-12-26T19:36:47
2020-12-26T19:36:47
319,167,367
0
0
null
null
null
null
UTF-8
Java
false
false
2,368
java
package com.george.hroauth.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 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; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private BCryptPasswordEncoder passwordEncoder; @Autowired private JwtAccessTokenConverter accessTokenConverter; @Autowired private JwtTokenStore tokenStore; @Autowired private AuthenticationManager authenticationManager; @Value("${oauth.client.name}") private String oauthClientName; @Value("${oauth.client.secret}") private String oauthClientSecret; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager) .tokenStore(tokenStore) .accessTokenConverter(accessTokenConverter); } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security .tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .inMemory() .withClient(oauthClientName) .secret(this.passwordEncoder.encode(oauthClientSecret)) .scopes("read", "write") .authorizedGrantTypes("password") .accessTokenValiditySeconds(86400); } }
[ "machadogeorge.p@gmail.com" ]
machadogeorge.p@gmail.com
e5dbceebedb62272f2b61f20ca2abdb0eca352f7
eb53ccda07f9f806b026df0d55f4a93dfe0c77f7
/java/week2/w3schools.java
fa3af5a02f399e301acee02c3f57e02f7d52fb5a
[]
no_license
arunthss/Just-Jelly-Mango
019fd690de56822244bca2bc9134f5f0de06db22
5c19704eeb56a20d04d7b24968e3fe673d17051d
refs/heads/master
2016-09-13T04:39:28.200946
2016-04-17T13:58:54
2016-04-17T13:58:54
56,242,656
0
0
null
null
null
null
UTF-8
Java
false
false
1,293
java
package week2; import org.openqa.selenium.Alert; import org.openqa.selenium.firefox.FirefoxDriver; public class w3schools { public static void main(String[] args) { // declare a string variable to store result text String result = ""; // create an object for chrome driver FirefoxDriver driver = new FirefoxDriver(); // open web site driver.get("http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm"); // maximize web page driver.manage().window().maximize(); // switch to frame inside the page from main page driver.switchTo().frame("iframeResult"); // click on button present in frame driver.findElementByTagName("button").click(); // switch control to alert box popped up Alert obj = driver.switchTo().alert(); // obj.dismiss(); to click cancel obj.accept(); // System.out.println(obj.getText()); // after we clicked ok or cancel ctrl will be transferred to calling page, here frame // select text with id called demo from frame and store it to result variable result = driver.findElementById("demo").getText(); // if(result.contains("Cancel")) if(result.contains("OK")) { // if result contains OK then print this System.out.println("Success"); } // close the window driver.close(); } }
[ "rar.chat@gmail.com" ]
rar.chat@gmail.com
ec968462d26b2a4e1e96ae984c7da2f9e21e5b04
23bbedb111bc82534464c69909ddecca8c5426bd
/src/main/java/multithreading/pool/ExecutorServices.java
882d7ed29aab6ec79b37931f6139e73f6c12daf2
[]
no_license
dinamsky/lessons-itmo
84b1b387f91d9974d1a515e8cfa79eb9ef44d0b3
7ba5e55130294b9a319127c3c275deb15a084d83
refs/heads/master
2020-04-28T06:26:06.220151
2019-05-08T10:59:44
2019-05-08T10:59:44
175,058,060
0
0
null
null
null
null
UTF-8
Java
false
false
2,053
java
package multithreading.pool; import java.util.Collections; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; public class ExecutorServices { public static void main(String[] args) { ExecutorService fixedPool = Executors.newFixedThreadPool(2); fixedPool.execute(new RunnableTask("fixedPool")); fixedPool.execute(new RunnableTask("fixedPool2")); fixedPool.execute(new RunnableTask("fixedPool3")); fixedPool.execute(new RunnableTask("fixedPool4")); fixedPool.execute(new RunnableTask("fixedPool5")); fixedPool.shutdown(); ExecutorService singleThread = Executors.newSingleThreadExecutor(); singleThread.execute(new RunnableTask("singleThread")); singleThread.execute(new RunnableTask("singleThread")); singleThread.shutdown(); ExecutorService cachedThread = Executors.newCachedThreadPool(); cachedThread.submit(new RunnableTask("cachedThread")); cachedThread.submit(new RunnableTask("cachedThread")); cachedThread.submit(new RunnableTask("cachedThread")); cachedThread.submit(new RunnableTask("cachedThread")); cachedThread.submit(new RunnableTask("cachedThread")); cachedThread.submit(new RunnableTask("cachedThread")); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); } } class CallableTask implements Callable<Integer>{ String name; @Override public Integer call() throws Exception { System.out.println("Thread: "+ name + " = "+(2+3)); return 2+3; } public CallableTask(String name) { this.name = name; } } class RunnableTask implements Runnable{ String name; @Override public void run() { System.out.println("Runnable thread "+ Thread.currentThread().getName()+ name); } public RunnableTask(String name) { this.name = name; } }
[ "dinamsky@gmail.com" ]
dinamsky@gmail.com
cb7016265c803eb48a3818eea6c4a82df229c09f
c42358d72477faac9cd23c587fba3add74434726
/spring-web-5.3.1-sources/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java
6f58950532d0b5441aa732219861d591e92b3a1c
[]
no_license
abkkm/spring-boot-sources
53e04a4182a01d162bbc9f4f5d95119e1194ebc1
731c4b27962960cfd57752cbebcdfc19c6688258
refs/heads/master
2023-03-17T17:01:39.296319
2021-01-22T09:52:54
2021-01-22T09:52:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,483
java
/* * Copyright 2002-2020 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 * * https://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.accept; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import javax.servlet.ServletContext; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.MediaType; import org.springframework.http.MediaTypeFactory; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.web.context.ServletContextAware; /** * Factory to create a {@code ContentNegotiationManager} and configure it with * {@link ContentNegotiationStrategy} instances. * * <p>This factory offers properties that in turn result in configuring the * underlying strategies. The table below shows the property names, their * default settings, as well as the strategies that they help to configure: * * <table> * <tr> * <th>Property Setter</th> * <th>Default Value</th> * <th>Underlying Strategy</th> * <th>Enabled Or Not</th> * </tr> * <tr> * <td>{@link #setFavorParameter favorParameter}</td> * <td>false</td> * <td>{@link ParameterContentNegotiationStrategy}</td> * <td>Off</td> * </tr> * <tr> * <td>{@link #setFavorPathExtension favorPathExtension}</td> * <td>false (as of 5.3)</td> * <td>{@link PathExtensionContentNegotiationStrategy}</td> * <td>Off</td> * </tr> * <tr> * <td>{@link #setIgnoreAcceptHeader ignoreAcceptHeader}</td> * <td>false</td> * <td>{@link HeaderContentNegotiationStrategy}</td> * <td>Enabled</td> * </tr> * <tr> * <td>{@link #setDefaultContentType defaultContentType}</td> * <td>null</td> * <td>{@link FixedContentNegotiationStrategy}</td> * <td>Off</td> * </tr> * <tr> * <td>{@link #setDefaultContentTypeStrategy defaultContentTypeStrategy}</td> * <td>null</td> * <td>{@link ContentNegotiationStrategy}</td> * <td>Off</td> * </tr> * </table> * * <p>Alternatively you can avoid use of the above convenience builder * methods and set the exact strategies to use via * {@link #setStrategies(List)}. * * <p><strong>Deprecation Note:</strong> As of 5.2.4, * {@link #setFavorPathExtension(boolean) favorPathExtension} and * {@link #setIgnoreUnknownPathExtensions(boolean) ignoreUnknownPathExtensions} * are deprecated in order to discourage using path extensions for content * negotiation and for request mapping with similar deprecations on * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping * RequestMappingHandlerMapping}. For further context, please read issue * <a href="https://github.com/spring-projects/spring-framework/issues/24179">#24719</a>. * @author Rossen Stoyanchev * @author Brian Clozel * @since 3.2 */ public class ContentNegotiationManagerFactoryBean implements FactoryBean<ContentNegotiationManager>, ServletContextAware, InitializingBean { @Nullable private List<ContentNegotiationStrategy> strategies; private boolean favorParameter = false; private String parameterName = "format"; private boolean favorPathExtension = true; private Map<String, MediaType> mediaTypes = new HashMap<>(); private boolean ignoreUnknownPathExtensions = true; @Nullable private Boolean useRegisteredExtensionsOnly; private boolean ignoreAcceptHeader = false; @Nullable private ContentNegotiationStrategy defaultNegotiationStrategy; @Nullable private ContentNegotiationManager contentNegotiationManager; @Nullable private ServletContext servletContext; /** * Set the exact list of strategies to use. * <p><strong>Note:</strong> use of this method is mutually exclusive with * use of all other setters in this class which customize a default, fixed * set of strategies. See class level doc for more details. * @param strategies the strategies to use * @since 5.0 */ public void setStrategies(@Nullable List<ContentNegotiationStrategy> strategies) { this.strategies = (strategies != null ? new ArrayList<>(strategies) : null); } /** * Whether a request parameter ("format" by default) should be used to * determine the requested media type. For this option to work you must * register {@link #setMediaTypes media type mappings}. * <p>By default this is set to {@code false}. * @see #setParameterName */ public void setFavorParameter(boolean favorParameter) { this.favorParameter = favorParameter; } /** * Set the query parameter name to use when {@link #setFavorParameter} is on. * <p>The default parameter name is {@code "format"}. */ public void setParameterName(String parameterName) { Assert.notNull(parameterName, "parameterName is required"); this.parameterName = parameterName; } /** * Whether the path extension in the URL path should be used to determine * the requested media type. * <p>By default this is set to {@code false} in which case path extensions * have no impact on content negotiation. * @deprecated as of 5.2.4. See class-level note on the deprecation of path * extension config options. As there is no replacement for this method, * in 5.2.x it is necessary to set it to {@code false}. In 5.3 the default * changes to {@code false} and use of this property becomes unnecessary. */ @Deprecated public void setFavorPathExtension(boolean favorPathExtension) { this.favorPathExtension = favorPathExtension; } /** * Add a mapping from a key to a MediaType where the key are normalized to * lowercase and may have been extracted from a path extension, a filename * extension, or passed as a query parameter. * <p>The {@link #setFavorParameter(boolean) parameter strategy} requires * such mappings in order to work while the {@link #setFavorPathExtension(boolean) * path extension strategy} can fall back on lookups via * {@link ServletContext#getMimeType} and * {@link MediaTypeFactory}. * <p><strong>Note:</strong> Mappings registered here may be accessed via * {@link ContentNegotiationManager#getMediaTypeMappings()} and may be used * not only in the parameter and path extension strategies. For example, * with the Spring MVC config, e.g. {@code @EnableWebMvc} or * {@code <mvc:annotation-driven>}, the media type mappings are also plugged * in to: * <ul> * <li>Determine the media type of static resources served with * {@code ResourceHttpRequestHandler}. * <li>Determine the media type of views rendered with * {@code ContentNegotiatingViewResolver}. * <li>List safe extensions for RFD attack detection (check the Spring * Framework reference docs for details). * </ul> * @param mediaTypes media type mappings * @see #addMediaType(String, MediaType) * @see #addMediaTypes(Map) */ public void setMediaTypes(Properties mediaTypes) { if (!CollectionUtils.isEmpty(mediaTypes)) { mediaTypes.forEach((key, value) -> addMediaType((String) key, MediaType.valueOf((String) value))); } } /** * An alternative to {@link #setMediaTypes} for programmatic registrations. */ public void addMediaType(String key, MediaType mediaType) { this.mediaTypes.put(key.toLowerCase(Locale.ENGLISH), mediaType); } /** * An alternative to {@link #setMediaTypes} for programmatic registrations. */ public void addMediaTypes(@Nullable Map<String, MediaType> mediaTypes) { if (mediaTypes != null) { mediaTypes.forEach(this::addMediaType); } } /** * Whether to ignore requests with path extension that cannot be resolved * to any media type. Setting this to {@code false} will result in an * {@code HttpMediaTypeNotAcceptableException} if there is no match. * <p>By default this is set to {@code true}. * @deprecated as of 5.2.4. See class-level note on the deprecation of path * extension config options. */ @Deprecated public void setIgnoreUnknownPathExtensions(boolean ignore) { this.ignoreUnknownPathExtensions = ignore; } /** * Indicate whether to use the Java Activation Framework as a fallback option * to map from file extensions to media types. * @deprecated as of 5.0, in favor of {@link #setUseRegisteredExtensionsOnly(boolean)}, * which has reverse behavior. */ @Deprecated public void setUseJaf(boolean useJaf) { setUseRegisteredExtensionsOnly(!useJaf); } /** * When {@link #setFavorPathExtension favorPathExtension} or * {@link #setFavorParameter(boolean)} is set, this property determines * whether to use only registered {@code MediaType} mappings or to allow * dynamic resolution, e.g. via {@link MediaTypeFactory}. * <p>By default this is not set in which case dynamic resolution is on. */ public void setUseRegisteredExtensionsOnly(boolean useRegisteredExtensionsOnly) { this.useRegisteredExtensionsOnly = useRegisteredExtensionsOnly; } private boolean useRegisteredExtensionsOnly() { return (this.useRegisteredExtensionsOnly != null && this.useRegisteredExtensionsOnly); } /** * Whether to disable checking the 'Accept' request header. * <p>By default this value is set to {@code false}. */ public void setIgnoreAcceptHeader(boolean ignoreAcceptHeader) { this.ignoreAcceptHeader = ignoreAcceptHeader; } /** * Set the default content type to use when no content type is requested. * <p>By default this is not set. * @see #setDefaultContentTypeStrategy */ public void setDefaultContentType(MediaType contentType) { this.defaultNegotiationStrategy = new FixedContentNegotiationStrategy(contentType); } /** * Set the default content types to use when no content type is requested. * <p>By default this is not set. * @since 5.0 * @see #setDefaultContentTypeStrategy */ public void setDefaultContentTypes(List<MediaType> contentTypes) { this.defaultNegotiationStrategy = new FixedContentNegotiationStrategy(contentTypes); } /** * Set a custom {@link ContentNegotiationStrategy} to use to determine * the content type to use when no content type is requested. * <p>By default this is not set. * @since 4.1.2 * @see #setDefaultContentType */ public void setDefaultContentTypeStrategy(ContentNegotiationStrategy strategy) { this.defaultNegotiationStrategy = strategy; } /** * Invoked by Spring to inject the ServletContext. */ @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void afterPropertiesSet() { build(); } /** * Create and initialize a {@link ContentNegotiationManager} instance. * @since 5.0 */ @SuppressWarnings("deprecation") public ContentNegotiationManager build() { List<ContentNegotiationStrategy> strategies = new ArrayList<>(); if (this.strategies != null) { strategies.addAll(this.strategies); } else { if (this.favorPathExtension) { PathExtensionContentNegotiationStrategy strategy; if (this.servletContext != null && !useRegisteredExtensionsOnly()) { strategy = new ServletPathExtensionContentNegotiationStrategy(this.servletContext, this.mediaTypes); } else { strategy = new PathExtensionContentNegotiationStrategy(this.mediaTypes); } strategy.setIgnoreUnknownExtensions(this.ignoreUnknownPathExtensions); if (this.useRegisteredExtensionsOnly != null) { strategy.setUseRegisteredExtensionsOnly(this.useRegisteredExtensionsOnly); } strategies.add(strategy); } if (this.favorParameter) { ParameterContentNegotiationStrategy strategy = new ParameterContentNegotiationStrategy(this.mediaTypes); strategy.setParameterName(this.parameterName); if (this.useRegisteredExtensionsOnly != null) { strategy.setUseRegisteredExtensionsOnly(this.useRegisteredExtensionsOnly); } else { strategy.setUseRegisteredExtensionsOnly(true); // backwards compatibility } strategies.add(strategy); } if (!this.ignoreAcceptHeader) { strategies.add(new HeaderContentNegotiationStrategy()); } if (this.defaultNegotiationStrategy != null) { strategies.add(this.defaultNegotiationStrategy); } } this.contentNegotiationManager = new ContentNegotiationManager(strategies); // Ensure media type mappings are available via ContentNegotiationManager#getMediaTypeMappings() // independent of path extension or parameter strategies. if (!CollectionUtils.isEmpty(this.mediaTypes) && !this.favorPathExtension && !this.favorParameter) { this.contentNegotiationManager.addFileExtensionResolvers( new MappingMediaTypeFileExtensionResolver(this.mediaTypes)); } return this.contentNegotiationManager; } @Override @Nullable public ContentNegotiationManager getObject() { return this.contentNegotiationManager; } @Override public Class<?> getObjectType() { return ContentNegotiationManager.class; } @Override public boolean isSingleton() { return true; } }
[ "yaocs2@midea.com" ]
yaocs2@midea.com