hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequence
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequence
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequence
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
92445b243ed670821c9466b6d0e8e942244960db
1,694
java
Java
app/src/main/java/one/empty3/library/core/script/IInterprete.java
manuelddahmen/featureApp
bedd9688944e24486b6a41464b6137a9a60aa9fe
[ "Apache-2.0" ]
null
null
null
app/src/main/java/one/empty3/library/core/script/IInterprete.java
manuelddahmen/featureApp
bedd9688944e24486b6a41464b6137a9a60aa9fe
[ "Apache-2.0" ]
3
2022-02-02T20:28:45.000Z
2022-02-02T20:31:40.000Z
app/src/main/java/one/empty3/library/core/script/IInterprete.java
manuelddahmen/featureApp-launch-ok
3dfeb713b937dee37ba652224fcfe02ace646dd9
[ "Apache-2.0" ]
null
null
null
32.576923
76
0.700708
1,002,979
/* * This file is part of Empty3. * * Empty3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Empty3 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Empty3. If not, see <https://www.gnu.org/licenses/>. 2 */ /* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/> */ /* Vous êtes libre de : */ package one.empty3.library.core.script; import one.empty3.library.*; public interface IInterprete { IInterprete interprete(int TYPE); IInterprete liste(int TYPE); Representable resultat(); Class<Representable> typeResultat(int TYPE); }
92445cb91cd3c50c6c5926ce03a8a86be9d7b9f3
1,781
java
Java
app/src/main/java/com/fafabtc/app/ui/viewholder/BlockchainAssetsViewHolder.java
jastrelax/btc-market
53dfca034bcb22c810698176be8fc5e1f36e0e0c
[ "Apache-2.0" ]
13
2018-09-25T08:42:58.000Z
2020-05-28T02:46:56.000Z
app/src/main/java/com/fafabtc/app/ui/viewholder/BlockchainAssetsViewHolder.java
jastrelax/fafabtc
53dfca034bcb22c810698176be8fc5e1f36e0e0c
[ "Apache-2.0" ]
2
2019-07-25T07:49:46.000Z
2019-08-02T15:35:19.000Z
app/src/main/java/com/fafabtc/app/ui/viewholder/BlockchainAssetsViewHolder.java
jastrelax/fafabtc
53dfca034bcb22c810698176be8fc5e1f36e0e0c
[ "Apache-2.0" ]
5
2018-03-07T05:26:29.000Z
2018-06-14T02:03:33.000Z
36.346939
133
0.720943
1,002,980
package com.fafabtc.app.ui.viewholder; import android.graphics.drawable.Drawable; import android.support.graphics.drawable.VectorDrawableCompat; import android.view.View; import com.fafabtc.app.R; import com.fafabtc.app.databinding.ViewHolderBlockchainAssetsBinding; import com.fafabtc.app.ui.activity.BalanceDepositActivity; import com.fafabtc.app.ui.base.BaseViewHolder; import com.fafabtc.app.ui.base.BindLayout; import com.fafabtc.data.model.entity.exchange.BlockchainAssets; /** * Created by jastrelax on 2018/1/9. */ @BindLayout(value = R.layout.view_holder_blockchain_assets, dataTypes = BlockchainAssets.class) public class BlockchainAssetsViewHolder extends BaseViewHolder<ViewHolderBlockchainAssetsBinding>{ public BlockchainAssetsViewHolder(View itemView) { super(itemView); } @Override public <T> void onBindView(T data, int position) { if (data == null) return; final BlockchainAssets assets = (BlockchainAssets) data; mBinding.setBlockchainAssets(assets); mBinding.executePendingBindings(); Drawable rightArrowDrawable = VectorDrawableCompat.create(itemView.getResources(), R.drawable.ic_keyboard_arrow_right, null); mBinding.btnDeposit.setCompoundDrawablesWithIntrinsicBounds(null, null, rightArrowDrawable, null); mBinding.btnDeposit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { BalanceDepositActivity.start(v.getContext(), assets); } }); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { BalanceDepositActivity.start(v.getContext(), assets); } }); } }
92445d26389cbc83541724a5827a42376b4415bc
453
java
Java
src/Model/EmployeeValidationUtils.java
moimran294/TechTonics
7375d20f255646baa5f2b6f3084bc54c204b2cfa
[ "Apache-2.0" ]
null
null
null
src/Model/EmployeeValidationUtils.java
moimran294/TechTonics
7375d20f255646baa5f2b6f3084bc54c204b2cfa
[ "Apache-2.0" ]
null
null
null
src/Model/EmployeeValidationUtils.java
moimran294/TechTonics
7375d20f255646baa5f2b6f3084bc54c204b2cfa
[ "Apache-2.0" ]
null
null
null
12.942857
45
0.679912
1,002,981
package Model; public class EmployeeValidationUtils { public static int MINLENGTH; public static int MAXLENGTH; public static String a; static { a="@atmecs.com"; MINLENGTH=5; MAXLENGTH=9; } public boolean validateEmail(String email) { if(!email.contains(a)) return false; return true; } public boolean validatePassword(int pass) { if(pass<MINLENGTH || pass>MAXLENGTH) return false; return true; } }
92445d414f8c3c7fa17a43b9ab627b0098c0dfa9
1,036
java
Java
Java Programs/DFS.java
iqbalikku/Hacktoberfest2020-Expert
5ad38cbccca18717ee7ca0b6b72e28c4b2ac1110
[ "MIT" ]
77
2020-10-01T10:06:59.000Z
2021-11-08T08:57:18.000Z
Java Programs/DFS.java
iqbalikku/Hacktoberfest2020-Expert
5ad38cbccca18717ee7ca0b6b72e28c4b2ac1110
[ "MIT" ]
46
2020-09-27T04:55:36.000Z
2021-05-14T18:49:06.000Z
Java Programs/DFS.java
iqbalikku/Hacktoberfest2020-Expert
5ad38cbccca18717ee7ca0b6b72e28c4b2ac1110
[ "MIT" ]
327
2020-09-26T17:06:03.000Z
2021-10-09T06:04:39.000Z
18.5
57
0.416023
1,002,982
import java.util.*; class BucketSort { static void bucketSort(int arr[], int n) { if (n <= 0) return; @SuppressWarnings("unchecked") Vector<Float>[] buckets = new Vector[n]; for (int i = 0; i < n; i++) { buckets[i] = new Vector<Float>(); } for (int i = 0; i < n; i++) { float idx = arr[i] * n; buckets[(int)idx].add(arr[i]); } for (int i = 0; i < n; i++) { Collections.sort(buckets[i]); } int index = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < buckets[i].size(); j++) { arr[index++] = buckets[i].get(j); } } } public static void main(String args[]) { int arr[] = {10,14,8,78,4,66,542,22,14}; int n = arr.length; bucketSort(arr, n); System.out.println("Sorted array is "); for (int el : arr) { System.out.print(el + " "); } } }
92445d4f889d87ee80f7c00b45386d966b24afa5
1,353
java
Java
fwmf-module-user-role/fwmf-module-user-role-service/src/main/java/cn/faury/fwmf/module/service/user/sqlProvider/PushRUserGroupsSQLProvider.java
fzyycp/fwmf-module
36d39a312ad73b0f9a77e96acd614b0ff8cebe4f
[ "Apache-2.0" ]
null
null
null
fwmf-module-user-role/fwmf-module-user-role-service/src/main/java/cn/faury/fwmf/module/service/user/sqlProvider/PushRUserGroupsSQLProvider.java
fzyycp/fwmf-module
36d39a312ad73b0f9a77e96acd614b0ff8cebe4f
[ "Apache-2.0" ]
null
null
null
fwmf-module-user-role/fwmf-module-user-role-service/src/main/java/cn/faury/fwmf/module/service/user/sqlProvider/PushRUserGroupsSQLProvider.java
fzyycp/fwmf-module
36d39a312ad73b0f9a77e96acd614b0ff8cebe4f
[ "Apache-2.0" ]
null
null
null
30.066667
94
0.688101
1,002,983
package cn.faury.fwmf.module.service.user.sqlProvider; import cn.faury.fwmf.module.service.constant.DBConstOfUserRole; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; public class PushRUserGroupsSQLProvider { /** * 日志记录器 */ private static Logger log = LoggerFactory.getLogger(PushRUserGroupsSQLProvider.class); @SuppressWarnings("unchecked") public static String getUserGroupsInfoByMessageId(Map<String, Object> parameter) { // 参数校验 log.debug("parameter ==> " + parameter.toString()); // SQL拼装 StringBuffer sql = new StringBuffer(128); sql.append("SELECT G.ID groupId,G.GROUP_NAME groupName,G.NUM ,G.ORIGIN_OS_ID systemId FROM " + DBConstOfUserRole.TN_CDA_GROUP + " G "); sql.append(" WHERE G.ID IN ("); sql.append(" select CUSTOMER_GROUP_ID from " + DBConstOfUserRole.TN_PUSH_R_CUSTOMER_GROUP); sql.append(" where MESSAGE_ID in ("); List<Long> messageIds = (List<Long>) parameter.get("messageIds"); if (messageIds != null) { if (messageIds.size() > 0) { for (int i = 0; i < messageIds.size(); i++) { sql.append(" #{messageIds[" + i + "]},"); } } } sql.deleteCharAt(sql.length() - 1); sql.append(" ))"); sql.append(" ORDER BY G.ORIGIN_OS_ID,G.ID DESC"); log.debug("SQL ==> " + sql.toString()); return sql.toString(); } }
92445d9b05ac20ca4802edb5174ffa0d1d9af696
9,027
java
Java
src/com/jwkj/activity/SettingBellRingActivity.java
bingo1118/sst
8adce8aa62f3de289191c6fb0cf688f183e598d6
[ "Apache-2.0" ]
null
null
null
src/com/jwkj/activity/SettingBellRingActivity.java
bingo1118/sst
8adce8aa62f3de289191c6fb0cf688f183e598d6
[ "Apache-2.0" ]
null
null
null
src/com/jwkj/activity/SettingBellRingActivity.java
bingo1118/sst
8adce8aa62f3de289191c6fb0cf688f183e598d6
[ "Apache-2.0" ]
null
null
null
31.785211
104
0.740002
1,002,984
package com.jwkj.activity; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Vibrator; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.test.jpushServer.R; import com.jwkj.adapter.BellChoiceAdapter; import com.jwkj.data.SharedPreferencesManager; import com.jwkj.data.SystemDataManager; import com.jwkj.global.Constants; import com.jwkj.utils.T; public class SettingBellRingActivity extends BaseActivity implements OnClickListener{ Button save_btn; ImageView back_btn; ListView list_sys_bell; Vibrator vibrator; MediaPlayer player; RelativeLayout set_bellRing_btn,set_sd_bell_btn; Context context; MyReceiver receiver; TextView selectBell; boolean myreceiverIsReg = false; BellChoiceAdapter adapter; int checkedId; int selectPos; int vibrateState; int bellType; int settingType; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.set_bell_ring); context = this; settingType = getIntent().getIntExtra("type", 0); initCompent(); registerMonitor(); initSelectMusicName(); } public void initCompent() { player = new MediaPlayer(); back_btn = (ImageView) findViewById(R.id.back_btn); save_btn = (Button) findViewById(R.id.save); set_sd_bell_btn = (RelativeLayout) findViewById(R.id.set_sd_bell_btn); selectBell = (TextView) findViewById(R.id.selectBell); list_sys_bell = (ListView) findViewById(R.id.list_sys_bell); initSelectState(); ArrayList<HashMap<String,String>> bells = SystemDataManager.getInstance().getSysBells(this); adapter = new BellChoiceAdapter(this,bells); adapter.setCheckedId(checkedId); list_sys_bell.setAdapter(adapter); list_sys_bell.setSelection(selectPos); list_sys_bell.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub HashMap<String,String> data = (HashMap<String, String>) adapter.getItem(arg2); int id = Integer.parseInt(data.get("bellId")); checkedId = id; selectPos = arg2; adapter.setCheckedId(id); adapter.notifyDataSetChanged(); playMusic(checkedId); } }); set_sd_bell_btn.setOnClickListener(this); save_btn.setOnClickListener(this); back_btn.setOnClickListener(this); } public void initSelectState(){ if(settingType==SettingSystemActivity.SET_TYPE_COMMING_RING){ selectPos = SharedPreferencesManager.getInstance().getCBellSelectPos(this); bellType = SharedPreferencesManager.getInstance().getCBellType(this); if(bellType==SharedPreferencesManager.TYPE_BELL_SYS){ checkedId = SharedPreferencesManager.getInstance().getCSystemBellId(this); selectBell.setText(""); }else{ checkedId = SharedPreferencesManager.getInstance().getCSdBellId(this); HashMap<String,String> data = SystemDataManager.getInstance().findSdBellById(context, checkedId); if(null!=data){ selectBell.setText(data.get("bellName")); } checkedId = -1; selectPos = 1; } }else if(settingType==SettingSystemActivity.SET_TYPE_ALLARM_RING){ selectPos = SharedPreferencesManager.getInstance().getABellSelectPos(this); bellType = SharedPreferencesManager.getInstance().getABellType(this); if(bellType==SharedPreferencesManager.TYPE_BELL_SYS){ checkedId = SharedPreferencesManager.getInstance().getASystemBellId(this); selectBell.setText(""); }else{ checkedId = SharedPreferencesManager.getInstance().getASdBellId(this); HashMap<String,String> data = SystemDataManager.getInstance().findSdBellById(context, checkedId); if(null!=data){ selectBell.setText(data.get("bellName")); } checkedId = -1; selectPos = 1; } } } public void registerMonitor(){ IntentFilter filter = new IntentFilter(); filter.addAction(SettingSystemActivity.ACTION_CHANGEBELL); receiver = new MyReceiver(); this.registerReceiver(receiver, filter); myreceiverIsReg = true; } @Override public void onClick(View view) { // TODO Auto-generated method stub switch(view.getId()){ case R.id.back_btn: this.finish(); break; case R.id.save: if(checkedId==-1){ T.showShort(this, R.string.savebell_error); }else{ if(settingType==SettingSystemActivity.SET_TYPE_COMMING_RING){ SharedPreferencesManager.getInstance().putCSystemBellId(checkedId, this); SharedPreferencesManager.getInstance().putCBellSelectPos(selectPos, this); SharedPreferencesManager.getInstance().putCBellType(SharedPreferencesManager.TYPE_BELL_SYS, this); Intent i = new Intent(); i.setAction(SettingSystemActivity.ACTION_CHANGEBELL); sendBroadcast(i); }else if(settingType==SettingSystemActivity.SET_TYPE_ALLARM_RING){ SharedPreferencesManager.getInstance().putASystemBellId(checkedId, this); SharedPreferencesManager.getInstance().putABellSelectPos(selectPos, this); SharedPreferencesManager.getInstance().putABellType(SharedPreferencesManager.TYPE_BELL_SYS, this); Intent i = new Intent(); i.setAction(SettingSystemActivity.ACTION_CHANGEBELL); sendBroadcast(i); } this.finish(); } break; case R.id.set_sd_bell_btn: Intent go_set_sd_bell = new Intent(this,SettingSdBellActivity.class); go_set_sd_bell.putExtra("type", settingType); startActivity(go_set_sd_bell); break; } } public class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent intent) { // TODO Auto-generated method stub if(intent.getAction().equals(SettingSystemActivity.ACTION_CHANGEBELL)){ initSelectMusicName(); initSelectState(); list_sys_bell.setSelection(selectPos); adapter.setCheckedId(checkedId); adapter.notifyDataSetChanged(); } } } //加载选择的音乐文字 public void initSelectMusicName(){ if(settingType==SettingSystemActivity.SET_TYPE_COMMING_RING){ int cbellType = SharedPreferencesManager.getInstance().getCBellType(this); if(cbellType==SharedPreferencesManager.TYPE_BELL_SYS){ int bellId = SharedPreferencesManager.getInstance().getCSystemBellId(this); HashMap<String,String> data = SystemDataManager.getInstance().findSystemBellById(this, bellId); if(null!=data){ selectBell.setText(""); } }else{ int bellId = SharedPreferencesManager.getInstance().getCSdBellId(this); HashMap<String,String> data = SystemDataManager.getInstance().findSdBellById(this, bellId); if(null!=data){ selectBell.setText(data.get("bellName")); } } }else if(settingType==SettingSystemActivity.SET_TYPE_ALLARM_RING){ int abellType = SharedPreferencesManager.getInstance().getABellType(this); if(abellType==SharedPreferencesManager.TYPE_BELL_SYS){ int bellId = SharedPreferencesManager.getInstance().getASystemBellId(this); HashMap<String,String> data = SystemDataManager.getInstance().findSystemBellById(this, bellId); if(null!=data){ selectBell.setText(""); } }else{ int bellId = SharedPreferencesManager.getInstance().getASdBellId(this); HashMap<String,String> data = SystemDataManager.getInstance().findSdBellById(this, bellId); if(null!=data){ selectBell.setText(data.get("bellName")); } } } } public void playMusic(int bellId){ try { player.reset(); HashMap<String,String> data; data = SystemDataManager.getInstance().findSystemBellById(context, bellId); String path = data.get("path"); if(null==path||"".equals(path)){ }else{ player.setDataSource(path); player.prepare(); player.start(); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onStop() { // TODO Auto-generated method stub super.onStop(); player.stop(); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if(myreceiverIsReg){ this.unregisterReceiver(receiver); } player.stop(); player.release(); } @Override public int getActivityInfo() { // TODO Auto-generated method stub return Constants.ActivityInfo.ACTIVITY_SETTINGBELLRINGACTIVITY; } }
92445df8582f50a74c3069966ea24f090883a956
2,018
java
Java
app/src/main/java/community/fairphone/launcher/PreloadReceiver.java
WeAreFairphone/FairphoneHome
8b40ecc6ccc7cea895595154a7f996054074cc29
[ "Apache-2.0" ]
5
2018-07-03T18:42:46.000Z
2018-12-16T23:19:57.000Z
app/src/main/java/community/fairphone/launcher/PreloadReceiver.java
WeAreFairphone/FP1-Launcher
8b40ecc6ccc7cea895595154a7f996054074cc29
[ "Apache-2.0" ]
10
2018-05-31T09:42:56.000Z
2018-09-08T19:56:06.000Z
app/src/main/java/community/fairphone/launcher/PreloadReceiver.java
WeAreFairphone/FairphoneHome
8b40ecc6ccc7cea895595154a7f996054074cc29
[ "Apache-2.0" ]
1
2018-05-31T09:08:17.000Z
2018-05-31T09:08:17.000Z
38.075472
100
0.675917
1,002,985
/* * Copyright (C) 2012 The Android Open Source Project * Copyright (C) 2013 Fairphone Project * * 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 community.fairphone.launcher; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.util.Log; public class PreloadReceiver extends BroadcastReceiver { private static final String TAG = "Launcher.PreloadReceiver"; private static final boolean LOGD = false; public static final String EXTRA_WORKSPACE_NAME = "com.android.launcher.action.EXTRA_WORKSPACE_NAME"; @Override public void onReceive(Context context, Intent intent) { final LauncherApplication app = (LauncherApplication) context.getApplicationContext(); final LauncherProvider provider = app.getLauncherProvider(); if (provider != null) { String name = intent.getStringExtra(EXTRA_WORKSPACE_NAME); final int workspaceResId = !TextUtils.isEmpty(name) ? context.getResources().getIdentifier(name, "xml", "com.android.launcher") : 0; if (LOGD) { Log.d(TAG, "workspace name: " + name + " id: " + workspaceResId); } new Thread(new Runnable() { @Override public void run() { provider.loadDefaultFavoritesIfNecessary(workspaceResId); } }).start(); } } }
92445ea2eb556b7c062104246323681d395e2c35
2,074
java
Java
build/swig/VixenJava/Sources/Box2.java
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
1
2019-02-13T15:39:56.000Z
2019-02-13T15:39:56.000Z
build/swig/VixenJava/Sources/Box2.java
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
null
null
null
build/swig/VixenJava/Sources/Box2.java
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
2
2017-11-09T12:06:41.000Z
2019-02-13T15:40:02.000Z
24.987952
83
0.62054
1,002,986
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.1 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package Vixen; public class Box2 { private long swigCPtr; protected boolean swigCMemOwn; public Box2(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } public static long getCPtr(Box2 obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; VixenLibJNI.delete_Box2(swigCPtr); } swigCPtr = 0; } } public void setMin(Vec2 value) { VixenLibJNI.Box2_min_set(swigCPtr, this, Vec2.getCPtr(value), value); } public Vec2 getMin() { return new Vec2(VixenLibJNI.Box2_min_get(swigCPtr, this), false); } public void setMax(Vec2 value) { VixenLibJNI.Box2_max_set(swigCPtr, this, Vec2.getCPtr(value), value); } public Vec2 getMax() { return new Vec2(VixenLibJNI.Box2_max_get(swigCPtr, this), false); } public Box2() { this(VixenLibJNI.new_Box2__SWIG_0(), true); } public Box2(float xmin, float xmax, float ymin, float ymax) { this(VixenLibJNI.new_Box2__SWIG_1(xmin, xmax, ymin, ymax), true); } public boolean Contains(Vec2 arg0) { return VixenLibJNI.Box2_Contains(swigCPtr, this, Vec2.getCPtr(arg0), arg0); } public void Set(float xmin, float xmax, float ymin, float ymax) { VixenLibJNI.Box2_Set(swigCPtr, this, xmin, xmax, ymin, ymax); } public float Height() { return VixenLibJNI.Box2_Height(swigCPtr, this); } public float Width() { return VixenLibJNI.Box2_Width(swigCPtr, this); } public Vec2 Center() { return new Vec2(VixenLibJNI.Box2_Center(swigCPtr, this), true); } }
924461aeb1ad7683bbef774142a70ac2567ab3d7
6,697
java
Java
src/main/java/lrgs/common/NetworkListItem.java
adamkorynta/opendcs
0a75fa38dd97cf73ad07edf2c1a978ad15b0270c
[ "Apache-2.0" ]
7
2021-09-21T12:59:16.000Z
2022-03-30T16:39:55.000Z
src/main/java/lrgs/common/NetworkListItem.java
adamkorynta/opendcs
0a75fa38dd97cf73ad07edf2c1a978ad15b0270c
[ "Apache-2.0" ]
20
2015-09-24T02:22:07.000Z
2022-03-29T20:03:56.000Z
src/main/java/lrgs/common/NetworkListItem.java
adamkorynta/opendcs
0a75fa38dd97cf73ad07edf2c1a978ad15b0270c
[ "Apache-2.0" ]
9
2021-03-25T21:43:50.000Z
2022-02-01T02:26:59.000Z
24.264493
76
0.629834
1,002,987
/* * $Id$ * * $Source$ * * $State$ * * $Log$ * Revision 1.6 2008/09/26 20:49:02 mjmaloney * Added <all> and <production> network lists * * Revision 1.5 2008/09/26 14:57:31 mjmaloney * Added <all> and <production> network lists * * Revision 1.4 2008/09/25 15:02:11 mjmaloney * Fixed parsing for string DCP address. * * Revision 1.3 2008/08/19 16:38:15 mjmaloney * DcpAddress stores internal value as String. * * Revision 1.2 2008/08/06 19:40:58 mjmaloney * dev * * Revision 1.1 2008/04/04 18:21:12 cvs * Added legacy code to repository * * Revision 1.7 2001/03/05 22:11:17 mike * Improved parsing logic to handle more text variations. * * Revision 1.6 2001/02/28 01:12:19 mike * Working network list editor. * * Revision 1.5 2001/01/12 15:39:28 mike * Better error reporting when constructing a network list item. All * parsing exceptions should be funnelled into IllegalArgumentException * * Revision 1.4 2000/03/02 20:58:58 mike * Added proper equals() and compareTo() methods. * * Revision 1.3 1999/09/14 17:05:34 mike * 9/14/1999 * * Revision 1.2 1999/09/03 17:22:57 mike * Put in new package hierarchy. * * Revision 1.1 1999/09/03 15:34:52 mike * Initial checkin. * * */ package lrgs.common; import java.io.Serializable; /** Class NetworkListItem holds a single element from a network list file. This item prepresents a data collection platform by name, description, and numeric address. */ public class NetworkListItem implements Serializable, Cloneable, Comparable { public String name; public String description; public char type; public DcpAddress addr; public static final int SORT_BY_ADDR = 0; public static final int SORT_BY_NAME = 1; /** By setting the static integer sortBy to one of the constants, SORT_BY_ADDR or SORT_BY_NAME, you can control the behavior of the compareTo function. */ public static int sortBy = SORT_BY_ADDR; /** Instantiate empty network list item. */ public NetworkListItem() { name = ""; description = ""; type = 'U'; // 'U' == unknown addr = new DcpAddress(); } /** Instantiate a network list item by parsing a string. See the 'fromString' method for a description of the required string format. */ public NetworkListItem(String s) throws IllegalArgumentException { this(); fromString(s); } /** * Copy constructor */ public NetworkListItem(NetworkListItem nli) { this(); name = nli.name; description = nli.description; type = nli.type; // 'U' == unknown addr = new DcpAddress(nli.addr); } public NetworkListItem(DcpAddress addr, String name, String desc) { this(); this.addr = addr; this.name = name; this.description = desc; } /** Return a string representing this DCP in the format: address:name description:type This string is suitable for saving in a network list file. */ public String toString() { String desc = (description == null ? "" : description); return addr.toString() + ":" + name + (desc.length()>0 ? " " : "") + desc + ":" + type; } /** Parse a string and load this object. The string should be in the format suitable for storage in a network list file: address:name description:type where... 'address' is an 8-hex-digit DCP address 'name' is the first blank-delimited word after the colon. 'description' is a brief text description of the DCP (e.g. location) 'type' is a single character code describing the DCP type If the string cannot be parsed, an IllegalArgumentException is thrown. */ public void fromString(String str) throws IllegalArgumentException { try { name = ""; description = ""; type = 'u'; str = str.trim(); int i = str.indexOf(':'); addr = new DcpAddress(i > 0 ? str.substring(0, i) : str); // Get new string after colon. if (i < 0) return; // No name or comment. int len = str.length(); while (++i < len && Character.isWhitespace(str.charAt(i))) ; if (i >= len) return; // No name present. str = str.substring(i); len = str.length(); // First blank delimited word in description field is the name. for(i = 0; i < len && !Character.isWhitespace(str.charAt(i)) && str.charAt(i) != ':'; ++i) ; if (i > 0) name = str.substring(0, i); if (i >= len) return; str = str.substring(i); len = str.length(); // Skip whitepsace between name and comment. for(i=0; i < len && str.charAt(i) == ' '; ++i); if (i >= len) return; // No description if (i > 0) str = str.substring(i); i = str.indexOf(':'); if (i >= 0) { description = str.substring(0, i); type = ++i < str.length() ? str.charAt(i) : 'u'; } else description = str; } catch(Exception e) { throw new IllegalArgumentException( "Bad format for network list item '" + str + "': " + e); } } /** Return true if the passed object is considered equal to 'this'. */ public boolean equals(Object obj) { // For equals() class types must match exactly. if (obj.getClass() != getClass()) return false; return compareTo(obj) == 0; } /** Compare two Network List Items. If the static integer sortBy is set to SORT_BY_ADDR (the default), then the fields are compared in the following order: DCP-Address, DCP-Name, Description, type Conversely, if sortBy is set to SORT_BY_NAME, then the fields are compared in the following order: DCP-Name, DCP-Address, Description, type Note that for name comparisons, a case-insensitive string compare is done. Return: 0 if objects are equal, <0 if 'this' is less than the passed object. Return >0 if 'this is greater than the passed object. */ public int compareTo(Object o) { if (this == o) return 0; if (o == null) return 1; // A null object is always greater than a non-null. // The following will throw an exception if o is not the right type: NetworkListItem rhs = (NetworkListItem)o; int i = 0; if (sortBy == SORT_BY_ADDR) { i = addr.compareTo(rhs.addr); if (i != 0) return i; i = name.compareToIgnoreCase(rhs.name); if (i != 0) return i; } else { i = name.compareToIgnoreCase(rhs.name); if (i != 0) return i; i = addr.compareTo(rhs.addr); if (i != 0) return i; } i = description.compareTo(rhs.description); if (i != 0) return i; i = (int)type - (int)rhs.type; if (i != 0) return i; return 0; // All fields are equal! } }
92446258d1e85d2374e3d5a4139a3f72aa2987ad
303
java
Java
main/src/net/arctics/clonk/c4script/ast/IFunctionCall.java
Meowtimer/C4DT
1f3cc8c405b9ff3e1bf462bcaae3ff11386d8ba0
[ "0BSD" ]
null
null
null
main/src/net/arctics/clonk/c4script/ast/IFunctionCall.java
Meowtimer/C4DT
1f3cc8c405b9ff3e1bf462bcaae3ff11386d8ba0
[ "0BSD" ]
null
null
null
main/src/net/arctics/clonk/c4script/ast/IFunctionCall.java
Meowtimer/C4DT
1f3cc8c405b9ff3e1bf462bcaae3ff11386d8ba0
[ "0BSD" ]
null
null
null
18.9375
69
0.739274
1,002,988
package net.arctics.clonk.c4script.ast; import net.arctics.clonk.ast.ASTNode; /** * Interface implemented by expressions representing a function call. * @author madeen * */ public interface IFunctionCall { ASTNode[] params(); int parmsStart(); int parmsEnd(); int indexOfParm(ASTNode parm); }
9244628bd91a039c1c46585a735de4c0a8ef11c7
964
java
Java
java/src/main/java/leetcode/Problem151ReverseWordsInAString.java
jaredsburrows/Project-Euler
032b60140ee33166df57e8723a532dc4bd7b0faf
[ "Apache-2.0" ]
56
2016-04-21T13:17:55.000Z
2022-03-13T16:32:37.000Z
java/src/main/java/leetcode/Problem151ReverseWordsInAString.java
jaredsburrows/Project-Euler
032b60140ee33166df57e8723a532dc4bd7b0faf
[ "Apache-2.0" ]
4
2016-06-09T04:33:18.000Z
2019-06-09T22:44:14.000Z
java/src/main/java/leetcode/Problem151ReverseWordsInAString.java
jaredsburrows/Project-Euler
032b60140ee33166df57e8723a532dc4bd7b0faf
[ "Apache-2.0" ]
12
2016-11-30T19:09:17.000Z
2022-01-26T22:35:34.000Z
24.1
67
0.511411
1,002,989
package leetcode; /** * https://leetcode.com/problems/reverse-words-in-a-string */ public final class Problem151ReverseWordsInAString { // Time - O(N), Space - O(N) public String reverseWords(String s) { if (s == null) { return ""; } s = s.trim(); if (s.isEmpty()) { return s; } String[] sentence = s.split("\\s+", -1); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0, j = sentence.length - 1; i < j; i++, j--) { swap(sentence, i, j); } for (String word : sentence) { stringBuilder.append(word); stringBuilder.append(" "); } return stringBuilder.toString().trim(); } // Time - O(1), Space - O(1) private void swap(String[] array, int left, int right) { String temp = array[left]; array[left] = array[right]; array[right] = temp; } }
92446385e95d49bb8233ba15b98d4c342640894d
4,433
java
Java
rice-middleware/krms/api/src/main/java/org/kuali/rice/krms/api/engine/TermResolutionException.java
cniesen/rice-playground
7c043822e8d431246c12121d5d609e626bfacd0b
[ "ECL-2.0" ]
2
2017-02-14T20:40:21.000Z
2018-12-05T18:45:26.000Z
rice-middleware/krms/api/src/main/java/org/kuali/rice/krms/api/engine/TermResolutionException.java
cniesen/rice-playground
7c043822e8d431246c12121d5d609e626bfacd0b
[ "ECL-2.0" ]
10
2015-10-12T18:58:39.000Z
2020-11-11T20:17:04.000Z
rice-middleware/krms/api/src/main/java/org/kuali/rice/krms/api/engine/TermResolutionException.java
cniesen/rice-playground
7c043822e8d431246c12121d5d609e626bfacd0b
[ "ECL-2.0" ]
3
2015-01-22T16:28:11.000Z
2021-01-21T09:17:57.000Z
32.152174
118
0.706784
1,002,990
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krms.api.engine; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.kuali.rice.core.api.exception.RiceRuntimeException; import org.springframework.util.CollectionUtils; /** * An Exception for {@link TermResolver} exceptions. * * @author Kuali Rice Team ([email protected]) */ public class TermResolutionException extends RiceRuntimeException { private static final long serialVersionUID = 1L; public final String termResolverClassName; public final String outputTerm; public final Set<String> prereqs; public final Set<String> parameterNames; public final Map<String, String> parameters; /** * Builds the resolution info string from the given values. * @param tr {@link TermResolver} whose values to append to the result String if not null * @param parameters Map<String, String> whose keys and values will be appended to the result String * @return String representing the given values */ private static String buildResolutionInfoString(TermResolver<?> tr, Map<String, String> parameters) { StringBuilder result = new StringBuilder(); result.append("["); result.append(TermResolver.class.getSimpleName() + "="); if (tr == null) { result.append("null"); } else { result.append(tr.toString()); } result.append(", parameters={"); boolean firstEntry = true; if (!CollectionUtils.isEmpty(parameters)) { for (Entry<String,String> parameter : parameters.entrySet()){ if (firstEntry) { firstEntry = false; } else { result.append(","); } result.append(parameter.getKey()); result.append("="); result.append(parameter.getValue()); } } result.append("}]"); return result.toString(); } /** * Create a TermResolutionException with the given values * @param message the exception message * @param tr {@link TermResolver} to use to set values to if not null * @param parameters to set the parameters value to if not null * @param cause the root Throwable cause. */ public TermResolutionException(String message, TermResolver<?> tr, Map<String, String> parameters, Throwable cause) { super(message + " " + buildResolutionInfoString(tr, parameters), cause); if (tr == null) { termResolverClassName = ""; outputTerm = null; prereqs = null; parameterNames = null; } else { termResolverClassName = tr.getClass().getName(); outputTerm = tr.getOutput(); prereqs = tr.getPrerequisites(); parameterNames = Collections.unmodifiableSet(new HashSet<String>(tr.getParameterNames())); } if (parameters != null){ this.parameters = Collections.unmodifiableMap(new HashMap<String, String>(parameters)); } else { this.parameters = null; } } /** * Create a TermResolutionException with the given values * @param message the exception message * @param tr {@link TermResolver} to use to set values to if not null * @param parameters to set the parameters value to if not null */ public TermResolutionException(String message, TermResolver<?> tr, Map<String, String> parameters) { super(message + " " + buildResolutionInfoString(tr, parameters)); if (tr == null) { termResolverClassName = ""; outputTerm = null; prereqs = null; parameterNames = null; } else { termResolverClassName = tr.getClass().getName(); outputTerm = tr.getOutput(); prereqs = tr.getPrerequisites(); parameterNames = Collections.unmodifiableSet(new HashSet<String>(tr.getParameterNames())); } if (parameters != null){ this.parameters = Collections.unmodifiableMap(new HashMap<String, String>(parameters)); } else { this.parameters = null; } } }
924464bcab710860afe2a7d811cbcc6f1496e786
4,932
java
Java
web/src/main/java/com/jeesite/modules/common/entity/CommonAccessory.java
sohero-0406/platform
48258056750bc6f8a4a1b9a47b23c5bc4122d594
[ "Apache-2.0" ]
null
null
null
web/src/main/java/com/jeesite/modules/common/entity/CommonAccessory.java
sohero-0406/platform
48258056750bc6f8a4a1b9a47b23c5bc4122d594
[ "Apache-2.0" ]
null
null
null
web/src/main/java/com/jeesite/modules/common/entity/CommonAccessory.java
sohero-0406/platform
48258056750bc6f8a4a1b9a47b23c5bc4122d594
[ "Apache-2.0" ]
null
null
null
32.235294
99
0.752028
1,002,991
package com.jeesite.modules.common.entity; import com.jeesite.common.utils.excel.annotation.ExcelField; import org.hibernate.validator.constraints.Length; import com.jeesite.common.entity.DataEntity; import com.jeesite.common.mybatis.annotation.Column; import com.jeesite.common.mybatis.annotation.Table; import com.jeesite.common.mybatis.mapper.query.QueryType; /** * 汽车配件表Entity * @author mayuhu * @version 2019-08-12 */ @Table(name="common_accessory", columns={ @Column(name="id", attrName="id", label="主键", isPK=true), @Column(name="accessory_index", attrName="accessoryIndex", label="配件编号"), @Column(name="accessory_name", attrName="accessoryName", label="配件名称", queryType=QueryType.LIKE), @Column(name="accessory_brand", attrName="accessoryBrand", label="配件品牌"), @Column(name="accessory_level", attrName="accessoryLevel", label="accessory_level"), @Column(name="accessory_specifications", attrName="accessorySpecifications", label="规格"), @Column(name="accessory_unit", attrName="accessoryUnit", label="单位"), @Column(name="accessory_price", attrName="accessoryPrice", label="指导价"), @Column(name="accessory_place_of_origin", attrName="accessoryPlaceOfOrigin", label="产地"), @Column(name="accessory_import", attrName="accessoryImport", label="是否 进口 取值 “是”或者“否”"), @Column(includeEntity=DataEntity.class), @Column(name="category_id", attrName="categoryId", label="配件分类id"), }, orderBy="a.update_date DESC" ) public class CommonAccessory extends PreEntity<CommonAccessory> { private static final long serialVersionUID = 1L; private String accessoryIndex; // 配件编号 private String accessoryName; // 配件名称 private String accessoryBrand; // 配件品牌 private String accessoryLevel; // 配件等级 private String accessorySpecifications; // 规格 private String accessoryUnit; // 单位 private String accessoryPrice; // 指导价 private String accessoryPlaceOfOrigin; // 产地 private String accessoryImport; // 是否 进口 取值 “是”或者“否” private String categoryId; // 配件分类id public CommonAccessory() { this(null); } public CommonAccessory(String id){ super(id); } @Length(max=50, message="配件编号长度不能超过 50 个字符") @ExcelField(title="配件编号", align = ExcelField.Align.CENTER, sort = 1) public String getAccessoryIndex() { return accessoryIndex; } public void setAccessoryIndex(String accessoryIndex) { this.accessoryIndex = accessoryIndex; } @Length(max=100, message="配件名称长度不能超过 100 个字符") @ExcelField(title="配件名称", align = ExcelField.Align.CENTER, sort = 2) public String getAccessoryName() { return accessoryName; } public void setAccessoryName(String accessoryName) { this.accessoryName = accessoryName; } @Length(max=100, message="配件品牌长度不能超过 100 个字符") @ExcelField(title="配件品牌", align = ExcelField.Align.CENTER, sort = 3) public String getAccessoryBrand() { return accessoryBrand; } public void setAccessoryBrand(String accessoryBrand) { this.accessoryBrand = accessoryBrand; } @Length(max=45, message="配件等级长度不能超过 45 个字符") @ExcelField(title="配件等级", align = ExcelField.Align.CENTER, sort = 4) public String getAccessoryLevel() { return accessoryLevel; } public void setAccessoryLevel(String accessoryLevel) { this.accessoryLevel = accessoryLevel; } @Length(max=20, message="规格长度不能超过 20 个字符") @ExcelField(title="规格", align = ExcelField.Align.CENTER, sort = 5) public String getAccessorySpecifications() { return accessorySpecifications; } public void setAccessorySpecifications(String accessorySpecifications) { this.accessorySpecifications = accessorySpecifications; } @Length(max=10, message="单位长度不能超过 10 个字符") @ExcelField(title="单位", align = ExcelField.Align.CENTER, sort = 6) public String getAccessoryUnit() { return accessoryUnit; } public void setAccessoryUnit(String accessoryUnit) { this.accessoryUnit = accessoryUnit; } @Length(max=20, message="指导价长度不能超过 20 个字符") @ExcelField(title="指导价", align = ExcelField.Align.CENTER, sort = 7) public String getAccessoryPrice() { return accessoryPrice; } public void setAccessoryPrice(String accessoryPrice) { this.accessoryPrice = accessoryPrice; } @Length(max=100, message="产地长度不能超过 100 个字符") @ExcelField(title="产地", align = ExcelField.Align.CENTER, sort = 8) public String getAccessoryPlaceOfOrigin() { return accessoryPlaceOfOrigin; } public void setAccessoryPlaceOfOrigin(String accessoryPlaceOfOrigin) { this.accessoryPlaceOfOrigin = accessoryPlaceOfOrigin; } @Length(max=10, message="是否 进口 取值 “是”或者“否”长度不能超过 10 个字符") @ExcelField(title="是否进口", align = ExcelField.Align.CENTER, sort = 9) public String getAccessoryImport() { return accessoryImport; } public void setAccessoryImport(String accessoryImport) { this.accessoryImport = accessoryImport; } @Length(max=64, message="配件分类id长度不能超过 64 个字符") public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } }
9244651adcc053717e35bf960954617308fc059f
991
java
Java
src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlywheelGenerator.java
Alonsinwhat/Create
ca40f990a62c5de8993ef5fa782f3e5e367ec480
[ "MIT" ]
1,131
2019-11-09T00:41:08.000Z
2022-03-31T17:42:41.000Z
src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlywheelGenerator.java
Alonsinwhat/Create
ca40f990a62c5de8993ef5fa782f3e5e367ec480
[ "MIT" ]
2,749
2019-11-09T03:37:38.000Z
2022-03-31T18:48:00.000Z
src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlywheelGenerator.java
Alonsinwhat/Create
ca40f990a62c5de8993ef5fa782f3e5e367ec480
[ "MIT" ]
528
2019-11-17T04:55:06.000Z
2022-03-31T16:11:43.000Z
31.967742
112
0.803229
1,002,992
package com.simibubi.create.content.contraptions.components.flywheel; import com.simibubi.create.foundation.data.SpecialBlockStateGen; import com.tterrag.registrate.providers.DataGenContext; import com.tterrag.registrate.providers.RegistrateBlockstateProvider; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraftforge.client.model.generators.ModelFile; public class FlywheelGenerator extends SpecialBlockStateGen { @Override protected int getXRotation(BlockState state) { return 0; } @Override protected int getYRotation(BlockState state) { return horizontalAngle(state.getValue(FlywheelBlock.HORIZONTAL_FACING)) + 90; } @Override public <T extends Block> ModelFile getModel(DataGenContext<Block, T> ctx, RegistrateBlockstateProvider prov, BlockState state) { return prov.models() .getExistingFile(prov.modLoc("block/" + ctx.getName() + "/casing_" + state.getValue(FlywheelBlock.CONNECTION) .getSerializedName())); } }
9244657196af58bdeadc00f6fc9a8e53b2b4e561
1,979
java
Java
src/breakout/RectBrick.java
puzzler7/Game_CS308
31eba55d6d03c1ab78078cacd5a11800dbf62999
[ "MIT" ]
null
null
null
src/breakout/RectBrick.java
puzzler7/Game_CS308
31eba55d6d03c1ab78078cacd5a11800dbf62999
[ "MIT" ]
null
null
null
src/breakout/RectBrick.java
puzzler7/Game_CS308
31eba55d6d03c1ab78078cacd5a11800dbf62999
[ "MIT" ]
null
null
null
26.039474
101
0.609399
1,002,993
package breakout; import javafx.scene.image.Image; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; /** * A rectangular brick that extends brick. * * Assumes that all inputs are positive and valid. * * @author Maverick Chung mc608 */ public class RectBrick extends Brick { public RectBrick(double x, double y) { this(x, y, Main.BRICK_HEALTH, Main.BRICK_HEIGHT); } public RectBrick(double x, double y, int health) { this(x, y, health, Main.BRICK_HEIGHT); } public RectBrick(double x, double y, int health, double height) { shape = new Rectangle(height*Main.BRICK_WIDTH_HEIGHT_RATIO, height); shape.setFill(Color.ORANGE); hp = health; setCenterX(x); setCenterY(y); updateImage(); } /** * Reflects the ball on hit, as well as taking damage as per the parent method. * @param b The ball that has collided with this brick. */ @Override public void onHit(Ball b) { if (b.getCenterX()<getCenterX()-getWidth()/2 || b.getCenterX()>getCenterX()+getWidth()/2) { b.setXNegate(-1); } if (b.getCenterY()<getCenterY()-getHeight()/2 || b.getCenterY()>getCenterY()+getHeight()/2) { b.setYNegate(-1); } super.onHit(b); } @Override public void setCenterX(double x) { ((Rectangle)shape).setX(x-((Rectangle) shape).getWidth()/2); } @Override public void setCenterY(double y) { ((Rectangle)shape).setY(y-((Rectangle) shape).getHeight()/2); } @Override double getCenterX() { return ((Rectangle)shape).getX()+((Rectangle)shape).getWidth()/2; } @Override double getCenterY() { return ((Rectangle)shape).getY()+((Rectangle)shape).getHeight()/2; } double getWidth() { return ((Rectangle)shape).getWidth(); } double getHeight() { return ((Rectangle)shape).getHeight(); } }
924465f93427d9ea6b450ed0f7fe63991d3eb61f
1,119
java
Java
api/src/main/java/ar/edu/itba/pod/census/combiner/CitizensPerHomeByRegionCombinerFactory.java
gibarsin/census
0ff528e13ba3877d651c6ff5f12927b6c2205c89
[ "MIT" ]
null
null
null
api/src/main/java/ar/edu/itba/pod/census/combiner/CitizensPerHomeByRegionCombinerFactory.java
gibarsin/census
0ff528e13ba3877d651c6ff5f12927b6c2205c89
[ "MIT" ]
1
2017-12-21T15:15:24.000Z
2017-12-24T00:03:02.000Z
api/src/main/java/ar/edu/itba/pod/census/combiner/CitizensPerHomeByRegionCombinerFactory.java
gibarsin/census
0ff528e13ba3877d651c6ff5f12927b6c2205c89
[ "MIT" ]
1
2019-10-22T02:42:38.000Z
2019-10-22T02:42:38.000Z
28.692308
120
0.728329
1,002,994
package ar.edu.itba.pod.census.combiner; import ar.edu.itba.pod.census.model.Region; import com.hazelcast.mapreduce.Combiner; import com.hazelcast.mapreduce.CombinerFactory; import java.util.HashMap; import java.util.Map; public class CitizensPerHomeByRegionCombinerFactory implements CombinerFactory<Region, Integer, Map<Integer, Integer>> { @Override public Combiner<Integer, Map<Integer, Integer>> newCombiner(final Region region) { return new CitizensPerHomeByRegionCombiner(); } private static class CitizensPerHomeByRegionCombiner extends Combiner<Integer, Map<Integer, Integer>> { private final Map<Integer, Integer> counterByHomeId; private CitizensPerHomeByRegionCombiner() { counterByHomeId = new HashMap<>(); } @Override public void reset() { counterByHomeId.clear(); } @Override public void combine(final Integer homeId) { counterByHomeId.compute(homeId, (key, counter) -> counter == null ? 1 : counter + 1); } @Override public Map<Integer, Integer> finalizeChunk() { return new HashMap<>(counterByHomeId); } } }
924466d7dc298cf5a7b596dc76e804cfba05f15c
1,799
java
Java
src/com/github/koshamo/puri/ui/controls/board/ColonistShipSkin.java
koshamo/puri
19bb1b5da8622da08dd5fc71be070d253d7b8cb8
[ "BSD-3-Clause" ]
2
2020-01-13T11:33:48.000Z
2020-05-02T20:37:15.000Z
src/com/github/koshamo/puri/ui/controls/board/ColonistShipSkin.java
koshamo/puri
19bb1b5da8622da08dd5fc71be070d253d7b8cb8
[ "BSD-3-Clause" ]
null
null
null
src/com/github/koshamo/puri/ui/controls/board/ColonistShipSkin.java
koshamo/puri
19bb1b5da8622da08dd5fc71be070d253d7b8cb8
[ "BSD-3-Clause" ]
1
2020-05-03T00:47:56.000Z
2020-05-03T00:47:56.000Z
27.257576
83
0.710951
1,002,995
package com.github.koshamo.puri.ui.controls.board; import com.github.koshamo.puri.setup.PrColors; import javafx.scene.control.SkinBase; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.text.Text; /*private*/ class ColonistShipSkin extends SkinBase<ColonistShip> { protected ColonistShipSkin(ColonistShip control) { super(control); drawComponent(0); } public void drawComponent(int colonists) { this.getChildren().clear(); Pane pane = new Pane(); drawShip(pane); drawText(pane, colonists); drawColonists(pane, colonists); this.getChildren().add(pane); } private static void drawShip(Pane pane) { Path path = new Path(); MoveTo start = new MoveTo(1, 25); LineTo line1 = new LineTo(21, 30); LineTo line2 = new LineTo(121, 30); LineTo line3 = new LineTo(141, 25); LineTo line4 = new LineTo(121, 60); LineTo line5 = new LineTo(21, 60); LineTo line6 = new LineTo(1, 25); path.getElements().add(start); path.getElements().addAll(line1, line2, line3, line4, line5, line6); path.setFill(Color.DARKGOLDENROD); pane.getChildren().add(path); } private static void drawText(Pane pane, int colonists) { Text text = new Text(String.valueOf(colonists)); text.setX(65); text.setY(50); pane.getChildren().add(text); } private static void drawColonists(Pane pane, int colonists) { double distance = 100 / (colonists-1); for (int i = 0; i < colonists; i++) { Circle border = new Circle(21+i*distance, 19, 11, Color.BLACK); Circle circle = new Circle(21+i*distance, 19, 10, PrColors.COLONIST.getColor()); pane.getChildren().addAll(border, circle); } } }
9244671d74f436bb0adb53d45554f99596ca430a
11,243
java
Java
protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderEnvelopeTest.java
brokenshoebox/james-project
a2a77ad247330ceb148ee0c7751cbe7e347467bd
[ "Apache-2.0" ]
634
2015-12-21T20:24:06.000Z
2022-03-24T09:57:48.000Z
protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderEnvelopeTest.java
brokenshoebox/james-project
a2a77ad247330ceb148ee0c7751cbe7e347467bd
[ "Apache-2.0" ]
4,148
2015-09-14T15:59:06.000Z
2022-03-31T10:29:10.000Z
protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderEnvelopeTest.java
brokenshoebox/james-project
a2a77ad247330ceb148ee0c7751cbe7e347467bd
[ "Apache-2.0" ]
392
2015-07-16T07:04:59.000Z
2022-03-28T09:37:53.000Z
36.385113
218
0.628569
1,002,996
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.imap.encode; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.apache.james.imap.encode.base.ByteImapResponseWriter; import org.apache.james.imap.encode.base.ImapResponseComposerImpl; import org.apache.james.imap.message.response.FetchResponse; import org.apache.james.imap.message.response.FetchResponse.Envelope.Address; import org.apache.james.mailbox.MessageSequenceNumber; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class FetchResponseEncoderEnvelopeTest { private static final String ADDRESS_ONE_HOST = "HOST"; private static final String ADDRESS_ONE_MAILBOX = "MAILBOX"; private static final String ADDRESS_ONE_DOMAIN_LIST = "DOMAIN LIST"; private static final String ADDRESS_ONE_NAME = "NAME"; private static final String ADDRESS_TWO_HOST = "2HOST"; private static final String ADDRESS_TWO_MAILBOX = "2MAILBOX"; private static final String ADDRESS_TWO_DOMAIN_LIST = "2DOMAIN LIST"; private static final String ADDRESS_TWO_NAME = "2NAME"; private static final MessageSequenceNumber MSN = MessageSequenceNumber.of(100); private FetchResponseEncoder encoder; private FetchResponse message; private FetchResponse.Envelope envelope; private Address[] bcc; private Address[] cc; private String date; private Address[] from; private String inReplyTo; private String messageId; private Address[] replyTo; private Address[] sender; private String subject; private Address[] to; private ByteImapResponseWriter writer = new ByteImapResponseWriter(); private ImapResponseComposer composer = new ImapResponseComposerImpl(writer); @BeforeEach void setUp() { envelope = mock(FetchResponse.Envelope.class); bcc = null; cc = null; date = null; from = null; inReplyTo = null; messageId = null; replyTo = null; sender = null; subject = null; to = null; message = new FetchResponse(MSN, null, null, null, null, null, envelope, null, null, null); encoder = new FetchResponseEncoder(false); } private Address[] mockOneAddress() { return new Address[]{ mockAddress(ADDRESS_ONE_NAME, ADDRESS_ONE_DOMAIN_LIST, ADDRESS_ONE_MAILBOX, ADDRESS_ONE_HOST) }; } private Address[] mockManyAddresses() { return new Address[]{ mockAddress(ADDRESS_ONE_NAME, ADDRESS_ONE_DOMAIN_LIST, ADDRESS_ONE_MAILBOX, ADDRESS_ONE_HOST), mockAddress(ADDRESS_TWO_NAME, ADDRESS_TWO_DOMAIN_LIST, ADDRESS_TWO_MAILBOX, ADDRESS_TWO_HOST) }; } private Address mockAddress(final String name, final String domainList, final String mailbox, final String host) { Address address = mock(Address.class); when(address.getPersonalName()).thenReturn(name); when(address.getAtDomainList()).thenReturn(domainList); when(address.getMailboxName()).thenReturn(mailbox); when(address.getHostName()).thenReturn(host); return address; } private void envelopExpects() { when(envelope.getBcc()).thenReturn(bcc); when(envelope.getCc()).thenReturn(cc); when(envelope.getDate()).thenReturn(date); when(envelope.getFrom()).thenReturn(from); when(envelope.getInReplyTo()).thenReturn(inReplyTo); when(envelope.getMessageId()).thenReturn(messageId); when(envelope.getReplyTo()).thenReturn(replyTo); when(envelope.getSender()).thenReturn(sender); when(envelope.getSubject()).thenReturn(subject); when(envelope.getTo()).thenReturn(to); } @Test void testShouldNilAllNullProperties() throws Exception { envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeDate() throws Exception { date = "a date"; envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (\"a date\" NIL NIL NIL NIL NIL NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeSubject() throws Exception { subject = "some subject"; envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL \"some subject\" NIL NIL NIL NIL NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeInReplyTo() throws Exception { inReplyTo = "some reply to"; envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL NIL NIL NIL NIL \"some reply to\" NIL))\r\n"); } @Test void testShouldComposeMessageId() throws Exception { messageId = "some message id"; envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL NIL NIL NIL NIL NIL \"some message id\"))\r\n"); } @Test void testShouldComposeOneFromAddress() throws Exception { from = mockOneAddress(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")) NIL NIL NIL NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeManyFromAddress() throws Exception { from = mockManyAddresses(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")(\"2NAME\" \"2DOMAIN LIST\" \"2MAILBOX\" \"2HOST\")) NIL NIL NIL NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeOneSenderAddress() throws Exception { sender = mockOneAddress(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")) NIL NIL NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeManySenderAddress() throws Exception { sender = mockManyAddresses(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")(\"2NAME\" \"2DOMAIN LIST\" \"2MAILBOX\" \"2HOST\")) NIL NIL NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeOneReplyToAddress() throws Exception { replyTo = mockOneAddress(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")) NIL NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeManyReplyToAddress() throws Exception { replyTo = mockManyAddresses(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")(\"2NAME\" \"2DOMAIN LIST\" \"2MAILBOX\" \"2HOST\")) NIL NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeOneToAddress() throws Exception { to = mockOneAddress(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")) NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeManyToAddress() throws Exception { to = mockManyAddresses(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")(\"2NAME\" \"2DOMAIN LIST\" \"2MAILBOX\" \"2HOST\")) NIL NIL NIL NIL))\r\n"); } @Test void testShouldComposeOneCcAddress() throws Exception { cc = mockOneAddress(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")) NIL NIL NIL))\r\n"); } @Test void testShouldComposeManyCcAddress() throws Exception { cc = mockManyAddresses(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")(\"2NAME\" \"2DOMAIN LIST\" \"2MAILBOX\" \"2HOST\")) NIL NIL NIL))\r\n"); } @Test void testShouldComposeOneBccAddress() throws Exception { bcc = mockOneAddress(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")) NIL NIL))\r\n"); } @Test void testShouldComposeManyBccAddress() throws Exception { bcc = mockManyAddresses(); envelopExpects(); encoder.encode(message, composer); assertThat(writer.getString()).isEqualTo("* 100 FETCH (ENVELOPE (NIL NIL NIL NIL NIL NIL NIL ((\"NAME\" \"DOMAIN LIST\" \"MAILBOX\" \"HOST\")(\"2NAME\" \"2DOMAIN LIST\" \"2MAILBOX\" \"2HOST\")) NIL NIL))\r\n"); } }
92446908dcce8698cd194a8dab2b0586974cda0f
4,740
java
Java
src/main/java/com/hujiang/project/zhgd/hjProjectPersonnelSynchronization/controller/HjProjectPersonnelSynchronizationController.java
xieyagit/zhgd
45ac870a62c7323a1bb40b99fb8f0c93e38aed0d
[ "MIT" ]
null
null
null
src/main/java/com/hujiang/project/zhgd/hjProjectPersonnelSynchronization/controller/HjProjectPersonnelSynchronizationController.java
xieyagit/zhgd
45ac870a62c7323a1bb40b99fb8f0c93e38aed0d
[ "MIT" ]
null
null
null
src/main/java/com/hujiang/project/zhgd/hjProjectPersonnelSynchronization/controller/HjProjectPersonnelSynchronizationController.java
xieyagit/zhgd
45ac870a62c7323a1bb40b99fb8f0c93e38aed0d
[ "MIT" ]
1
2021-12-06T09:51:17.000Z
2021-12-06T09:51:17.000Z
37.03125
176
0.794937
1,002,997
package com.hujiang.project.zhgd.hjProjectPersonnelSynchronization.controller; import java.util.List; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.hujiang.framework.aspectj.lang.annotation.Log; import com.hujiang.framework.aspectj.lang.enums.BusinessType; import com.hujiang.project.zhgd.hjProjectPersonnelSynchronization.domain.HjProjectPersonnelSynchronization; import com.hujiang.project.zhgd.hjProjectPersonnelSynchronization.service.IHjProjectPersonnelSynchronizationService; import com.hujiang.framework.web.controller.BaseController; import com.hujiang.framework.web.page.TableDataInfo; import com.hujiang.framework.web.domain.AjaxResult; import com.hujiang.common.utils.poi.ExcelUtil; /** * 项目人员同步 信息操作处理 * * @author hujiang * @date 2019-05-16 */ @Controller @RequestMapping("/zhgd/hjProjectPersonnelSynchronization") public class HjProjectPersonnelSynchronizationController extends BaseController { private String prefix = "zhgd/hjProjectPersonnelSynchronization"; @Autowired private IHjProjectPersonnelSynchronizationService hjProjectPersonnelSynchronizationService; @RequiresPermissions("zhgd:hjProjectPersonnelSynchronization:view") @GetMapping() public String hjProjectPersonnelSynchronization() { return prefix + "/hjProjectPersonnelSynchronization"; } /** * 查询项目人员同步列表 */ @RequiresPermissions("zhgd:hjProjectPersonnelSynchronization:list") @PostMapping("/list") @ResponseBody public TableDataInfo list(HjProjectPersonnelSynchronization hjProjectPersonnelSynchronization) { startPage(); List<HjProjectPersonnelSynchronization> list = hjProjectPersonnelSynchronizationService.selectHjProjectPersonnelSynchronizationList(hjProjectPersonnelSynchronization); return getDataTable(list); } /** * 导出项目人员同步列表 */ @RequiresPermissions("zhgd:hjProjectPersonnelSynchronization:export") @PostMapping("/export") @ResponseBody public AjaxResult export(HjProjectPersonnelSynchronization hjProjectPersonnelSynchronization) { List<HjProjectPersonnelSynchronization> list = hjProjectPersonnelSynchronizationService.selectHjProjectPersonnelSynchronizationList(hjProjectPersonnelSynchronization); ExcelUtil<HjProjectPersonnelSynchronization> util = new ExcelUtil<HjProjectPersonnelSynchronization>(HjProjectPersonnelSynchronization.class); return util.exportExcel(list, "hjProjectPersonnelSynchronization"); } /** * 新增项目人员同步 */ @GetMapping("/add") public String add() { return prefix + "/add"; } /** * 新增保存项目人员同步 */ @RequiresPermissions("zhgd:hjProjectPersonnelSynchronization:add") @Log(title = "项目人员同步", businessType = BusinessType.INSERT) @PostMapping("/add") @ResponseBody public AjaxResult addSave(HjProjectPersonnelSynchronization hjProjectPersonnelSynchronization) { return toAjax(hjProjectPersonnelSynchronizationService.insertHjProjectPersonnelSynchronization(hjProjectPersonnelSynchronization)); } /** * 修改项目人员同步 */ @GetMapping("/edit/{id}") public String edit(@PathVariable("id") Integer id, ModelMap mmap) { HjProjectPersonnelSynchronization hjProjectPersonnelSynchronization = hjProjectPersonnelSynchronizationService.selectHjProjectPersonnelSynchronizationById(id); mmap.put("hjProjectPersonnelSynchronization", hjProjectPersonnelSynchronization); return prefix + "/edit"; } /** * 修改保存项目人员同步 */ @RequiresPermissions("zhgd:hjProjectPersonnelSynchronization:edit") @Log(title = "项目人员同步", businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(HjProjectPersonnelSynchronization hjProjectPersonnelSynchronization) { return toAjax(hjProjectPersonnelSynchronizationService.updateHjProjectPersonnelSynchronization(hjProjectPersonnelSynchronization)); } /** * 删除项目人员同步 */ @RequiresPermissions("zhgd:hjProjectPersonnelSynchronization:remove") @Log(title = "项目人员同步", businessType = BusinessType.DELETE) @PostMapping( "/remove") @ResponseBody public AjaxResult remove(String ids) { return toAjax(hjProjectPersonnelSynchronizationService.deleteHjProjectPersonnelSynchronizationByIds(ids)); } }
9244691dda9f0890a1d4437b38edbb48685474f6
523
java
Java
PlatformTools/src/main/java/com/avid/ctms/examples/tools/common/Terminator.java
avid-technology/ctms-examples-java
76d6318db5c15522d06deb7e53c71a4575a8c995
[ "Apache-2.0" ]
4
2019-04-29T09:53:56.000Z
2021-11-24T14:24:47.000Z
PlatformTools/src/main/java/com/avid/ctms/examples/tools/common/Terminator.java
avid-technology/ctms-examples-java
76d6318db5c15522d06deb7e53c71a4575a8c995
[ "Apache-2.0" ]
null
null
null
PlatformTools/src/main/java/com/avid/ctms/examples/tools/common/Terminator.java
avid-technology/ctms-examples-java
76d6318db5c15522d06deb7e53c71a4575a8c995
[ "Apache-2.0" ]
null
null
null
22.73913
78
0.707457
1,002,998
package com.avid.ctms.examples.tools.common; import java.util.function.*; /** * Copyright 2017-2021 by Avid Technology, Inc. * User: nludwig * Date: 2017-05-04 * Time: 08:47 * Project: CTMS */ /** * Dedicated interface to indicate termination callbacks/continuations. */ @FunctionalInterface public interface Terminator<T, E extends Throwable> extends BiConsumer<T, E> { void terminate(T message, E exception); default void accept(T message, E exception) { terminate(message, exception); } }
9244695b8561eab1eb08108e2e7e7bed63882c82
4,759
java
Java
src/main/java/com/github/novelrt/fumocement/IndirectedPointer.java
jeuxjeux20/FumoCement
d2af6cdeb737cbb3e62cd4ba837eac75e25d3e53
[ "MIT" ]
6
2021-04-29T20:06:18.000Z
2022-01-31T12:33:59.000Z
src/main/java/com/github/novelrt/fumocement/IndirectedPointer.java
jeuxjeux20/FumoCement
d2af6cdeb737cbb3e62cd4ba837eac75e25d3e53
[ "MIT" ]
null
null
null
src/main/java/com/github/novelrt/fumocement/IndirectedPointer.java
jeuxjeux20/FumoCement
d2af6cdeb737cbb3e62cd4ba837eac75e25d3e53
[ "MIT" ]
1
2021-04-29T20:22:25.000Z
2021-04-29T20:22:25.000Z
38.379032
141
0.686909
1,002,999
// Copyright © Matt Jones and Contributors. Licensed under the MIT License (MIT). See LICENCE.md in the repository root for more information. package com.github.novelrt.fumocement; import com.github.novelrt.fumocement.builtin.Int32Pointer; import org.jetbrains.annotations.Nullable; import java.util.Objects; /** * Represents an indirected pointer of type {@code T}, which can be represented in C * as {@code T*}. For instance, putting a {@link Int32Pointer} will result in a * {@code int**} type. * <p> * This class uses a {@link NativeObjectProvider} to provide native objects * that consumes the underlying handle without owning it. * * @param <T> the native object type that this double pointer contains * @implNote Under the hood, this class allocates a {@code void**}. */ public final class IndirectedPointer<T extends NativeObject> extends NativeObject { private final NativeObjectProvider<T> provider; private @Pointer("T*") long lastUnderlyingHandle; private @Nullable T lastUnderlyingHandleAsObject; /** * Creates a new instance of {@link IndirectedPointer} with the given {@link NativeObjectProvider} * which is used for giving native objects that serves as an access layer for the underlying * pointer. This object's native resources will be garbage collected. * * @param provider the native object provider to use * @throws NullPointerException when {@code provider} is null */ public IndirectedPointer(NativeObjectProvider<T> provider) { this(provider, DisposalMethod.GARBAGE_COLLECTED); } /** * Creates a new instance of {@link IndirectedPointer} with the given {@link NativeObjectProvider} * which is used for giving native objects that serves as an access layer for the underlying * pointer, and with the given {@link DisposalMethod}. * * @param provider the native object provider to use * @param disposalMethod the disposal method to use * @throws NullPointerException when {@code provider} is null */ public IndirectedPointer(NativeObjectProvider<T> provider, DisposalMethod disposalMethod) { super(createPointer(), true, disposalMethod, IndirectedPointer::destroyPointer); this.provider = Objects.requireNonNull(provider); } // For now, these are implemented in the methods generated by ClangSharp // fork. Maybe that we can do something like a separate C++ library, // but this will induce much more work as one has to create a CMake project, // make sure it works on Windows, Linux, Mac, Android, etc. Then, you // must somehow package the dll/so/dylib in the jar and also somehow load // it, as it must be loaded from a file. So yeah, it's a pain. private static native long getNativeUnderlyingHandle(long handle); private static native void setNativeUnderlyingHandle(long handle, long value); private static native long createPointer(); private static native void destroyPointer(long handle); /** * {@inheritDoc} */ @Override public @Pointer("void**") long getHandle() { return super.getHandle(); } /** * Gets the underlying value of this double pointer as an instance of {@code T}. * * @return an instance of {@code T} from the underlying value of this pointer, * or {@code null} if the pointer is null */ public @Nullable T get() { long underlyingHandle = getNativeUnderlyingHandle(getHandle()); if (lastUnderlyingHandle != underlyingHandle) { lastUnderlyingHandle = underlyingHandle; if (Pointers.isNullPointer(underlyingHandle)) { lastUnderlyingHandleAsObject = null; } else { lastUnderlyingHandleAsObject = provider.provide(underlyingHandle); } } return lastUnderlyingHandleAsObject; } /** * Gets the underlying handle of this double pointer, as a pointer such as {@code T*}. * * @return the underlying handle */ public @Pointer("T*") long getUnderlyingHandle() { return getNativeUnderlyingHandle(getHandle()); } /** * Sets the underlying value of this double pointer using the given instance of @{code T}. * <p> * A value of {@code null} will result in a null value inside the double pointer. * * @param value the new value */ public void set(@Nullable T value) { setNativeUnderlyingHandle(getHandle(), value == null ? Pointers.NULLPTR : value.getHandle()); } /** * Sets the underlying value of this double pointer to {@code null}. */ public void setNull() { setNativeUnderlyingHandle(getHandle(), Pointers.NULLPTR); } }
92446a97d2ea91bc3477b0d8f651c1debe2fdbda
4,199
java
Java
app/src/main/java/com/paulvarry/intra42/utils/BypassPicassoImageGetter.java
alexandregv/intra42
670677014e2441e50027feb7c238096dd430c825
[ "Apache-2.0" ]
56
2016-12-11T11:55:05.000Z
2022-03-17T17:07:49.000Z
app/src/main/java/com/paulvarry/intra42/utils/BypassPicassoImageGetter.java
alexandregv/intra42
670677014e2441e50027feb7c238096dd430c825
[ "Apache-2.0" ]
27
2016-11-22T13:37:23.000Z
2021-08-15T20:16:01.000Z
app/src/main/java/com/paulvarry/intra42/utils/BypassPicassoImageGetter.java
alexandregv/intra42
670677014e2441e50027feb7c238096dd430c825
[ "Apache-2.0" ]
17
2017-01-13T06:08:23.000Z
2021-07-09T15:04:51.000Z
34.138211
126
0.539176
1,003,000
package com.paulvarry.intra42.utils; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.lang.ref.WeakReference; import in.uncod.android.bypass.Bypass; /** * Original credits: http://stackoverflow.com/a/25530488/504611 */ public class BypassPicassoImageGetter implements Bypass.ImageGetter { private final Picasso mPicasso; private final WeakReference<TextView> mTextView; private SourceModifier mSourceModifier; public BypassPicassoImageGetter(final TextView textView) { mTextView = new WeakReference<>(textView); mPicasso = Picasso.get(); } @Override public Drawable getDrawable(String source) { final Handler handler = new Handler(); final BitmapDrawablePlaceHolder result = new BitmapDrawablePlaceHolder(); final String finalSource = mSourceModifier == null ? source : mSourceModifier.modify(source); new Thread(new Runnable() { @Override public void run() { try { final Bitmap bitmap = mPicasso.load(finalSource).get(); handler.post(new Runnable() { @Override public void run() { TextView textView = mTextView.get(); if (textView == null) { return; } try { int maxWidth; int horizontalPadding = textView.getPaddingLeft() + textView.getPaddingRight(); maxWidth = textView.getMeasuredWidth() - horizontalPadding; if (maxWidth == 0) { maxWidth = Integer.MAX_VALUE; } final BitmapDrawable drawable = new BitmapDrawable(textView.getResources(), bitmap); final double aspectRatio = 1.0 * drawable.getIntrinsicWidth() / drawable.getIntrinsicHeight(); final int width = Math.min(maxWidth, drawable.getIntrinsicWidth()); final int height = (int) (width / aspectRatio); drawable.setBounds(0, 0, width, height); result.setDrawable(drawable); result.setBounds(0, 0, width, height); textView.setText(textView.getText()); // invalidate() doesn't work correctly... } catch (Exception e) { //do something with this? } } }); } catch (Exception | OutOfMemoryError e) { e.printStackTrace(); } } }).start(); return result; } /** * Set the {@link SourceModifier} * * @param sourceModifier the new source modifier */ public void setSourceModifier(SourceModifier sourceModifier) { mSourceModifier = sourceModifier; } /** * Allows hooking into the source so that you can do things like modify relative urls */ public interface SourceModifier { /** * Modify the source url, adding to it in any way you need to * * @param source the source url from the markdown * @return the modified url which will be loaded by Picasso */ String modify(String source); } private static class BitmapDrawablePlaceHolder extends BitmapDrawable { protected Drawable drawable; @Override public void draw(final Canvas canvas) { if (drawable != null) { drawable.draw(canvas); } } public void setDrawable(Drawable drawable) { this.drawable = drawable; } } }
92446c9121866520af270d8f1964c1eeb9beae8b
3,443
java
Java
src/main/java/com/smartsoftasia/module/HorrizontalImageListView/view/HorrizontalListImageView.java
B-greg/HorrizontalImageListView
ba6e181508ee78204d30efb1a2333dce0937d99f
[ "Apache-2.0" ]
null
null
null
src/main/java/com/smartsoftasia/module/HorrizontalImageListView/view/HorrizontalListImageView.java
B-greg/HorrizontalImageListView
ba6e181508ee78204d30efb1a2333dce0937d99f
[ "Apache-2.0" ]
null
null
null
src/main/java/com/smartsoftasia/module/HorrizontalImageListView/view/HorrizontalListImageView.java
B-greg/HorrizontalImageListView
ba6e181508ee78204d30efb1a2333dce0937d99f
[ "Apache-2.0" ]
null
null
null
33.754902
113
0.713912
1,003,001
package com.smartsoftasia.module.HorrizontalImageListView.view; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.smartsoftasia.module.HorrizontalImageListView.Model.HorizontalListViewModel; import com.smartsoftasia.module.HorrizontalImageListView.R; import com.smartsoftasia.module.HorrizontalImageListView.adapter.ImageAdapter; import org.lucasr.twowayview.TwoWayView; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by gregoire on 9/18/14. */ public class HorrizontalListImageView extends LinearLayout implements TwoWayView.OnScrollListener { TwoWayView mTwoWayView; ImageAdapter imageAdapter; ImageView mArrowLeft; ImageView mArrowRight; List<HorizontalListViewModel> mPictureResources = new ArrayList<>(); Boolean isArrowVisible = false; public HorrizontalListImageView(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.horizontal_listview, this); setupViewItems(); } private void setupViewItems() { mTwoWayView = (TwoWayView) findViewById(R.id.twoWayView); mArrowLeft = (ImageView) findViewById(R.id.twoWayView_arrow_left); mArrowRight = (ImageView) findViewById(R.id.twoWayView_arrow_right); mTwoWayView.setOrientation(TwoWayView.Orientation.HORIZONTAL); imageAdapter = new ImageAdapter(mPictureResources, getContext()); mTwoWayView.setAdapter(imageAdapter); mTwoWayView.setOnScrollListener(this); } // public void setPicturesDrawable(Collection<Integer> items){ // if(items==null)items = new ArrayList<>(); // mPictureResources.addAll(items); // imageAdapter.notifyDataSetChanged(); // } public void setItems(Collection<HorizontalListViewModel> items){ if(items==null)items = new ArrayList<>(); mPictureResources.addAll(items); imageAdapter.notifyDataSetChanged(); } public void setcarousel(){ imageAdapter.setCarousel(true); } public void setArrowVisible(Boolean isVisible){ isArrowVisible = isVisible; if(isVisible){ if(mArrowLeft!=null)mArrowLeft.setVisibility(VISIBLE); if(mArrowRight!=null)mArrowRight.setVisibility(VISIBLE); }else{ if(mArrowLeft!=null)mArrowLeft.setVisibility(VISIBLE); if(mArrowRight!=null)mArrowRight.setVisibility(VISIBLE); } } @Override public void onScrollStateChanged(TwoWayView twoWayView, int i) { } @Override public void onScroll(TwoWayView twoWayView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if(!isArrowVisible)return; int l = visibleItemCount + firstVisibleItem; if (l >= totalItemCount) { if(mArrowRight!=null)mArrowRight.setVisibility(View.GONE); }else{ if(mArrowRight!=null)mArrowRight.setVisibility(View.VISIBLE); } if (firstVisibleItem <= 0){ if(mArrowLeft!=null)mArrowLeft.setVisibility(View.GONE); }else{ if(mArrowLeft!=null)mArrowLeft.setVisibility(View.VISIBLE); } } }
92446da72117551a9813cc07bfee8bb93aec1208
13,758
java
Java
app/src/test/java/org/mercycorps/translationcards/activity/TranslationsActivityTest.java
translation-cards/translation-cards
b42a110397a9d61971a1e667364c5f5a922c0099
[ "Apache-2.0" ]
28
2016-02-24T20:17:57.000Z
2022-02-19T23:21:07.000Z
app/src/test/java/org/mercycorps/translationcards/activity/TranslationsActivityTest.java
translation-cards/translation-cards
b42a110397a9d61971a1e667364c5f5a922c0099
[ "Apache-2.0" ]
270
2016-01-14T16:11:56.000Z
2019-06-25T06:45:03.000Z
app/src/test/java/org/mercycorps/translationcards/activity/TranslationsActivityTest.java
translation-cards/translation-cards
b42a110397a9d61971a1e667364c5f5a922c0099
[ "Apache-2.0" ]
21
2016-03-02T05:13:09.000Z
2017-12-27T14:39:26.000Z
44.247588
147
0.766296
1,003,002
package org.mercycorps.translationcards.activity; import android.app.Activity; import android.content.Intent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mercycorps.translationcards.BuildConfig; import org.mercycorps.translationcards.R; import org.mercycorps.translationcards.TestMainApplication; import org.mercycorps.translationcards.activity.addTranslation.AddNewTranslationContext; import org.mercycorps.translationcards.activity.addTranslation.EnterSourcePhraseActivity; import org.mercycorps.translationcards.activity.addTranslation.GetStartedActivity; import org.mercycorps.translationcards.activity.translations.TranslationsActivity; import org.mercycorps.translationcards.dagger.TestBaseComponent; import org.mercycorps.translationcards.model.Deck; import org.mercycorps.translationcards.model.Dictionary; import org.mercycorps.translationcards.model.Translation; import org.mercycorps.translationcards.service.DeckService; import org.mercycorps.translationcards.service.DictionaryService; import org.mercycorps.translationcards.service.TranslationService; import org.robolectric.Robolectric; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.Shadows; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowActivity; import org.robolectric.util.ActivityController; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import javax.inject.Inject; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.mercycorps.translationcards.util.TestAddTranslationCardActivityHelper.CONTEXT_INTENT_KEY; import static org.mercycorps.translationcards.util.TestAddTranslationCardActivityHelper.click; import static org.mercycorps.translationcards.util.TestAddTranslationCardActivityHelper.findTextView; import static org.mercycorps.translationcards.util.TestAddTranslationCardActivityHelper.findView; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.when; import static org.robolectric.Shadows.shadowOf; /** * Test for TranslationsActivity * * @author [email protected] (Pat Dale) */ @Config(constants = BuildConfig.class, sdk = 21) @RunWith(RobolectricGradleTestRunner.class) public class TranslationsActivityTest { public static final int DEFAULT_DECK_ID = 1; public static final String NO_VALUE = ""; public static final long DEFAULT_LONG = -1; public static final String DICTIONARY_TEST_LABEL = "Testlabel"; public static final String DICTIONARY_ARABIC_LABEL = "ARABIC"; public static final String DICTIONARY_FARSI_LABEL = "FARSI"; public static final String TRANSLATED_TEXT = "TranslatedText"; public static final String TRANSLATION_LABEL = "TranslationLabel"; public static final String DEFAULT_DECK_NAME = "Default"; private static final String EMPTY_DECK_TITLE = "Let's make this useful"; private static final String DEFAULT_LANGUAGE_NAME = "English"; private TranslationsActivity translationsActivity; private Deck deck; ActivityController<TranslationsActivity> controller; @Inject DeckService deckService; @Inject DictionaryService dictionaryService; @Inject TranslationService translationService; @Before public void setUp() { TestMainApplication application = (TestMainApplication) RuntimeEnvironment.application; ((TestBaseComponent) application.getBaseComponent()).inject(this); initializeStubsAndMocks(); controller = Robolectric.buildActivity(TranslationsActivity.class); Intent intent = new Intent(); translationsActivity = controller.withIntent(intent).create().get(); } @After public void teardown() { translationsActivity.finish(); controller.pause().stop().destroy(); } private void initializeStubsAndMocks() { Dictionary[] dictionaries = new Dictionary[3]; Translation translation = new Translation(TRANSLATION_LABEL, false, NO_VALUE, DEFAULT_LONG, TRANSLATED_TEXT); Translation nullTranslatedTextTranslation = new Translation(TRANSLATION_LABEL, false, "audio.mp3", DEFAULT_LONG, null); Translation[] translations = {translation, nullTranslatedTextTranslation}; dictionaries[0] = new Dictionary(DICTIONARY_TEST_LABEL, translations, DEFAULT_LONG); dictionaries[1] = new Dictionary(DICTIONARY_ARABIC_LABEL, translations, DEFAULT_LONG); dictionaries[2] = new Dictionary(DICTIONARY_FARSI_LABEL, translations, DEFAULT_LONG); deck = new Deck(DEFAULT_DECK_NAME, NO_VALUE, NO_VALUE, DEFAULT_DECK_ID, DEFAULT_LONG, false, DEFAULT_LANGUAGE_NAME, dictionaries); when(deckService.currentDeck()).thenReturn(deck); when(dictionaryService.currentDictionary()).thenReturn(dictionaries[0]); when(dictionaryService.getDictionariesForCurrentDeck()).thenReturn(Arrays.asList(dictionaries)); when(translationService.cardIsExpanded(anyInt())).thenReturn(false); when(translationService.getCurrentTranslations()).thenReturn(Arrays.asList(translations)); } @Test public void shouldShowWelcomeTitleWhenNoCardsArePresent() { Activity activity = createEmptyTranslationsActivity(); TextView welcomeTitle = (TextView) activity.findViewById(R.id.empty_deck_title); assertThat(welcomeTitle.getText().toString(), is(EMPTY_DECK_TITLE)); } @Test public void shouldNotShowWelcomeTitleWhenCardsArePresent() { TextView welcomeMessageTitle = findTextView(translationsActivity, R.id.empty_deck_title); assertEquals(View.GONE, welcomeMessageTitle.getVisibility()); } @Test public void shouldShowWelcomeMessageWhenNoCardsArePresent() { Activity activity = createEmptyTranslationsActivity(); TextView welcomeMessage = findTextView(activity, R.id.empty_deck_message); assertEquals("This deck doesn't have any cards.\\nGet started by creating your first card.", welcomeMessage.getText().toString()); } @Test public void shouldNotDisplayCreateTranslationButtonWhenDeckIsLocked() { Activity activity = createLockedDeckTranslationsActivity(); View addTranslationButton = findView(activity, R.id.add_translation_button); assertEquals(View.GONE, addTranslationButton.getVisibility()); } @Test public void shouldDisplayCreateTranslationButtonWhenDeckIsUnlocked() { Activity activity = createEmptyTranslationsActivity(); View addTranslationButton = findView(activity, R.id.add_translation_button); assertEquals(View.VISIBLE, addTranslationButton.getVisibility()); } @Test public void shouldNotDisplayHeaderInEmptyDeck() { Activity activity= createEmptyTranslationsActivity(); TextView header = findTextView(activity, R.id.translation_list_header); assertEquals(View.GONE, header.getVisibility()); } @Test public void shouldDisplayHeaderWhenDeckIsPopulated() { TextView header = findTextView(translationsActivity, R.id.translation_list_header); assertEquals(View.VISIBLE, header.getVisibility()); } @Test public void shouldNotShowWelcomeMessageWhenCardsArePresent() { TextView welcomeMessage = findTextView(translationsActivity, R.id.empty_deck_message); assertEquals(View.GONE, welcomeMessage.getVisibility()); } private Activity createEmptyTranslationsActivity() { return createActivityWithDeck(deck); } private Activity createActivityWithDeck(Deck deck) { Intent intent = new Intent(); intent.putExtra("Deck", deck); initializeStubsAndMocksForEmptyDeck(); controller = Robolectric.buildActivity(TranslationsActivity.class); return controller.withIntent(intent).create().get(); } private Activity createLockedDeckTranslationsActivity() { Deck deck = new Deck(DEFAULT_DECK_NAME, NO_VALUE, NO_VALUE, DEFAULT_DECK_ID, DEFAULT_LONG, true, DEFAULT_LANGUAGE_NAME, new Dictionary[0]); when(deckService.currentDeck()).thenReturn(deck); return createActivityWithDeck(deck); } private void initializeStubsAndMocksForEmptyDeck() { Dictionary[] dictionaries = new Dictionary[1]; dictionaries[0] = new Dictionary(DICTIONARY_TEST_LABEL, new Translation[0], DEFAULT_LONG ); when(dictionaryService.currentDictionary()).thenReturn(dictionaries[0]); when(dictionaryService.getDictionariesForCurrentDeck()).thenReturn(Arrays.asList(dictionaries)); } @Test public void onCreate_shouldShowDeckNameInToolbar() { assertThat(translationsActivity.getSupportActionBar().getTitle().toString(), is( DEFAULT_DECK_NAME)); } @Test public void initList_shouldShowEditAndDeleteSectionByDefault() { View translationsListItem = firstTranslationCardInListView(); assertEquals(View.VISIBLE, translationsListItem.findViewById(R.id.translation_grandchild).getVisibility()); } @Test public void shouldStartGetStartedActivityWhenAddTranslationButtonIsClicked() { click(translationsActivity, R.id.add_translation_button); Intent nextStartedActivity = shadowOf(translationsActivity).getNextStartedActivity(); assertEquals(GetStartedActivity.class.getCanonicalName(), nextStartedActivity.getComponent().getClassName()); } @Test public void onClick_shouldStartEnterSourcePhraseActivityWhenEditLayoutIsClicked() { View translationsListItem = firstTranslationCardInListView(); translationsListItem.findViewById(R.id.translation_card_edit).performClick(); Intent nextStartedActivity = shadowOf(translationsActivity).getNextStartedActivity(); assertEquals(EnterSourcePhraseActivity.class.getCanonicalName(), nextStartedActivity.getComponent().getClassName()); } @Test public void shouldShowCollapsedCardIndicatorByDefault() { View translationsListItem = firstTranslationCardInListView(); ImageView cardIndicator = (ImageView) translationsListItem.findViewById(R.id.indicator_icon); assertThat(shadowOf(cardIndicator.getBackground()).getCreatedFromResId(), is(R.drawable.expand_arrow)); } @Test public void shouldHideTranslationCardChildByDefault() { View translationsListItem = firstTranslationCardInListView(); assertEquals(View.GONE, translationsListItem.findViewById(R.id.translation_child).getVisibility()); } @Test public void initTabs_shouldShowLanguageTabWhenOnHomeScreen() { LinearLayout tabContainer = (LinearLayout) translationsActivity.findViewById(R.id.tabs); assertThat(tabContainer.getChildCount(), is(3)); TextView languageTabText = (TextView) tabContainer.getChildAt(0).findViewById(R.id.tab_label_text); assertThat(languageTabText.getText().toString(), is(DICTIONARY_TEST_LABEL.toUpperCase())); } @Test public void setDictionary_shouldNotHaveAnyTranslationCardsWhenNoneHaveBeenCreated() { TextView translationCardText = (TextView) translationsActivity.findViewById(R.id.origin_translation_text); assertThat(translationCardText, is(nullValue())); } @Test public void shouldGoToDecksActivityWhenBackButtonPressed() { ShadowActivity shadowActivity = Shadows.shadowOf(translationsActivity); shadowActivity.onBackPressed(); assertTrue(shadowActivity.isFinishing()); } @Test public void shouldSetEditFlagInContextWhenEditButtonIsClicked() { firstTranslationCardInListView().findViewById(R.id.translation_card_edit).performClick(); Intent nextStartedActivity = shadowOf(translationsActivity).getNextStartedActivity(); AddNewTranslationContext context = nextStartedActivity.getParcelableExtra(CONTEXT_INTENT_KEY); assertTrue(context.isEdit()); } @Test public void shouldNotSetEditFlagInContextWhenCreateNewTranslationButtonIsClicked(){ click(translationsActivity, R.id.add_translation_button); Intent nextStartedActivity = shadowOf(translationsActivity).getNextStartedActivity(); AddNewTranslationContext context = nextStartedActivity.getParcelableExtra(CONTEXT_INTENT_KEY); assertFalse(context.isEdit()); } @Test public void shouldUpdateTranslationsListOnResume() throws Exception { when(translationService.getCurrentTranslations()).thenReturn(new ArrayList<Translation>(), new ArrayList<Translation>()) .thenReturn(Collections.singletonList(new Translation())); ShadowActivity shadowActivity = Shadows.shadowOf(translationsActivity); ListView listView = (ListView)translationsActivity.findViewById(R.id.translations_list); shadowActivity.pauseAndThenResume(); assertEquals(2, listView.getAdapter().getCount()); shadowActivity.pauseAndThenResume(); assertEquals(3, listView.getAdapter().getCount()); } private View firstTranslationCardInListView() { ListView translationsList = (ListView) translationsActivity .findViewById(R.id.translations_list); return translationsList.getAdapter().getView(1, null, translationsList); } }
92446e8e37ef6c583c820b19aa2091e4085dbc36
1,072
java
Java
caf-api/src/main/java/com/hpe/caf/api/CipherException.java
CAFapi/caf-common
388c27b8c8c2ba2019bb5b3fb35e38aaf6c452c1
[ "Apache-2.0" ]
2
2017-10-12T15:31:23.000Z
2017-10-13T00:23:51.000Z
caf-api/src/main/java/com/hpe/caf/api/CipherException.java
CAFapi/caf-common
388c27b8c8c2ba2019bb5b3fb35e38aaf6c452c1
[ "Apache-2.0" ]
37
2016-11-30T11:28:38.000Z
2022-03-31T20:04:49.000Z
caf-api/src/main/java/com/hpe/caf/api/CipherException.java
CAFapi/caf-common
388c27b8c8c2ba2019bb5b3fb35e38aaf6c452c1
[ "Apache-2.0" ]
6
2016-12-21T14:50:12.000Z
2019-07-25T12:18:03.000Z
31.529412
87
0.713619
1,003,003
/* * Copyright 2015-2021 Micro Focus or one of its affiliates. * * 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.hpe.caf.api; /** * Thrown when a Cipher encounters a failure when encrypting or decrypting information. */ public class CipherException extends Exception { /** * Create a new CipherException. * * @param message the message indicating the problem * @param cause the exception cause */ public CipherException(final String message, final Throwable cause) { super(message, cause); } }
92446f152c1ac453eaa345b0c15b2cb922ed6e7e
6,034
java
Java
src/main/java/org/clarksnut/models/jpa/JpaAbstractDocumentProvider.java
clarksnut/openfact-sync
f17b3275d29e1af7db950bc2538861112c7016f6
[ "Apache-2.0" ]
1
2021-01-09T08:45:34.000Z
2021-01-09T08:45:34.000Z
src/main/java/org/clarksnut/models/jpa/JpaAbstractDocumentProvider.java
openfact/openfact-plus
5e911d825ba21abf5c5b3c9254a2e584b64acfba
[ "Apache-2.0" ]
2
2018-03-07T16:21:25.000Z
2018-03-07T16:23:49.000Z
src/main/java/org/clarksnut/models/jpa/JpaAbstractDocumentProvider.java
openfact/openfact-plus
5e911d825ba21abf5c5b3c9254a2e584b64acfba
[ "Apache-2.0" ]
3
2017-12-22T17:32:32.000Z
2018-01-20T14:46:26.000Z
44.367647
142
0.707657
1,003,004
package org.clarksnut.models.jpa; import org.clarksnut.mapper.document.DocumentMapped; import org.clarksnut.models.DocumentModel; import org.clarksnut.models.ImportedDocumentModel; import org.clarksnut.models.exceptions.AlreadyImportedDocumentException; import org.clarksnut.models.jpa.entity.DocumentEntity; import org.clarksnut.models.jpa.entity.DocumentVersionEntity; import org.jboss.logging.Logger; import javax.enterprise.event.Event; import javax.inject.Inject; import javax.persistence.EntityGraph; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.HashMap; import java.util.List; import java.util.UUID; public abstract class JpaAbstractDocumentProvider { private static final Logger logger = Logger.getLogger(JpaLuceneDocumentProvider.class); @PersistenceContext private EntityManager em; @Inject private Event<DocumentModel.DocumentCreationEvent> creationEvent; @Inject private Event<DocumentModel.DocumentRemovedEvent> removedEvent; public DocumentModel addDocument(String documentType, ImportedDocumentModel importedDocument, DocumentMapped.DocumentBean bean) throws AlreadyImportedDocumentException { DocumentModel document = getDocument(documentType, bean.getAssignedId(), bean.getSupplierAssignedId()); if (document == null) { DocumentEntity documentEntity = new DocumentEntity(); documentEntity.setId(UUID.randomUUID().toString()); documentEntity.setType(documentType); documentEntity.setAssignedId(bean.getAssignedId()); documentEntity.setIssueDate(bean.getIssueDate()); documentEntity.setCurrency(bean.getCurrency()); documentEntity.setAmount(bean.getAmount()); documentEntity.setTax(bean.getTax()); documentEntity.setSupplierName(bean.getSupplierName()); documentEntity.setSupplierAssignedId(bean.getSupplierAssignedId()); documentEntity.setSupplierStreetAddress(bean.getSupplierStreetAddress()); documentEntity.setSupplierCity(bean.getSupplierCity()); documentEntity.setSupplierCountry(bean.getSupplierCountry()); documentEntity.setCustomerName(bean.getCustomerName()); documentEntity.setCustomerAssignedId(bean.getCustomerAssignedId()); documentEntity.setCustomerStreetAddress(bean.getCustomerStreetAddress()); documentEntity.setCustomerCity(bean.getCustomerCity()); documentEntity.setCustomerCountry(bean.getCustomerCountry()); em.persist(documentEntity); DocumentVersionEntity documentVersionEntity = new DocumentVersionEntity(); documentVersionEntity.setId(UUID.randomUUID().toString()); documentVersionEntity.setCurrentVersion(true); documentVersionEntity.setDocument(documentEntity); documentVersionEntity.setImportedDocument(ImportedDocumentAdapter.toEntity(importedDocument, em)); em.persist(documentVersionEntity); document = new DocumentAdapter(em, documentEntity); logger.debug("New Document has been imported"); final DocumentModel documentCreated = document; creationEvent.fire(() -> documentCreated); } else { long currentChecksum = document.getCurrentVersion().getImportedDocument().getFile().getChecksum(); if (currentChecksum != importedDocument.getFile().getChecksum()) { DocumentVersionEntity documentVersionEntity = new DocumentVersionEntity(); documentVersionEntity.setId(UUID.randomUUID().toString()); documentVersionEntity.setCurrentVersion(false); documentVersionEntity.setDocument(DocumentAdapter.toEntity(document, em)); documentVersionEntity.setImportedDocument(ImportedDocumentAdapter.toEntity(importedDocument, em)); em.persist(documentVersionEntity); logger.debug("New Document Version has been imported"); } else { throw new AlreadyImportedDocumentException("Document has already been imported"); } } return document; } public DocumentModel getDocument(String id) { DocumentEntity entity = em.find(DocumentEntity.class, id); if (entity == null) return null; return new DocumentAdapter(em, entity); } public DocumentModel getDocumentViewAndChecksAndStarts(String id) { EntityGraph<?> graph = em.getEntityGraph("graph.DocumentViewsAndChecks"); HashMap<String, Object> properties = new HashMap<>(); properties.put("javax.persistence.fetchgraph", graph); DocumentEntity entity = em.find(DocumentEntity.class, id, properties); if (entity == null) return null; return new DocumentAdapter(em, entity); } public DocumentModel getDocument(String type, String assignedId, String supplierAssignedId) { TypedQuery<DocumentEntity> typedQuery = em.createNamedQuery("getDocumentByTypeAssignedIdAndSupplierAssignedId", DocumentEntity.class); typedQuery.setParameter("type", type); typedQuery.setParameter("assignedId", assignedId); typedQuery.setParameter("supplierAssignedId", supplierAssignedId); List<DocumentEntity> resultList = typedQuery.getResultList(); if (resultList.size() == 1) { return new DocumentAdapter(em, resultList.get(0)); } else if (resultList.size() == 0) { return null; } else { throw new IllegalStateException("Invalid number of results"); } } public boolean removeDocument(DocumentModel document) { DocumentEntity entity = em.find(DocumentEntity.class, document.getId()); if (entity == null) return false; em.remove(entity); em.flush(); removedEvent.fire(() -> document); return true; } }
9244705e03be34df6114d36bd1e69b9a247fb9ee
1,700
java
Java
src/main/java/frc/robot/commands/TurretManual.java
commodores/irAtHomeAuto
399d9dd51946831e9f65f42ae13ba6fbfc40f13d
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/TurretManual.java
commodores/irAtHomeAuto
399d9dd51946831e9f65f42ae13ba6fbfc40f13d
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/TurretManual.java
commodores/irAtHomeAuto
399d9dd51946831e9f65f42ae13ba6fbfc40f13d
[ "BSD-3-Clause" ]
null
null
null
29.310345
80
0.586471
1,003,005
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.RobotContainer; import frc.robot.subsystems.Turret; public class TurretManual extends CommandBase { private final Turret m_turret; /** * Creates a new TurretManual. */ public TurretManual(Turret m_turret) { this.m_turret = m_turret; addRequirements(m_turret); // Use addRequirements() here to declare subsystem dependencies. } // Called when the command is initially scheduled. @Override public void initialize() { } // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { double speed = -RobotContainer.m_driverController.getRawAxis(4); /*double rotation = -RobotContainer.m_driverController.getRawAxis(4); if( rotation > -0.1 && rotation < 0.1){ rotation = 0; } */ if( speed > -0.1 && speed < 0.1){ speed = 0; } m_turret.turnTurret(speed*.5); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { } // Returns true when the command should end. @Override public boolean isFinished() { return false; } }
924470731d17eca180952969eab5e01b8ad33c8d
3,912
java
Java
canal-demo/src/main/java/com/bulain/canal/CanalClient.java
bulain/boot-demo
d2f0b487b2afbc38b4632f585da4d9ccf1e419c4
[ "MIT" ]
null
null
null
canal-demo/src/main/java/com/bulain/canal/CanalClient.java
bulain/boot-demo
d2f0b487b2afbc38b4632f585da4d9ccf1e419c4
[ "MIT" ]
6
2020-05-15T21:01:35.000Z
2021-05-23T13:27:37.000Z
canal-demo/src/main/java/com/bulain/canal/CanalClient.java
bulain/boot-demo
d2f0b487b2afbc38b4632f585da4d9ccf1e419c4
[ "MIT" ]
null
null
null
39.515152
112
0.564928
1,003,006
package com.bulain.canal; import java.net.InetSocketAddress; import java.util.List; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import com.alibaba.otter.canal.client.CanalConnector; import com.alibaba.otter.canal.client.CanalConnectors; import com.alibaba.otter.canal.protocol.CanalEntry.Column; import com.alibaba.otter.canal.protocol.CanalEntry.Entry; import com.alibaba.otter.canal.protocol.CanalEntry.EntryType; import com.alibaba.otter.canal.protocol.CanalEntry.EventType; import com.alibaba.otter.canal.protocol.CanalEntry.Header; import com.alibaba.otter.canal.protocol.CanalEntry.RowChange; import com.alibaba.otter.canal.protocol.CanalEntry.RowData; import com.alibaba.otter.canal.protocol.Message; import lombok.extern.slf4j.Slf4j; @Slf4j @Component public class CanalClient implements InitializingBean { private final static int BATCH_SIZE = 1000; @Override public void afterPropertiesSet() throws Exception { CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("127.0.0.1", 11111), "example", "", ""); try { connector.connect(); connector.subscribe(".*\\..*"); connector.rollback(); while (true) { Message message = connector.getWithoutAck(BATCH_SIZE); long batchId = message.getId(); int size = message.getEntries().size(); if (batchId == -1 || size == 0) { try { Thread.sleep(2000); } catch (InterruptedException e) { log.error("afterPropertiesSet()", e); } } else { printEntry(message.getEntries()); } connector.ack(batchId); } } catch (Exception e) { log.error("afterPropertiesSet()", e); } finally { connector.disconnect(); } } private static void printEntry(List<Entry> entrys) { for (Entry entry : entrys) { if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) { continue; } RowChange rowChage; try { rowChage = RowChange.parseFrom(entry.getStoreValue()); } catch (Exception e) { throw new RuntimeException("ERROR ## parser of event, data:" + entry.toString(), e); } EventType eventType = rowChage.getEventType(); Header header = entry.getHeader(); log.info("=======>;binlog[{}:{}] , name[{},{}] , eventType : {}", header.getLogfileName(), header.getLogfileOffset(), header.getSchemaName(), header.getTableName(), eventType); if (rowChage.getIsDdl()) { log.info("=======>;isDdl: true,sql:" + rowChage.getSql()); } for (RowData rowData : rowChage.getRowDatasList()) { if (eventType == EventType.DELETE) { printColumn(rowData.getBeforeColumnsList()); } else if (eventType == EventType.INSERT) { printColumn(rowData.getAfterColumnsList()); } else { log.info("------->; before"); printColumn(rowData.getBeforeColumnsList()); log.info("------->; after"); printColumn(rowData.getAfterColumnsList()); } } } } private static void printColumn(List<Column> columns) { for (Column column : columns) { log.info(column.getName() + " : " + column.getValue() + " update=" + column.getUpdated()); } } }
924471070a394c37675fc4f2698c145efe4a47de
27,735
java
Java
app/src/main/java/com/hitesh_sahu/retailapp/domain/mock/FakeWebServer.java
sanjaynme/ecommerce-java
ef1775e25727974c504674b4d8e0fb06b4323e8a
[ "Apache-2.0" ]
574
2016-06-16T15:38:08.000Z
2022-03-23T18:07:05.000Z
app/src/main/java/com/hitesh_sahu/retailapp/domain/mock/FakeWebServer.java
sanjaynme/ecommerce-java
ef1775e25727974c504674b4d8e0fb06b4323e8a
[ "Apache-2.0" ]
19
2017-04-02T14:45:17.000Z
2022-03-28T17:06:13.000Z
app/src/main/java/com/hitesh_sahu/retailapp/domain/mock/FakeWebServer.java
sanjaynme/ecommerce-java
ef1775e25727974c504674b4d8e0fb06b4323e8a
[ "Apache-2.0" ]
504
2016-06-16T15:38:12.000Z
2022-03-24T13:02:02.000Z
50.436364
253
0.520224
1,003,007
/* * Copyright (c) 2017. http://hiteshsahu.com- All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * If you use or distribute this project then you MUST ADD A COPY OF LICENCE * along with the project. * Written by Hitesh Sahu <[email protected]>, 2017. */ package com.hitesh_sahu.retailapp.domain.mock; import com.hitesh_sahu.retailapp.model.CenterRepository; import com.hitesh_sahu.retailapp.model.entities.Product; import com.hitesh_sahu.retailapp.model.entities.ProductCategoryModel; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; /* * This class serve as fake server and provides dummy product and category with real Image Urls taken from flipkart */ public class FakeWebServer { private static FakeWebServer fakeServer; public static FakeWebServer getFakeWebServer() { if (null == fakeServer) { fakeServer = new FakeWebServer(); } return fakeServer; } void initiateFakeServer() { addCategory(); } public void addCategory() { ArrayList<ProductCategoryModel> listOfCategory = new ArrayList<ProductCategoryModel>(); listOfCategory .add(new ProductCategoryModel( "Electronic", "Electric Items", "10%", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSeNSONF3fr9bZ6g0ztTAIPXPRCYN9vtKp1dXQB2UnBm8n5L34r")); listOfCategory .add(new ProductCategoryModel( "Furnitures", "Furnitures Items", "15%", "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRaUR5_wzLgBOuNtkWjOxhgaYaPBm821Hb_71xTyQ-OdUd-ojMMvw")); CenterRepository.getCenterRepository().setListOfCategory(listOfCategory); } public void getAllElectronics() { ConcurrentHashMap<String, ArrayList<Product>> productMap = new ConcurrentHashMap<String, ArrayList<Product>>(); ArrayList<Product> productlist = new ArrayList<Product>(); // Ovens productlist .add(new Product( "Solo Microwave Oven", "IFB 17PMMEC1 17 L Solo Microwave Oven", "Explore the joys of cooking with IFB 17PM MEC1 Solo Microwave Oven. The budget-friendly appliance has several nifty features including Multi Power Levels and Speed Defrost to make cooking a fun-filled experience.", "5490", "10", "4290", "0", "http://img6a.flixcart.com/image/microwave-new/3/3/z/ifb-17pmmec1-400x400-imae4g4uzzjsumhk.jpeg", "oven_1")); productlist .add(new Product( "Solo Microwave Oven", "Bajaj 1701MT 17 L Solo Microwave Oven", "Explore the joys of cooking with IFB 17PM MEC1 Solo Microwave Oven. The budget-friendly appliance has several nifty features including Multi Power Levels and Speed Defrost to make cooking a fun-filled experience.", "5000", "10", "4290", "0", "http://img6a.flixcart.com/image/microwave-new/z/j/p/bajaj-1701mt-400x400-imae4ty4vyzhaagz.jpeg", "oven_2")); productlist .add(new Product( "Solo Microwave Oven", "Whirlpool MW 25 BG 25 L Grill Microwave Oven", "http://img6a.flixcart.com/image/microwave-new/a/y/f/whirlpool-mw-25-bg-400x400-imaebagzstnngjqt.jpeg", "5290", "10", "4290", "0", "http://img6a.flixcart.com/image/microwave-new/z/j/p/bajaj-1701mt-400x400-imae4ty4vyzhaagz.jpeg", "oven_3")); productlist .add(new Product( "Solo Microwave Oven", "Morphy Richards 25CG 25 L Convection Microwave Oven", "http://img5a.flixcart.com/image/microwave-new/v/q/y/morphy-richard-25cg-400x400-imadxecx93kb6q4f.jpeg", "5300", "12", "4290", "0", "http://img6a.flixcart.com/image/microwave-new/z/j/p/bajaj-1701mt-400x400-imae4ty4vyzhaagz.jpeg", "oven_4")); productlist .add(new Product( "Solo Microwave Oven", "IFB 25SC4 25 L Convection Microwave Oven", "http://img5a.flixcart.com/image/microwave-new/v/q/y/morphy-richard-25cg-400x400-imadxecx93kb6q4f.jpeg", "5190", "10", "4290", "0", "http://img6a.flixcart.com/image/microwave-new/y/k/m/ifb-25sc4-400x400-imaef2pztynvqjaf.jpeg", "oven_5")); productMap.put("Microwave oven", productlist); ArrayList<Product> tvList = new ArrayList<Product>(); // TV tvList.add(new Product( "LED", "Vu 80cm (32) HD Ready LED TV", "Enjoy movie night with the family on this 80cm LED TV from Vu. With an A+ grade panel, this TV renders crisp details that make what you're watching look realistic.", "16000", "12", "13990", "0", "http://img5a.flixcart.com/image/television/g/y/w/vu-32k160mrevd-400x400-imae93ahpwtchzys.jpeg", "tv_1")); tvList.add(new Product( "LED 1", "Vu 80cm (32) HD Ready LED TV", "Enjoy movie night with the family on this 80cm LED TV from Vu. With an A+ grade panel, this TV renders crisp details that make what you're watching look realistic.", "17000", "12", "13990", "0", "http://img6a.flixcart.com/image/television/z/f/w/bpl-bpl080d51h-400x400-imaeeztqvhxbnam2.jpeg", "tv_2")); tvList.add(new Product( "LED 2", "Vu 80cm (32) HD Ready LED TV", "Enjoy movie night with the family on this 80cm LED TV from Vu. With an A+ grade panel, this TV renders crisp details that make what you're watching look realistic.", "18000", "12", "13990", "0", "http://img6a.flixcart.com/image/television/f/b/z/micromax-43x6300mhd-400x400-imaednxv8bgznhbx.jpeg", "tv_3")); tvList.add(new Product( "LED 3", "Vu 80cm (32) HD Ready LED TV", "Enjoy movie night with the family on this 80cm LED TV from Vu. With an A+ grade panel, this TV renders crisp details that make what you're watching look realistic.", "16000", "12", "13990", "0", "http://img6a.flixcart.com/image/television/a/w/z/vu-32d6545-400x400-imaebagzbpzqhmxc.jpeg", "tv_4")); tvList.add(new Product( "LED 4", "Vu 80cm (32) HD Ready LED TV", "Enjoy movie night with the family on this 80cm LED TV from Vu. With an A+ grade panel, this TV renders crisp details that make what you're watching look realistic.", "16000", "12", "13990", "0", "http://img6a.flixcart.com/image/television/s/r/t/lg-32lf550a-400x400-imae8nyvxyjds3qu.jpeg", "tv_5")); productMap.put("Television", tvList); productlist = new ArrayList<Product>(); // Vaccum Cleaner productlist .add(new Product( "Easy Clean Plus Hand-held ", "Eureka Forbes Easy Clean Plus Hand-held Vacuum Cleaner", "The Eureka Forbes Easy Clean vacuum cleaner is best for those who are looking for a machine that makes cleaning easier and is convenient to use. It is a compact and powerful machine with high suction and low power consumption.", "2699", "10", "2566", "0", "http://img5a.flixcart.com/image/vacuum-cleaner/e/e/g/eureka-forbes-easy-clean-easy-clean-plus-400x400-imae7dam5ey3vaeb.jpeg", "v_cleaner_1")); productlist .add(new Product( "Easy Clean Plus Hand-held ", "Eureka Forbes Easy Clean Plus Hand-held Vacuum Cleaner", "The Eureka Forbes Easy Clean vacuum cleaner is best for those who are looking for a machine that makes cleaning easier and is convenient to use. It is a compact and powerful machine with high suction and low power consumption.", "2699", "10", "2566", "0", "http://img6a.flixcart.com/image/vacuum-cleaner/j/e/x/nova-vc-761h-plus-vacuum-cleaner-400x400-imaecmhyadgxzzpg.jpeg", "v_cleaner_2")); productlist .add(new Product( "Easy Clean Plus Hand-held ", "Eureka Forbes Easy Clean Plus Hand-held Vacuum Cleaner", "The Eureka Forbes Easy Clean vacuum cleaner is best for those who are looking for a machine that makes cleaning easier and is convenient to use. It is a compact and powerful machine with high suction and low power consumption.", "2699", "10", "2566", "0", "http://img6a.flixcart.com/image/vacuum-cleaner/y/g/b/eureka-forbes-car-clean-car-clean-400x400-imae376v2kta5utj.jpeg", "v_cleaner_3")); productlist .add(new Product( "Easy Clean Plus Hand-held ", "Eureka Forbes Easy Clean Plus Hand-held Vacuum Cleaner", "The Eureka Forbes Easy Clean vacuum cleaner is best for those who are looking for a machine that makes cleaning easier and is convenient to use. It is a compact and powerful machine with high suction and low power consumption.", "2699", "10", "2566", "0", "http://img5a.flixcart.com/image/vacuum-cleaner/m/y/g/sarita-115-400x400-imae9b5zhzjagykx.jpeg", "v_cleaner_4")); productlist .add(new Product( "Easy Clean Plus Hand-held ", "Eureka Forbes Easy Clean Plus Hand-held Vacuum Cleaner", "The Eureka Forbes Easy Clean vacuum cleaner is best for those who are looking for a machine that makes cleaning easier and is convenient to use. It is a compact and powerful machine with high suction and low power consumption.", "2699", "10", "2566", "0", "http://img6a.flixcart.com/image/vacuum-cleaner/s/c/j/eureka-forbes-trendy-steel-trendy-steel-400x400-imae7vashkfj2hgk.jpeg", "v_cleaner_5")); productMap.put("Vaccum Cleaner", productlist); CenterRepository.getCenterRepository().setMapOfProductsInCategory(productMap); } public void getAllFurnitures() { ConcurrentHashMap<String, ArrayList<Product>> productMap = new ConcurrentHashMap<String, ArrayList<Product>>(); ArrayList<Product> productlist = new ArrayList<Product>(); // Table productlist .add(new Product( " Wood Coffee Table", "Royal Oak Engineered Wood Coffee Table", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "10200", "12", "7000", "0", "http://img6a.flixcart.com/image/coffee-table/q/f/4/ct15bl-mdf-royal-oak-dark-400x400-imaeehkd8xuheh2u.jpeg", "table_1")); productlist .add(new Product( " Wood Coffee Table", "Royal Oak Engineered Wood Coffee Table", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "10200", "12", "7000", "0", "http://img5a.flixcart.com/image/coffee-table/c/z/e/afr1096-sm-mango-wood-onlineshoppee-brown-400x400-imaea6c2bhwz8tns.jpeg", "table_2")); productlist .add(new Product( " Wood Coffee Table", "Royal Oak Engineered Wood Coffee Table", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "10200", "12", "7000", "0", "http://img5a.flixcart.com/image/coffee-table/u/n/p/brass-table0016-rosewood-sheesham-zameerwazeer-beige-400x400-imaedwk5ksph9ut2.jpeg", "table_3")); productlist .add(new Product( " Wood Coffee Table", "Royal Oak Engineered Wood Coffee Table", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "10200", "12", "7000", "0", "http://img6a.flixcart.com/image/coffee-table/v/h/h/side-tb-53-ad-particle-board-debono-acacia-dark-matt-400x400-imaecnctfgjahsnu.jpeg", "table_4")); productlist .add(new Product( " Wood Coffee Table", "Royal Oak Engineered Wood Coffee Table", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "10200", "12", "7000", "0", "http://img5a.flixcart.com/image/coffee-table/c/z/e/afr1096-sm-mango-wood-onlineshoppee-brown-400x400-imaea6c2bhwz8tns.jpeg", "table_5")); productlist .add(new Product( " Wood Coffee Table", "Royal Oak Engineered Wood Coffee Table", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "10200", "12", "7000", "0", "http://img5a.flixcart.com/image/coffee-table/k/y/h/1-particle-board-wood-an-wood-coffee-400x400-imae7uvzqsf4ynan.jpeg", "table_6")); productMap.put("Tables", productlist); productlist = new ArrayList<Product>(); // Chair productlist .add(new Product( "Bean Bag Chair Cover", "ab Homez XXXL Bean Bag Chair Cover (Without Filling)", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "36500", "20", "1200", "0", "http://img5a.flixcart.com/image/bean-bag/5/b/b/boss-moda-chair-br1088-comf-on-xxxl-400x400-imae9k78vg8gjh3q.jpeg", "chair_1")); productlist .add(new Product( "Bean Bag Chair Cover", "ab Homez XXXL Bean Bag Chair Cover (Without Filling)", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "36500", "20", "1200", "0", "http://img6a.flixcart.com/image/office-study-chair/e/f/p/flversaossblu-stainless-steel-nilkamal-400x400-imaeeptqczc5kbjg.jpeg", "chair_2")); productlist .add(new Product( "Bean Bag Chair Cover", "ab Homez XXXL Bean Bag Chair Cover (Without Filling)", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "36500", "20", "1200", "0", "http://img5a.flixcart.com/image/bean-bag/7/w/b/chr-01-fab-homez-xxxl-400x400-imae9qnbfwr9vkk4.jpeg", "chair_3")); productlist .add(new Product( "Adiko Leatherette Office Chair", "ab Homez XXXL Bean Bag Chair Cover (Without Filling)", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "36500", "20", "1200", "0", "http://img5a.flixcart.com/image/office-study-chair/h/z/d/adxn275-pu-leatherette-adiko-400x400-imaedpmyhzefdzgz.jpeg", "chair_4")); productlist .add(new Product( "Adiko Leatherette Office Chair", "ab Homez XXXL Bean Bag Chair Cover (Without Filling)", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "36500", "20", "1200", "0", "http://img5a.flixcart.com/image/office-study-chair/h/z/d/adxn275-pu-leatherette-adiko-400x400-imaedpmyytefgvz7.jpeg", "chair_5")); productlist .add(new Product( "Adiko Leatherette Office Chair", "ab Homez XXXL Bean Bag Chair Cover (Without Filling)", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "36500", "20", "1200", "0", "http://img6a.flixcart.com/image/office-study-chair/j/y/q/adpn-d021-pp-adiko-400x400-imaee2vrg9bkkxjg.jpeg", "chair_6")); productlist .add(new Product( "Adiko Leatherette Office Chair", "ab Homez XXXL Bean Bag Chair Cover (Without Filling)", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "36500", "20", "1200", "0", "http://img6a.flixcart.com/image/office-study-chair/k/s/2/adxn-034-pu-leatherette-adiko-400x400-imaedpmyyyg8bdmv.jpeg", "chair_7")); productlist .add(new Product( "Adiko Leatherette Office Chair", "ab Homez XXXL Bean Bag Chair Cover (Without Filling)", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "36500", "20", "1200", "0", "http://img6a.flixcart.com/image/bean-bag/t/8/n/fk0100391-star-xxxl-400x400-imae72dsb5h2r9uj.jpeg", "chair_8")); productlist .add(new Product( "Adiko Leatherette Office Chair", "ab Homez XXXL Bean Bag Chair Cover (Without Filling)", "With a contemporary design and gorgeous finish, this coffee table will be a brilliant addition to modern homes and even offices. The table has a glass table top with a floral print, and a pull-out drawer in the center.", "36500", "20", "1200", "0", "http://img5a.flixcart.com/image/bean-bag/3/h/w/rydclassicgreenl-rockyard-large-400x400-imae6zfaz6qzj3jd.jpeg", "chair_9")); productMap.put("Chairs", productlist); productlist = new ArrayList<Product>(); // Chair productlist .add(new Product( "l Collapsible Wardrobe", "Everything Imported Carbon Steel Collapsible Wardrobe", "Portable Wardrobe Has Hanging Space And Shelves Which Are Very Practical And The Roll Down Cover Keeps The Dust Out", "2999", "20", "1999", "0", "http://img5a.flixcart.com/image/collapsible-wardrobe/h/h/g/best-quality-3-5-feet-foldable-storage-cabinet-almirah-shelf-400x400-imaees5fq7wbndak.jpeg", "almirah_1")); productlist .add(new Product( "l Collapsible Wardrobe", "Everything Imported Carbon Steel Collapsible Wardrobe", "Portable Wardrobe Has Hanging Space And Shelves Which Are Very Practical And The Roll Down Cover Keeps The Dust Out", "2999", "20", "1999", "0", "http://img6a.flixcart.com/image/collapsible-wardrobe/d/n/s/cb265-carbon-steel-cbeeso-dark-beige-400x400-imaefn9vha2hm9qk.jpeg", "almirah_2")); productlist .add(new Product( "l Collapsible Wardrobe", "Everything Imported Carbon Steel Collapsible Wardrobe", "Portable Wardrobe Has Hanging Space And Shelves Which Are Very Practical And The Roll Down Cover Keeps The Dust Out", "2999", "20", "1999", "0", "http://img6a.flixcart.com/image/wardrobe-closet/b/v/3/srw-146-jute-pindia-blue-400x400-imaeb9g4y6tegzfn.jpeg", "almirah_3")); productlist .add(new Product( "l Collapsible Wardrobe", "Everything Imported Carbon Steel Collapsible Wardrobe", "Portable Wardrobe Has Hanging Space And Shelves Which Are Very Practical And The Roll Down Cover Keeps The Dust Out", "2999", "20", "1999", "0", "http://img6a.flixcart.com/image/cupboard-almirah/y/w/q/100009052-particle-board-housefull-mahogany-400x400-imaebazkwhv64p8q.jpeg", "almirah_4")); productlist .add(new Product( "l Collapsible Wardrobe", "Everything Imported Carbon Steel Collapsible Wardrobe", "Portable Wardrobe Has Hanging Space And Shelves Which Are Very Practical And The Roll Down Cover Keeps The Dust Out", "2999", "20", "1999", "0", "http://img5a.flixcart.com/image/collapsible-wardrobe/w/c/k/srw-116a-aluminium-pindia-maroon-wardrobe-400x400-imaeb9g4945dqunu.jpeg", "almirah_5")); productlist .add(new Product( "Metal Free Standing Wardrobe", "Everything Imported Carbon Steel Collapsible Wardrobe", "Portable Wardrobe Has Hanging Space And Shelves Which Are Very Practical And The Roll Down Cover Keeps The Dust Out", "2999", "20", "1999", "0", "http://img6a.flixcart.com/image/wardrobe-closet/f/b/p/srw-167-jute-pindia-purple-400x400-imaeb9g4d8uvatck.jpeg", "almirah_6")); productMap.put("Almirah", productlist); productMap.put("Almirah", productlist); CenterRepository.getCenterRepository().setMapOfProductsInCategory(productMap); } public void getAllProducts(int productCategory) { if (productCategory == 0) { getAllElectronics(); } else { getAllFurnitures(); } } }
92447133f0c5ce6375ab6c9d4998511cc49a79ad
1,510
java
Java
app/src/main/java/com/huawei/hms/modeling3d/utils/ToastUtil.java
gmYusuf/HMS-3D-Collection-App
8d4f1fbcbba392131744ee055568d2f3b6899a3d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/huawei/hms/modeling3d/utils/ToastUtil.java
gmYusuf/HMS-3D-Collection-App
8d4f1fbcbba392131744ee055568d2f3b6899a3d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/huawei/hms/modeling3d/utils/ToastUtil.java
gmYusuf/HMS-3D-Collection-App
8d4f1fbcbba392131744ee055568d2f3b6899a3d
[ "Apache-2.0" ]
null
null
null
31.458333
75
0.623841
1,003,008
// Copyright 2020. Explore in HMS. All rights reserved. // // 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.huawei.hms.modeling3d.utils; import android.content.Context; import android.widget.Toast; public class ToastUtil { private static String oldMsg; private static Toast toast = null; private static long oneTime = 0; private static long twoTime = 0; public static void showToast(Context context, String s) { if (toast == null) { toast = Toast.makeText(context, s, Toast.LENGTH_SHORT); toast.show(); oneTime = System.currentTimeMillis(); } else { twoTime = System.currentTimeMillis(); if (s.equals(oldMsg)) { if (twoTime - oneTime > Toast.LENGTH_SHORT) { toast.show(); } } else { oldMsg = s; toast.setText(s); toast.show(); } } oneTime = twoTime; } }
9244728603fecd5f88c29f91a9903b541ff8a614
3,062
java
Java
sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlScriptResource.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlScriptResource.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlScriptResource.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
26.859649
142
0.640431
1,003,009
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.analytics.synapse.artifacts.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; /** Sql Script resource type. */ @Fluent public final class SqlScriptResource { /* * Fully qualified resource Id for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) private String id; /* * The name of the resource */ @JsonProperty(value = "name", required = true) private String name; /* * The type of the resource. Ex- Microsoft.Compute/virtualMachines or * Microsoft.Storage/storageAccounts. */ @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY) private String type; /* * Resource Etag. */ @JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY) private String etag; /* * Properties of sql script. */ @JsonProperty(value = "properties", required = true) private SqlScript properties; /** * Get the id property: Fully qualified resource Id for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. * * @return the id value. */ public String getId() { return this.id; } /** * Get the name property: The name of the resource. * * @return the name value. */ public String getName() { return this.name; } /** * Set the name property: The name of the resource. * * @param name the name value to set. * @return the SqlScriptResource object itself. */ public SqlScriptResource setName(String name) { this.name = name; return this; } /** * Get the type property: The type of the resource. Ex- Microsoft.Compute/virtualMachines or * Microsoft.Storage/storageAccounts. * * @return the type value. */ public String getType() { return this.type; } /** * Get the etag property: Resource Etag. * * @return the etag value. */ public String getEtag() { return this.etag; } /** * Get the properties property: Properties of sql script. * * @return the properties value. */ public SqlScript getProperties() { return this.properties; } /** * Set the properties property: Properties of sql script. * * @param properties the properties value to set. * @return the SqlScriptResource object itself. */ public SqlScriptResource setProperties(SqlScript properties) { this.properties = properties; return this; } }
9244752f39c8634c35f250b86e17cb535d44416a
1,304
java
Java
src/main/java/com/pluralsight/async_rest_grizzly/Author.java
mukul-knit/async-grizzly-rest
7aa73e6411a876c32ba89ef6a01ee2bc9040d0e2
[ "MIT" ]
null
null
null
src/main/java/com/pluralsight/async_rest_grizzly/Author.java
mukul-knit/async-grizzly-rest
7aa73e6411a876c32ba89ef6a01ee2bc9040d0e2
[ "MIT" ]
null
null
null
src/main/java/com/pluralsight/async_rest_grizzly/Author.java
mukul-knit/async-grizzly-rest
7aa73e6411a876c32ba89ef6a01ee2bc9040d0e2
[ "MIT" ]
null
null
null
16.3
60
0.700153
1,003,010
package com.pluralsight.async_rest_grizzly; import javax.ws.rs.DefaultValue; import javax.ws.rs.MatrixParam; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonPropertyOrder({"id", "name", "age"}) @JsonInclude(Include.NON_NULL) public class Author { @MatrixParam("name") private String name; @DefaultValue("No address.") private String address; @QueryParam("city") private String city; private int age = 45; @PathParam("authorId") private String id; public Author() {} public Author(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
92447580b3617956f7ba8936815671cd5725d67d
5,490
java
Java
src/main/java/com/aws/greengrass/secretmanager/AWSSecretClient.java
NikOrin/aws-greengrass-secret-manager
248db3a48212b93efdc27caaba277aa7b5f6ad5d
[ "Apache-2.0" ]
5
2020-12-15T18:24:15.000Z
2021-12-21T21:26:53.000Z
src/main/java/com/aws/greengrass/secretmanager/AWSSecretClient.java
NikOrin/aws-greengrass-secret-manager
248db3a48212b93efdc27caaba277aa7b5f6ad5d
[ "Apache-2.0" ]
13
2021-03-16T00:52:24.000Z
2021-12-20T15:51:16.000Z
src/main/java/com/aws/greengrass/secretmanager/AWSSecretClient.java
NikOrin/aws-greengrass-secret-manager
248db3a48212b93efdc27caaba277aa7b5f6ad5d
[ "Apache-2.0" ]
3
2020-12-16T20:15:02.000Z
2021-05-24T23:22:15.000Z
47.327586
119
0.720219
1,003,011
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.aws.greengrass.secretmanager; import com.aws.greengrass.deployment.DeviceConfiguration; import com.aws.greengrass.secretmanager.exception.SecretManagerException; import com.aws.greengrass.tes.LazyCredentialProvider; import com.aws.greengrass.util.BaseRetryableAccessor; import com.aws.greengrass.util.Coerce; import com.aws.greengrass.util.CrashableSupplier; import com.aws.greengrass.util.ProxyUtils; import com.aws.greengrass.util.Utils; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.DecryptionFailureException; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import software.amazon.awssdk.services.secretsmanager.model.InternalServiceErrorException; import software.amazon.awssdk.services.secretsmanager.model.InvalidParameterException; import software.amazon.awssdk.services.secretsmanager.model.InvalidRequestException; import software.amazon.awssdk.services.secretsmanager.model.ResourceNotFoundException; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import javax.inject.Inject; public class AWSSecretClient { private final SecretsManagerClient secretsManagerClient; private static final int RETRY_COUNT = 3; private static final int BACKOFF_MILLIS = 200; /** * Constructor which utilizes TES for initializing AWS client. * @param credentialProvider TES credential provider * @param deviceConfiguration device configuration properties from kernel */ @Inject public AWSSecretClient(LazyCredentialProvider credentialProvider, DeviceConfiguration deviceConfiguration) { Region region = Region.of(Coerce.toString(deviceConfiguration.getAWSRegion())); this.secretsManagerClient = SecretsManagerClient.builder().httpClient(ProxyUtils.getSdkHttpClient()) .credentialsProvider(credentialProvider).region(region).build(); } // Constructor used for testing. AWSSecretClient(SecretsManagerClient secretsManager) { this.secretsManagerClient = secretsManager; } /** * Fetch secret from AWS cloud. * @param request AWS request for fetching secret from cloud * @return AWS secret response * @throws SecretManagerException If there is a problem fetching secret * @throws IOException If there is a network error */ public GetSecretValueResponse getSecret(GetSecretValueRequest request) throws SecretManagerException, IOException { String errorMsg = String.format("Exception occurred while fetching secrets " + "from AWSSecretsManager for secret: %s, version: %s, label: %s", request.secretId(), request.versionId(), request.versionStage()); try { validateInput(request); BaseRetryableAccessor accessor = new BaseRetryableAccessor(); CrashableSupplier<GetSecretValueResponse, IOException> getSecretValueResponse = () -> secretsManagerClient.getSecretValue(request); GetSecretValueResponse response = accessor.retry(RETRY_COUNT, BACKOFF_MILLIS, getSecretValueResponse, new HashSet<>(Collections.singletonList(IOException.class))); validateResponse(response); return response; } catch (InternalServiceErrorException | DecryptionFailureException | ResourceNotFoundException | InvalidParameterException | InvalidRequestException | IllegalArgumentException e) { throw new SecretManagerException(errorMsg, e); } } private void validateResponse(GetSecretValueResponse response) { String errorStr = "Invalid secret response, %s is missing"; if (Utils.isEmpty(response.versionId())) { throw new IllegalArgumentException(String.format(errorStr, "version Id")); } if (Utils.isEmpty(response.arn())) { throw new IllegalArgumentException(String.format(errorStr, "arn")); } if (Utils.isEmpty(response.name())) { throw new IllegalArgumentException(String.format(errorStr, "name")); } if (response.createdDate() == null) { throw new IllegalArgumentException(String.format(errorStr, "created date")); } if (!response.hasVersionStages() || response.versionStages().isEmpty()) { throw new IllegalArgumentException(String.format(errorStr, "version stages")); } if (Utils.isEmpty(response.secretString()) && response.secretBinary() == null) { throw new IllegalArgumentException(String.format(errorStr, "both secret string and binary")); } } private void validateInput(GetSecretValueRequest request) { if (Utils.isEmpty(request.secretId())) { throw new IllegalArgumentException("invalid secret request, secret id is required"); } if (Utils.isEmpty(request.versionId()) && Utils.isEmpty(request.versionStage())) { throw new IllegalArgumentException("invalid secret request, either version Id or stage is required"); } } }
92447582d5ca3c021d72b342f8a2563acb32f8d4
23
java
Java
src/main/java/com/controller/package-info.java
ThiagoFLupus/APILupusSec_SpringBoot
0f5e2ad8ab9580bd79c19a52c3091461624a61aa
[ "MIT" ]
null
null
null
src/main/java/com/controller/package-info.java
ThiagoFLupus/APILupusSec_SpringBoot
0f5e2ad8ab9580bd79c19a52c3091461624a61aa
[ "MIT" ]
null
null
null
src/main/java/com/controller/package-info.java
ThiagoFLupus/APILupusSec_SpringBoot
0f5e2ad8ab9580bd79c19a52c3091461624a61aa
[ "MIT" ]
null
null
null
23
23
0.869565
1,003,012
package com.controller;
924475f8ee9b65dff3c90b2a6efe332063eaf0f5
359
java
Java
src/main/java/L_292_Nim_Game/Solution.java
Limyiter-gh/leetcode
0b45fc065f8f3551a7f1e8021d8b0ac383c8c5a2
[ "Apache-2.0" ]
null
null
null
src/main/java/L_292_Nim_Game/Solution.java
Limyiter-gh/leetcode
0b45fc065f8f3551a7f1e8021d8b0ac383c8c5a2
[ "Apache-2.0" ]
null
null
null
src/main/java/L_292_Nim_Game/Solution.java
Limyiter-gh/leetcode
0b45fc065f8f3551a7f1e8021d8b0ac383c8c5a2
[ "Apache-2.0" ]
null
null
null
19.944444
79
0.660167
1,003,013
/* * 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 L_292_Nim_Game; /** * * @author Li Mingyang */ public class Solution { public boolean canWinNim(int n) { return (n % 4 == 0) ? false : true; } }
9244766d23ce9daa0c235877be23b682edc2ec44
3,345
java
Java
manage-service/src/main/java/com/huotu/cms/manage/util/web/CookieHelper.java
tomkay1/cms
56e1bea259123d2e8111e9d808d20900fd76332b
[ "Apache-2.0" ]
null
null
null
manage-service/src/main/java/com/huotu/cms/manage/util/web/CookieHelper.java
tomkay1/cms
56e1bea259123d2e8111e9d808d20900fd76332b
[ "Apache-2.0" ]
2
2021-04-07T18:44:39.000Z
2022-01-21T23:47:13.000Z
manage-service/src/main/java/com/huotu/cms/manage/util/web/CookieHelper.java
tomkay1/cms
56e1bea259123d2e8111e9d808d20900fd76332b
[ "Apache-2.0" ]
null
null
null
26.975806
131
0.55994
1,003,014
package com.huotu.cms.manage.util.web; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 操作Cookie * Created by Administrator on 2015/5/21. */ public class CookieHelper { /** * 得到cookie的值,返回String * * @param request * @param key * @return */ public static String getCookieVal(HttpServletRequest request, String key) { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (cookie.getName().equals(key)) { return cookie.getValue(); } } } return null; } /** * 得到cookie的值,返回int * * @param request * @param key * @return */ public static int getCookieValInteger(HttpServletRequest request, String key) { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (cookie.getName().equals(key)) { return Integer.parseInt(cookie.getValue()); } } } return 0; } private static Cookie findCookie(HttpServletRequest request,String key){ Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (cookie.getName().equals(key)) { return cookie; } } } return null; } /** * 设置Cookie,存在则覆盖 * @param request * @param response * @param key * @param value * @param maxAgeSecond */ public static void setCookie(HttpServletRequest request,HttpServletResponse response,String key,String value,int maxAgeSecond){ Cookie cookie=findCookie(request,key); if(cookie!=null){ cookie.setValue(value); cookie.setMaxAge(maxAgeSecond); cookie.setPath("/"); response.addCookie(cookie); }else{ addCookie(response, key, value, maxAgeSecond); } } // /** // * 设置cookie // * // * @param response // * @param key // * @param value // */ // public static void addCookie(HttpServletRequest request,HttpServletResponse response, String key, String value) { // Cookie cookie = new Cookie(key, value); // cookie.setMaxAge(1209600); // cookie.setPath("/"); // response.addCookie(cookie); // } /** * 新增Cookie * @param response * @param key * @param value * @param maxAgeSecond */ public static void addCookie(HttpServletResponse response,String key,String value,int maxAgeSecond) { Cookie cookie=new Cookie(key,value); cookie.setMaxAge(maxAgeSecond); cookie.setPath("/"); response.addCookie(cookie); } /** * 删除cookie * * @param response * @param key */ public static void removeCookie(HttpServletRequest request,HttpServletResponse response, String key) { Cookie cookie=findCookie(request,key); if(cookie!=null){ cookie.setMaxAge(0); } } }
9244767db17a1a0bea0873e5eeddef6afd746afc
351
java
Java
src/main/java/io/github/pedroermarinho/comandalivreapi/domain/dtos/UserDTO.java
pedroermarinho/ComandaLivre-API
27e1869df2cf94a6366abf9f82f62fefefab8313
[ "MIT" ]
null
null
null
src/main/java/io/github/pedroermarinho/comandalivreapi/domain/dtos/UserDTO.java
pedroermarinho/ComandaLivre-API
27e1869df2cf94a6366abf9f82f62fefefab8313
[ "MIT" ]
null
null
null
src/main/java/io/github/pedroermarinho/comandalivreapi/domain/dtos/UserDTO.java
pedroermarinho/ComandaLivre-API
27e1869df2cf94a6366abf9f82f62fefefab8313
[ "MIT" ]
1
2022-02-23T13:31:58.000Z
2022-02-23T13:31:58.000Z
15.954545
61
0.763533
1,003,015
package io.github.pedroermarinho.comandalivreapi.domain.dtos; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = true) public class UserDTO extends AuditableDTO { private String name; private String email; private String username; private String password; private String telefone; }
924476a02338a76ed56e25979ec6d1a593809992
4,459
java
Java
Server/src/main/java/com/magic/terry/server_magic/Communication/ConnectThreadGroup.java
terry-gjt/Magic_link_android
e01b9da48e92d430460caf41469375304b81f1ea
[ "Apache-2.0" ]
1
2020-09-08T09:34:22.000Z
2020-09-08T09:34:22.000Z
Server/src/main/java/com/magic/terry/server_magic/Communication/ConnectThreadGroup.java
terry-gjt/Magic_link_android
e01b9da48e92d430460caf41469375304b81f1ea
[ "Apache-2.0" ]
null
null
null
Server/src/main/java/com/magic/terry/server_magic/Communication/ConnectThreadGroup.java
terry-gjt/Magic_link_android
e01b9da48e92d430460caf41469375304b81f1ea
[ "Apache-2.0" ]
null
null
null
31.85
114
0.573895
1,003,016
package com.magic.terry.server_magic.Communication; import android.os.Handler; import android.util.Log; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import static com.magic.terry.server_magic.com.Safe.encipher; /** * Created by terry on 2018-05-26. */ public class ConnectThreadGroup implements ConnectAdd { private List<ConnectThread> threadgroup = new ArrayList<ConnectThread>(); private ConnectThread connectthread; private int threadgroupnum=0;//当前连接的数量 private boolean serverRunning; private ServerSocket serverSocket; private Handler handler; private MyMessage myMessage; private ActivityShow ActivityShow; public ConnectThreadGroup(ActivityShow ActivityShow, Handler handler,MyMessage myMessage){ this.ActivityShow=ActivityShow; this.handler=handler; this.myMessage=myMessage; if(!serverRunning){ serverRunning=true; try { serverSocket = new ServerSocket(55555); getLocalAddress(); } catch (IOException e) { ActivityShow.ToastShow("本机55555端口被占用,请退出冲突程序"); e.printStackTrace(); } connectthread=new ConnectThread(1,this);//第一个客户机线程 connectthread.start(); threadgroup.add(connectthread); threadgroupnum=1; } } public void DestroyGroup(){ for(int i=0; i<threadgroup.size(); i++) { connectthread = threadgroup.get(i); connectthread.StopThread(); connectthread.interrupt(); } try { serverSocket.close(); } catch (IOException e) { Log.i("线程serveractivity","seversocket已经关闭了"); } } public void SendCommand(String ss,int i){ if(serverRunning) { if(ss.length()<=0){ Log.i("线程异常sendstring","发送内容不能为空"); // Toast.makeText(mContext, "发送内容不能为空!", Toast.LENGTH_SHORT).show(); } else{ connectthread = threadgroup.get(i-1); connectthread.SendString(ss); } } else{ Log.i("线程异常sendstring","没有连接"); ActivityShow.ToastShow("没有连接"); } } public void getLocalAddress(){//将ip计算为密码显示出来 String MessageServer=""; try { for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for(Enumeration<InetAddress> enumIPAddr = intf.getInetAddresses(); enumIPAddr.hasMoreElements();) { InetAddress inetAddress = enumIPAddr.nextElement(); String ipstr=inetAddress.getHostAddress(); int start = ipstr.indexOf("192.168"); if((start!=-1)&&(start+1<ipstr.length())){ Log.i("密码测试","ip为"+ipstr); MessageServer=encipher(ipstr); Log.i("密码测试",MessageServer); }else{ Log.i("密码测试","ip:"+ipstr+"不属于局域网"); } // MessageServer += "请连接IP:"+inetAddress.getHostAddress()+"\n"; } } }catch (SocketException ex) { ActivityShow.TextShow("获取IP地址异常:" + ex.getMessage()); } if("".equals(MessageServer)) ActivityShow.TextShow("IP地址不属于局域网或未连接网络"); else ActivityShow.TextShow("密钥为:"+MessageServer); try{ ActivityShow.QRcodeImageShow(MessageServer); }catch (Exception e){ Log.i("线程异常","异常为"+e.toString()); } } @Override public void add(ConnectThread connectthread) { threadgroup.add(connectthread); threadgroupnum++; } @Override public boolean serverrunning() { return serverRunning; } @Override public Handler gerhandler() { return handler; } @Override public ServerSocket getServerSocket() { return serverSocket; } @Override public MyMessage getMyMessage() { return myMessage; } }
924477250a252e0c914695bbef4de15fe3ce9efd
6,128
java
Java
net-proxy-server/src/main/java/tech/pcloud/proxy/server/ServerConfig.java
pandong2015/net-proxy
f13bd0ee5f32a2f0e65ee2b174dd3f347881e147
[ "Apache-2.0" ]
null
null
null
net-proxy-server/src/main/java/tech/pcloud/proxy/server/ServerConfig.java
pandong2015/net-proxy
f13bd0ee5f32a2f0e65ee2b174dd3f347881e147
[ "Apache-2.0" ]
null
null
null
net-proxy-server/src/main/java/tech/pcloud/proxy/server/ServerConfig.java
pandong2015/net-proxy
f13bd0ee5f32a2f0e65ee2b174dd3f347881e147
[ "Apache-2.0" ]
null
null
null
40.315789
121
0.665144
1,003,017
package tech.pcloud.proxy.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import tech.pcloud.framework.netty.handler.DHSecurityCodecHandler; import tech.pcloud.framework.utility.common.HashUtil; import tech.pcloud.framework.utility.common.NetworkUtils; import tech.pcloud.proxy.core.model.Node; import tech.pcloud.proxy.core.model.NodeType; import tech.pcloud.proxy.core.model.Service; import tech.pcloud.proxy.core.service.CacheService; import tech.pcloud.proxy.message.TransferProto; import tech.pcloud.proxy.server.handler.ServerChannelHandler; import tech.pcloud.proxy.server.service.NodesService; import tech.pcloud.proxy.server.service.ServicesService; import tech.pcloud.proxy.server.util.Global; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.List; @Slf4j @Configuration @SpringBootApplication @ComponentScan("tech.pcloud.nnts") @MapperScan("tech.pcloud.nnts.server.mapper") @EnableConfigurationProperties({ServerConfig.ServerProperties.class}) public class ServerConfig { @Data @ConfigurationProperties(prefix = "nat.nnts.server") public static class ServerProperties { private String name; private String ip; private int port; private int backlog; } @Bean(value = "server") public Node getServer(@Autowired ServerProperties properties) { Node node = new Node(); node.setId(HashUtil.hashByMD5(NetworkUtils.getHardwareAddress())); node.setIp(NetworkUtils.getIP(NetworkUtils.IP_VERSION.V4)); node.setName(properties.getName()); node.setPort(properties.getPort()); node.setType(NodeType.SERVER.getType()); log.info("server id : " + node.getId()); log.info("server ip : " + node.getIp()); return node; } @Bean(value = "bossGroup") public EventLoopGroup getBossGroup() { return new NioEventLoopGroup(); } @Bean(value = "workerGroup") public EventLoopGroup getWorkerGroup() { return new NioEventLoopGroup(); } @Data @Component public static class Server { @Autowired @Qualifier("bossGroup") private EventLoopGroup bossGroup; @Autowired @Qualifier("workerGroup") private EventLoopGroup workerGroup; @Autowired ServerProperties properties; @Autowired NodesService nodesService; @Autowired ServicesService servicesService; private ServerBootstrap bootstrap; @Autowired private CacheService cacheService; @PostConstruct public void init() { bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, properties.getBacklog()) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast(new ProtobufVarint32FrameDecoder()); channel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); channel.pipeline().addLast(new DHSecurityCodecHandler(2048)); channel.pipeline().addLast(new ProtobufDecoder(TransferProto.Transfer.getDefaultInstance())); channel.pipeline().addLast(new ProtobufEncoder()); // channel.pipeline().addLast(new IdleHandler()); channel.pipeline().addLast(new ServerChannelHandler()); } }); try { log.info("proxy server start on port " + properties.getPort()); bootstrap.bind(properties.getPort()).get(); } catch (Exception e) { log.error(e.getMessage(), e); } startProxyServer(); } private void startProxyServer() { List<Node> nodes = nodesService.selectAll(); nodes.stream() .filter(node -> { if(cacheService.getClientChannel(node.getId()) == null){ log.warn("client not connection, don't start proxy server."); return false; } return true; }) .forEach(node -> { List<Service> services = servicesService.selectNodeService(node.getId()); services.forEach(service -> Global.startProxyServer(node, service)); }); } @PreDestroy public void destroy() { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
924477ffbed5594cf2f74fe2b08f2ff0e6c8d8a9
708
java
Java
src/main/java/com/bcreagh/mpspark/routes/quickselect/QuickSelectRoute.java
bcreagh/mp.spark-algorithms
c734bf73bb438964ae9bdd9598522711f25c1fe1
[ "MIT" ]
null
null
null
src/main/java/com/bcreagh/mpspark/routes/quickselect/QuickSelectRoute.java
bcreagh/mp.spark-algorithms
c734bf73bb438964ae9bdd9598522711f25c1fe1
[ "MIT" ]
null
null
null
src/main/java/com/bcreagh/mpspark/routes/quickselect/QuickSelectRoute.java
bcreagh/mp.spark-algorithms
c734bf73bb438964ae9bdd9598522711f25c1fe1
[ "MIT" ]
null
null
null
25.285714
72
0.717514
1,003,018
package com.bcreagh.mpspark.routes.quickselect; import com.bcreagh.javaalgos.select.QuickSelect; import com.bcreagh.mpspark.routes.AlgorithmRoute; import com.bcreagh.mpspark.routes.routeutils.MpRoute; @MpRoute public class QuickSelectRoute extends AlgorithmRoute<QuickSelectInput> { private final String ROUTE_NAME = "quickselect"; @Override protected String routeName() { return ROUTE_NAME; } @Override protected Class<?> inputType() { return QuickSelectInput.class; } @Override protected Object algorithm() { QuickSelect<Integer> quickSelect = new QuickSelect<>(); return quickSelect.select(input.getInput(), input.getK()); } }
924478a168c37f1fe32db9d7bcf72451d4f65754
2,104
java
Java
app/src/main/java/com/example/parstegram/CommentAdapter.java
ainsleyogarro/Parstegram
5f76101cfe8867e3ecf7ee369de7aa2717edeb90
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/parstegram/CommentAdapter.java
ainsleyogarro/Parstegram
5f76101cfe8867e3ecf7ee369de7aa2717edeb90
[ "Apache-2.0" ]
1
2020-07-11T11:44:34.000Z
2020-07-12T15:19:42.000Z
app/src/main/java/com/example/parstegram/CommentAdapter.java
ainsleyogarro/Parstegram
5f76101cfe8867e3ecf7ee369de7aa2717edeb90
[ "Apache-2.0" ]
null
null
null
26.3
95
0.678707
1,003,019
package com.example.parstegram; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.parse.ParseException; import com.parse.ParseUser; import java.util.List; public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.ViewHolder> { private static String TAG = "CommentAdapter"; private Context context; private List<Comments> comments; public CommentAdapter(Context context, List<Comments> comments){ this.comments = comments; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_comment, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Comments comment = comments.get(position); holder.bind(position); } @Override public int getItemCount() { return comments.size(); } class ViewHolder extends RecyclerView.ViewHolder{ TextView tvCommentText; TextView tvUsernameText; public ViewHolder(@NonNull View itemView) { super(itemView); tvCommentText = itemView.findViewById(R.id.tvCommmentText); tvUsernameText = itemView.findViewById(R.id.tvCommentUsername); } public void bind(int position) { Comments comment = comments.get(position); tvCommentText.setText(comment.getKeyText()); ParseUser user = comment.getUser(); try { tvUsernameText.setText(comment.getUser().fetchIfNeeded().getUsername()); } catch (ParseException e) { e.printStackTrace(); } } } }
92447916054a0052346da8a6e7fd846d1db111fe
2,471
java
Java
cas-server-core/src/test/java/org/jasig/cas/validation/Cas10ProtocolValidationSpecificationTests.java
osuisumi/mycas
5952f56dd8818acd70deb08c494197e1f33da7cb
[ "Apache-2.0" ]
39
2017-12-04T11:53:35.000Z
2021-05-19T10:52:19.000Z
cas-server-core/src/test/java/org/jasig/cas/validation/Cas10ProtocolValidationSpecificationTests.java
osuisumi/mycas
5952f56dd8818acd70deb08c494197e1f33da7cb
[ "Apache-2.0" ]
7
2016-10-11T09:41:41.000Z
2017-11-17T06:20:40.000Z
cas-server-core/src/test/java/org/jasig/cas/validation/Cas10ProtocolValidationSpecificationTests.java
osuisumi/mycas
5952f56dd8818acd70deb08c494197e1f33da7cb
[ "Apache-2.0" ]
23
2017-09-22T08:04:53.000Z
2022-02-18T08:31:40.000Z
33.391892
113
0.740591
1,003,020
/* * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.cas.validation; import static org.junit.Assert.*; import org.jasig.cas.TestUtils; import org.junit.Test; /** * @author Scott Battaglia * @since 3.0.0 */ public class Cas10ProtocolValidationSpecificationTests { @Test public void verifyRenewGettersAndSettersFalse() { final Cas10ProtocolValidationSpecification s = new Cas10ProtocolValidationSpecification(); s.setRenew(false); assertFalse(s.isRenew()); } @Test public void verifyRenewGettersAndSettersTrue() { final Cas10ProtocolValidationSpecification s = new Cas10ProtocolValidationSpecification(); s.setRenew(true); assertTrue(s.isRenew()); } @Test public void verifyRenewAsTrueAsConstructor() { assertTrue(new Cas10ProtocolValidationSpecification(true).isRenew()); } @Test public void verifyRenewAsFalseAsConstructor() { assertFalse(new Cas10ProtocolValidationSpecification(false).isRenew()); } @Test public void verifySatisfiesSpecOfTrue() { assertTrue(new Cas10ProtocolValidationSpecification(true).isSatisfiedBy(TestUtils.getAssertion(true))); } public void verifyNotSatisfiesSpecOfTrue() { assertFalse(new Cas10ProtocolValidationSpecification(true).isSatisfiedBy(TestUtils.getAssertion(false))); } public void verifySatisfiesSpecOfFalse() { assertTrue(new Cas10ProtocolValidationSpecification(false).isSatisfiedBy(TestUtils.getAssertion(true))); } public void verifySatisfiesSpecOfFalse2() { assertTrue(new Cas10ProtocolValidationSpecification(false).isSatisfiedBy(TestUtils.getAssertion(false))); } }
9244792041adcc3478d0bb159bc6d5c3cca787b6
1,283
java
Java
sample/src/main/java/io/noties/markwon/sample/customextension/IconNode.java
vfishv/Markwon
a26c13c93a0bccb828118b8df4266d8249993cd0
[ "Apache-2.0" ]
1
2020-06-19T05:17:45.000Z
2020-06-19T05:17:45.000Z
sample/src/main/java/io/noties/markwon/sample/customextension/IconNode.java
vfishv/Markwon
a26c13c93a0bccb828118b8df4266d8249993cd0
[ "Apache-2.0" ]
null
null
null
sample/src/main/java/io/noties/markwon/sample/customextension/IconNode.java
vfishv/Markwon
a26c13c93a0bccb828118b8df4266d8249993cd0
[ "Apache-2.0" ]
1
2020-03-17T08:31:18.000Z
2020-03-17T08:31:18.000Z
20.693548
88
0.59392
1,003,021
package io.noties.markwon.sample.customextension; import androidx.annotation.NonNull; import org.commonmark.node.CustomNode; import org.commonmark.node.Delimited; @SuppressWarnings("WeakerAccess") public class IconNode extends CustomNode implements Delimited { public static final char DELIMITER = '@'; public static final String DELIMITER_STRING = "" + DELIMITER; private final String name; private final String color; private final String size; public IconNode(@NonNull String name, @NonNull String color, @NonNull String size) { this.name = name; this.color = color; this.size = size; } @NonNull public String name() { return name; } @NonNull public String color() { return color; } @NonNull public String size() { return size; } @Override public String getOpeningDelimiter() { return DELIMITER_STRING; } @Override public String getClosingDelimiter() { return DELIMITER_STRING; } @Override public String toString() { return "IconNode{" + "name='" + name + '\'' + ", color='" + color + '\'' + ", size='" + size + '\'' + '}'; } }
9244793be5e5c431dcc2f497befe3c339f694b88
8,994
java
Java
backend/manager/modules/enginesso/src/main/java/org/ovirt/engine/core/sso/utils/SsoContext.java
StevenCode/ovirt-engine
71ce0d81815d4dcddee27634167cc006aac0dd4b
[ "Apache-2.0" ]
null
null
null
backend/manager/modules/enginesso/src/main/java/org/ovirt/engine/core/sso/utils/SsoContext.java
StevenCode/ovirt-engine
71ce0d81815d4dcddee27634167cc006aac0dd4b
[ "Apache-2.0" ]
1
2020-04-24T01:12:59.000Z
2020-04-24T01:12:59.000Z
backend/manager/modules/enginesso/src/main/java/org/ovirt/engine/core/sso/utils/SsoContext.java
StevenCode/ovirt-engine
71ce0d81815d4dcddee27634167cc006aac0dd4b
[ "Apache-2.0" ]
null
null
null
35.270588
114
0.668223
1,003,022
package org.ovirt.engine.core.sso.utils; import java.io.Serializable; import java.security.cert.Certificate; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.http.conn.util.InetAddressUtils; import org.ovirt.engine.api.extensions.Base; import org.ovirt.engine.api.extensions.aaa.Authn; import org.ovirt.engine.core.extensions.mgr.ConfigurationException; import org.ovirt.engine.core.extensions.mgr.ExtensionProxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SsoContext implements Serializable{ private static final long serialVersionUID = 2059075681091705372L; private SsoLocalConfig ssoLocalConfig; private SsoExtensionsManager ssoExtensionsManager; private NegotiateAuthUtils negotiateAuthUtils; private LocalizationUtils localizationUtils; private String ssoDefaultProfile; private List<String> ssoProfiles; private List<String> ssoProfilesSupportingPasswd; private List<String> ssoProfilesSupportingPasswdChange; private Map<String, ClientInfo> ssoClientRegistry; private Map<String, SsoSession> ssoSessions = new ConcurrentHashMap<>(); private Map<String, SsoSession> ssoSessionsById = new ConcurrentHashMap<>(); private Map<String, AuthenticationProfile> profiles = null; private Map<String, List<String>> scopeDependenciesMap = new HashMap<>(); private String engineUrl; private Certificate engineCertificate; private static final Logger log = LoggerFactory.getLogger(SsoContext.class); public void init(SsoLocalConfig ssoLocalConfig) { this.ssoLocalConfig = ssoLocalConfig; engineUrl = ssoLocalConfig.getProperty("SSO_ENGINE_URL"); createProfiles(); } private void createProfiles() { // Get the extensions that correspond to authn (authentication) service. // For each extension - get the relevant authn extension. Map<String, AuthenticationProfile> results = new HashMap<>(); for (ExtensionProxy authnExtension : ssoExtensionsManager.getExtensionsByService(Authn.class.getName())) { try { String mapperName = authnExtension.getContext().<Properties>get(Base.ContextKeys.CONFIGURATION) .getProperty(Authn.ConfigKeys.MAPPING_PLUGIN); String authzName = authnExtension.getContext().<Properties>get(Base.ContextKeys.CONFIGURATION) .getProperty(Authn.ConfigKeys.AUTHZ_PLUGIN); AuthenticationProfile profile = new AuthenticationProfile( authnExtension, ssoExtensionsManager.getExtensionByName(authzName), mapperName != null ? ssoExtensionsManager.getExtensionByName(mapperName) : null ); if (results.containsKey(profile.getName())) { log.warn( "Profile name '{}' already registered for '{}', ignoring for '{}'", profile.getName(), results.get(profile.getName()).getAuthnName(), profile.getAuthnName() ); } else { results.put(profile.getName(), profile); } } catch (ConfigurationException e) { log.debug("Exception", e); } } profiles = results; } /** * Returns an unmodifiable list containing all the authentication profiles that have been previously loaded. */ public Collection<AuthenticationProfile> getProfiles() { return Collections.unmodifiableCollection(profiles.values()); } public SsoLocalConfig getSsoLocalConfig() { return ssoLocalConfig; } public SsoExtensionsManager getSsoExtensionsManager() { return ssoExtensionsManager; } public void setSsoExtensionsManager(SsoExtensionsManager ssoExtensionsManager) { this.ssoExtensionsManager = ssoExtensionsManager; } public String getSsoDefaultProfile() { return ssoDefaultProfile; } public void setSsoDefaultProfile(String ssoDefaultProfile) { this.ssoDefaultProfile = ssoDefaultProfile; } public List<String> getSsoProfiles() { return ssoProfiles; } public void setSsoProfiles(List<String> ssoProfiles) { this.ssoProfiles = ssoProfiles; } public List<String> getSsoProfilesSupportingPasswd() { return ssoProfilesSupportingPasswd; } public void setSsoProfilesSupportingPasswd(List<String> ssoProfiles) { this.ssoProfilesSupportingPasswd = ssoProfiles; } public List<String> getSsoProfilesSupportingPasswdChange() { return ssoProfilesSupportingPasswdChange; } public void setSsoProfilesSupportingPasswdChange(List<String> ssoProfiles) { this.ssoProfilesSupportingPasswdChange = ssoProfiles; } public void setSsoClientRegistry(Map<String, ClientInfo> ssoClientRegistry) { this.ssoClientRegistry = ssoClientRegistry; } public NegotiateAuthUtils getNegotiateAuthUtils() { return negotiateAuthUtils; } public void setNegotiateAuthUtils(NegotiateAuthUtils negotiateAuthUtils) { this.negotiateAuthUtils = negotiateAuthUtils; } public SsoSession getSsoSession(String token) { return ssoSessions.get(token); } public void registerSsoSession(SsoSession ssoSession) { ssoSessions.put(ssoSession.getAccessToken(), ssoSession); } public void removeSsoSession(String token) { ssoSessions.remove(token); } public SsoSession getSsoSessionById(String id) { return ssoSessionsById.get(id); } public void registerSsoSessionById(String ssoSessionId, SsoSession ssoSession) { ssoSession.setSessionIdToken(ssoSessionId); ssoSessionsById.put(ssoSessionId, ssoSession); } public void removeSsoSessionById(SsoSession ssoSession) { String id = ssoSession.getSessionIdToken(); if (StringUtils.isNotEmpty(id)) { ssoSessionsById.remove(id); ssoSession.setSessionIdToken(null); } } public ClientInfo getClienInfo(String clientId) { return ssoClientRegistry.get(clientId); } public String getTokenForAuthCode(String authCode) { String token = null; for (Map.Entry<String, SsoSession> entry : ssoSessions.entrySet()) { if (entry.getValue().getAuthorizationCode().equals(authCode)) { token = entry.getKey(); break; } } return token; } public String getTokenForOpenIdAuthCode(String authCode) { String token = null; for (Map.Entry<String, SsoSession> entry : ssoSessions.entrySet()) { if (entry.getValue().getAuthorizationCode().equals(authCode)) { if (entry.getValue().isTokenIssued()) { entry.getValue().setActive(false); } else { token = entry.getKey(); // the auth code should be used to obtain token only once entry.getValue().setTokenIssued(true); } break; } } return token; } public Map<String, SsoSession> getSsoSessions() { return ssoSessions; } public String getEngineUrl() { return engineUrl; } public String getEngineUrl(HttpServletRequest request) { String serverName = request.getServerName(); serverName = InetAddressUtils.isIPv6Address(serverName) ? String.format("[%s]", serverName) : serverName; return String.format("%s://%s:%s%s", request.getScheme(), serverName, request.getServerPort(), ssoLocalConfig.getProperty("ENGINE_URI")); } public void setScopeDependencies(Map<String, List<String>> scopeDependenciesMap) { this.scopeDependenciesMap = scopeDependenciesMap; } public List<String> getScopeDependencies(String scope) { if (!scopeDependenciesMap.containsKey(scope)) { return Collections.emptyList(); } return scopeDependenciesMap.get(scope); } public LocalizationUtils getLocalizationUtils() { return localizationUtils; } public void setLocalizationUtils(LocalizationUtils localizationUtils) { this.localizationUtils = localizationUtils; } public void setEngineCertificate(Certificate engineCertificate) { this.engineCertificate = engineCertificate; } public Certificate getEngineCertificate() { return engineCertificate; } }
92447958d3541d2aa5af93229ddd8693c1b54403
2,256
java
Java
RistogoServer3/src/ristogo/server/db/DBManager.java
SpeedJack/lsmsd3
0d99156bb076ac5ef4c63fa31b79a3ac8d9ac645
[ "MIT" ]
null
null
null
RistogoServer3/src/ristogo/server/db/DBManager.java
SpeedJack/lsmsd3
0d99156bb076ac5ef4c63fa31b79a3ac8d9ac645
[ "MIT" ]
null
null
null
RistogoServer3/src/ristogo/server/db/DBManager.java
SpeedJack/lsmsd3
0d99156bb076ac5ef4c63fa31b79a3ac8d9ac645
[ "MIT" ]
null
null
null
20.888889
79
0.698582
1,003,023
package ristogo.server.db; import org.neo4j.ogm.config.Configuration; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; public class DBManager { private static ThreadLocal<DBManager> instance = new ThreadLocal<DBManager>(); private static String username = "neo4j"; private static String password = "password"; private static String host = "localhost"; private static int port = 7687; private static String databaseName; private static SessionFactory factory; private Session session; private DBManager() { initFactory(); } private static synchronized final void initFactory() { if (factory != null) return; Configuration configuration = new Configuration.Builder() .uri("bolt://" + host + ":" + port) .credentials(username, password) .database(databaseName) .connectionPoolSize(150) .build(); factory = new SessionFactory(configuration, "ristogo.server.db.entities"); } public static DBManager getInstance() { if (instance.get() == null) instance.set(new DBManager()); return instance.get(); } public Session getSession() { if (session == null) session = factory.openSession(); return session; } public static Session session() { return getInstance().getSession(); } public static void setHost(String host) { if (host == null || host.isBlank()) host = "localhost"; DBManager.host = host; } public static void setPort(int port) { if (port < 0 || port > 65535) throw new IllegalArgumentException("Invalid port specified."); DBManager.port = port; } public static void setUsername(String username) { if (username == null || username.isBlank()) username = "neo4j"; DBManager.username = username; } public static void setPassword(String password) { DBManager.password = password; } public static void setDatabaseName(String databaseName) { if (databaseName != null && databaseName.isEmpty()) databaseName = null; DBManager.databaseName = databaseName; } public void close() { if (session == null) return; session.clear(); session = null; } public static void dispose() { if (instance.get() != null) instance.get().close(); if (factory == null) return; factory.close(); } }
924479b0152a316063850422299e3e1da0dcd380
1,447
java
Java
src/main/java/com/mrbysco/candyworld/registry/ModItemTier.java
Mrbysco/CandyWorld
3385074e6feb9909a0a605adcf1144b1a6f2b490
[ "MIT" ]
1
2022-03-14T04:34:11.000Z
2022-03-14T04:34:11.000Z
src/main/java/com/mrbysco/candyworld/registry/ModItemTier.java
Mrbysco/CandyWorld
3385074e6feb9909a0a605adcf1144b1a6f2b490
[ "MIT" ]
15
2021-12-06T07:19:32.000Z
2021-12-31T16:07:24.000Z
src/main/java/com/mrbysco/candyworld/registry/ModItemTier.java
Mrbysco/CandyWorld
3385074e6feb9909a0a605adcf1144b1a6f2b490
[ "MIT" ]
1
2021-12-20T19:56:44.000Z
2021-12-20T19:56:44.000Z
25.385965
152
0.760885
1,003,024
package com.mrbysco.candyworld.registry; import net.minecraft.item.IItemTier; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.LazyValue; import java.util.function.Supplier; public enum ModItemTier implements IItemTier { CHOCOLATE(2, 750, 7.0F, 2.5F, 25, () -> { return Ingredient.of(ModTags.CHOCOLATE_BARS); }), COTTON_CANDY(1, 5, 15.0F, 5.0F, 65, () -> { return Ingredient.of(ModTags.CHOCOLATE_BARS); }); private final int harvestLevel; private final int maxUses; private final float efficiency; private final float attackDamage; private final int enchantability; private final LazyValue<Ingredient> repairMaterial; ModItemTier(int harvestLevelIn, int maxUsesIn, float efficiencyIn, float attackDamageIn, int enchantabilityIn, Supplier<Ingredient> repairMaterialIn) { this.harvestLevel = harvestLevelIn; this.maxUses = maxUsesIn; this.efficiency = efficiencyIn; this.attackDamage = attackDamageIn; this.enchantability = enchantabilityIn; this.repairMaterial = new LazyValue<>(repairMaterialIn); } public int getUses() { return this.maxUses; } public float getSpeed() { return this.efficiency; } public float getAttackDamageBonus() { return this.attackDamage; } public int getLevel() { return this.harvestLevel; } public int getEnchantmentValue() { return this.enchantability; } public Ingredient getRepairIngredient() { return this.repairMaterial.get(); } }
924479e4fd3a9cbda98b9a09ed8f3f82451af7a8
7,226
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/lib/WheelController.java
FTCTechTurtles10179/TechTurtlesTurbo2019-2020
1b87dfe281520ad9d542d7215cdabf7f7a51058a
[ "MIT" ]
1
2019-12-09T05:26:08.000Z
2019-12-09T05:26:08.000Z
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/lib/WheelController.java
FTCTechTurtles10179/TechTurtlesTurbo2019-2020
1b87dfe281520ad9d542d7215cdabf7f7a51058a
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/lib/WheelController.java
FTCTechTurtles10179/TechTurtlesTurbo2019-2020
1b87dfe281520ad9d542d7215cdabf7f7a51058a
[ "MIT" ]
null
null
null
39.486339
108
0.666621
1,003,025
package org.firstinspires.ftc.teamcode.lib; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.util.Range; import org.firstinspires.ftc.teamcode.lib.util.states.State; public class WheelController { //This class can be changed for each drive train without breaking our library //The configurator that this WheelController is attached to Configurator config; //Variables for fault detection private int oldFrontLeftEncoder = 0; private int oldFrontRightEncoder = 0; private int oldBackLeftEncoder = 0; private int oldBackRightEncoder = 0; private boolean faultOccured = false; //Define the four wheels since we are using a mecanum drive train public DcMotor frontLeft; public DcMotor frontRight; public DcMotor backLeft; public DcMotor backRight; public int avgEncoder() { //Returns the average of both wheel encoders, or how return (frontLeft.getCurrentPosition() + frontRight.getCurrentPosition())/2; } public int leftEncoder() { //Returns the frontLeft encoder return frontLeft.getCurrentPosition(); } public int rightEncoder() { //Returns the frontright encoder return frontRight.getCurrentPosition(); } public void resetLeftEncoder() { frontLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); frontLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void resetRightEncoder() { frontRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); frontRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void moveXY(double tx, double ty) { //Take in translateX and translateY //Start with how fast we are moving forward double frontLeftSpd = ty; double frontRightSpd = ty; double backLeftSpd = ty; double backRightSpd = ty; //Add the strafing values frontLeftSpd -= tx; backLeftSpd += tx; frontRightSpd += tx; backRightSpd -= tx; //Make sure the final output is safe for the motors, or a speed from -1 to 1 frontLeft.setPower(Range.clip(frontLeftSpd, -1, 1)); frontRight.setPower(Range.clip(frontRightSpd, -1, 1)); backLeft.setPower(Range.clip(backLeftSpd, -1, 1)); backRight.setPower(Range.clip(backRightSpd, -1, 1)); } public void moveTurn(double tspeed) { //Take in turnSpeed //Start with the turn values double frontLeftSpd = tspeed; double backLeftSpd = tspeed; double frontRightSpd = -tspeed; double backRightSpd = -tspeed; //Make sure the final output is safe for the motors, or a speed from -1 to 1 frontLeft.setPower(Range.clip(frontLeftSpd, -1, 1)); frontRight.setPower(Range.clip(frontRightSpd, -1, 1)); backLeft.setPower(Range.clip(backLeftSpd, -1, 1)); backRight.setPower(Range.clip(backRightSpd, -1, 1)); } public void moveXYTurn(double tx, double ty, double tspeed) { //Start with how fast we are moving forward double frontLeftSpd = ty; double frontRightSpd = ty; double backLeftSpd = ty; double backRightSpd = ty; //Add the strafing values frontLeftSpd -= tx; backLeftSpd += tx; frontRightSpd += tx; backRightSpd -= tx; //Add the turning values frontLeftSpd += tspeed; backLeftSpd += tspeed; frontRightSpd -= tspeed; backRightSpd -= tspeed; //Make sure the final output is safe for the motors, or a speed from -1 to 1 frontLeft.setPower(Range.clip(frontLeftSpd, -1, 1)); frontRight.setPower(Range.clip(frontRightSpd, -1, 1)); backLeft.setPower(Range.clip(backLeftSpd, -1, 1)); backRight.setPower(Range.clip(backRightSpd, -1, 1)); } public void stopWheels() { moveXY(0,0); } public void runUsingEncoder() { frontLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER); frontRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER); backLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER); backRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void runWithoutEncoder() { frontLeft.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); frontRight.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); backLeft.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); backRight.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } public void detectMotorFault() { if (faultOccured) config.telemetry.addLine("A motor fault occurred!"); //Check if the front left motor is powered but the encoder is not moving if (frontLeft.getPower() != 0 && oldFrontLeftEncoder == frontLeft.getCurrentPosition()) { //If so, there is an encoder issue so we disable encoders faultOccured = true; frontLeft.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } //Do the same for the other motors if (frontRight.getPower() != 0 && oldFrontRightEncoder == frontRight.getCurrentPosition()) { faultOccured = true; frontRight.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } if (backLeft.getPower() != 0 && oldBackLeftEncoder == backLeft.getCurrentPosition()) { faultOccured = true; backLeft.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } if (backRight.getPower() != 0 && oldBackRightEncoder == backRight.getCurrentPosition()) { faultOccured = true; backRight.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } //Update all of the "old" values oldFrontLeftEncoder = frontLeft.getCurrentPosition(); oldFrontRightEncoder = frontRight.getCurrentPosition(); oldBackLeftEncoder = backLeft.getCurrentPosition(); oldBackRightEncoder = backRight.getCurrentPosition(); } public WheelController(Configurator config) { //Save the configurator for later. this.config = config; //Setup all the motors to what config says they are frontLeft = config.frontLeft; frontRight = config.frontRight; backLeft = config.backLeft; backRight = config.backRight; //Debug state config.stateMachine.addState(new State(() -> { if (config.getDebugMode()) { //If debug mode is active, telemetry the encoders of all wheels config.telemetry.addData("frontLeftEncoder", frontLeft.getCurrentPosition()); config.telemetry.addData("frontRightEncoder", frontRight.getCurrentPosition()); config.telemetry.addData("backLeftEncoder", backLeft.getCurrentPosition()); config.telemetry.addData("backRightEncoder", backRight.getCurrentPosition()); } return false; }, () -> {}, "Hidden")); runUsingEncoder(); //Turn on encoder speed adjustments //Reverse frontLeft and backLeft so the wheels all go forward frontLeft.setDirection(DcMotorSimple.Direction.REVERSE); backLeft.setDirection(DcMotorSimple.Direction.REVERSE); } }
92447a276ed41775d917cf8cd65a6288b2451975
2,798
java
Java
openjdk11/test/hotspot/jtreg/runtime/appcds/javaldr/AnonVmClassesDuringDumpTransformer.java
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
2
2018-06-19T05:43:32.000Z
2018-06-23T10:04:56.000Z
test/hotspot/jtreg/runtime/appcds/javaldr/AnonVmClassesDuringDumpTransformer.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
test/hotspot/jtreg/runtime/appcds/javaldr/AnonVmClassesDuringDumpTransformer.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
41.147059
106
0.705504
1,003,026
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; public class AnonVmClassesDuringDumpTransformer implements ClassFileTransformer { public byte[] transform(ClassLoader loader, String name, Class<?> classBeingRedefined, ProtectionDomain pd, byte[] buffer) throws IllegalClassFormatException { return null; } private static Instrumentation savedInstrumentation; public static void premain(String agentArguments, Instrumentation instrumentation) { System.out.println("ClassFileTransformer.premain() is called"); instrumentation.addTransformer(new AnonVmClassesDuringDumpTransformer(), /*canRetransform=*/true); savedInstrumentation = instrumentation; // This will create a Lambda, which will result in some Anonymous VM Classes // being generated. // // Look for something like these in the STDOUT: // ---------------- // ClassFileTransformer.premain() is called // Dumping class files to DUMP_CLASS_FILES/... // dump: DUMP_CLASS_FILES/java/lang/invoke/LambdaForm$MH000.class // dump: DUMP_CLASS_FILES/java/lang/invoke/LambdaForm$MH001.class // Invoked inside a Lambda // ---------------- Runnable r = () -> { System.out.println("Invoked inside a Lambda"); }; r.run(); } public static Instrumentation getInstrumentation() { return savedInstrumentation; } public static void agentmain(String args, Instrumentation inst) throws Exception { premain(args, inst); } }
92447a4e886bfa56612de21d629a93eef24dcfeb
12,025
java
Java
src/main/java/com/twilio/rest/taskrouter/v1/workspace/Worker.java
Ben-Liao/twilio-java
5073c0f3fe613f51937983c0551d797c309377a7
[ "MIT" ]
295
2015-01-04T17:00:48.000Z
2022-03-29T21:51:49.000Z
src/main/java/com/twilio/rest/taskrouter/v1/workspace/Worker.java
Ben-Liao/twilio-java
5073c0f3fe613f51937983c0551d797c309377a7
[ "MIT" ]
349
2015-01-14T19:08:16.000Z
2022-03-09T15:50:13.000Z
src/main/java/com/twilio/rest/taskrouter/v1/workspace/Worker.java
Ben-Liao/twilio-java
5073c0f3fe613f51937983c0551d797c309377a7
[ "MIT" ]
376
2015-01-03T22:31:01.000Z
2022-03-31T08:23:17.000Z
34.161932
92
0.619875
1,003,027
/** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ package com.twilio.rest.taskrouter.v1.workspace; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.twilio.base.Resource; import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; import lombok.ToString; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.ZonedDateTime; import java.util.Map; import java.util.Objects; @JsonIgnoreProperties(ignoreUnknown = true) @ToString public class Worker extends Resource { private static final long serialVersionUID = 71992031157502L; /** * Create a WorkerReader to execute read. * * @param pathWorkspaceSid The SID of the Workspace with the Workers to read * @return WorkerReader capable of executing the read */ public static WorkerReader reader(final String pathWorkspaceSid) { return new WorkerReader(pathWorkspaceSid); } /** * Create a WorkerCreator to execute create. * * @param pathWorkspaceSid The SID of the Workspace that the new Worker belongs * to * @param friendlyName A string to describe the resource * @return WorkerCreator capable of executing the create */ public static WorkerCreator creator(final String pathWorkspaceSid, final String friendlyName) { return new WorkerCreator(pathWorkspaceSid, friendlyName); } /** * Create a WorkerFetcher to execute fetch. * * @param pathWorkspaceSid The SID of the Workspace with the Worker to fetch * @param pathSid The SID of the resource to fetch * @return WorkerFetcher capable of executing the fetch */ public static WorkerFetcher fetcher(final String pathWorkspaceSid, final String pathSid) { return new WorkerFetcher(pathWorkspaceSid, pathSid); } /** * Create a WorkerUpdater to execute update. * * @param pathWorkspaceSid The SID of the Workspace with the Worker to update * @param pathSid The SID of the resource to update * @return WorkerUpdater capable of executing the update */ public static WorkerUpdater updater(final String pathWorkspaceSid, final String pathSid) { return new WorkerUpdater(pathWorkspaceSid, pathSid); } /** * Create a WorkerDeleter to execute delete. * * @param pathWorkspaceSid The SID of the Workspace with the Worker to delete * @param pathSid The SID of the resource to delete * @return WorkerDeleter capable of executing the delete */ public static WorkerDeleter deleter(final String pathWorkspaceSid, final String pathSid) { return new WorkerDeleter(pathWorkspaceSid, pathSid); } /** * Converts a JSON String into a Worker object using the provided ObjectMapper. * * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Worker object represented by the provided JSON */ public static Worker fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Worker.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { throw new ApiConnectionException(e.getMessage(), e); } } /** * Converts a JSON InputStream into a Worker object using the provided * ObjectMapper. * * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Worker object represented by the provided JSON */ public static Worker fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Worker.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { throw new ApiConnectionException(e.getMessage(), e); } } private final String accountSid; private final String activityName; private final String activitySid; private final String attributes; private final Boolean available; private final ZonedDateTime dateCreated; private final ZonedDateTime dateStatusChanged; private final ZonedDateTime dateUpdated; private final String friendlyName; private final String sid; private final String workspaceSid; private final URI url; private final Map<String, String> links; @JsonCreator private Worker(@JsonProperty("account_sid") final String accountSid, @JsonProperty("activity_name") final String activityName, @JsonProperty("activity_sid") final String activitySid, @JsonProperty("attributes") final String attributes, @JsonProperty("available") final Boolean available, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_status_changed") final String dateStatusChanged, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("friendly_name") final String friendlyName, @JsonProperty("sid") final String sid, @JsonProperty("workspace_sid") final String workspaceSid, @JsonProperty("url") final URI url, @JsonProperty("links") final Map<String, String> links) { this.accountSid = accountSid; this.activityName = activityName; this.activitySid = activitySid; this.attributes = attributes; this.available = available; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.dateStatusChanged = DateConverter.iso8601DateTimeFromString(dateStatusChanged); this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.friendlyName = friendlyName; this.sid = sid; this.workspaceSid = workspaceSid; this.url = url; this.links = links; } /** * Returns The SID of the Account that created the resource. * * @return The SID of the Account that created the resource */ public final String getAccountSid() { return this.accountSid; } /** * Returns The friendly_name of the Worker's current Activity. * * @return The friendly_name of the Worker's current Activity */ public final String getActivityName() { return this.activityName; } /** * Returns The SID of the Worker's current Activity. * * @return The SID of the Worker's current Activity */ public final String getActivitySid() { return this.activitySid; } /** * Returns The JSON string that describes the Worker. * * @return The JSON string that describes the Worker */ public final String getAttributes() { return this.attributes; } /** * Returns Whether the Worker is available to perform tasks. * * @return Whether the Worker is available to perform tasks */ public final Boolean getAvailable() { return this.available; } /** * Returns The ISO 8601 date and time in GMT when the resource was created. * * @return The ISO 8601 date and time in GMT when the resource was created */ public final ZonedDateTime getDateCreated() { return this.dateCreated; } /** * Returns The date and time in GMT of the last change to the Worker's activity. * * @return The date and time in GMT of the last change to the Worker's activity */ public final ZonedDateTime getDateStatusChanged() { return this.dateStatusChanged; } /** * Returns The ISO 8601 date and time in GMT when the resource was last updated. * * @return The ISO 8601 date and time in GMT when the resource was last updated */ public final ZonedDateTime getDateUpdated() { return this.dateUpdated; } /** * Returns The string that you assigned to describe the resource. * * @return The string that you assigned to describe the resource */ public final String getFriendlyName() { return this.friendlyName; } /** * Returns The unique string that identifies the resource. * * @return The unique string that identifies the resource */ public final String getSid() { return this.sid; } /** * Returns The SID of the Workspace that contains the Worker. * * @return The SID of the Workspace that contains the Worker */ public final String getWorkspaceSid() { return this.workspaceSid; } /** * Returns The absolute URL of the Worker resource. * * @return The absolute URL of the Worker resource */ public final URI getUrl() { return this.url; } /** * Returns The URLs of related resources. * * @return The URLs of related resources */ public final Map<String, String> getLinks() { return this.links; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Worker other = (Worker) o; return Objects.equals(accountSid, other.accountSid) && Objects.equals(activityName, other.activityName) && Objects.equals(activitySid, other.activitySid) && Objects.equals(attributes, other.attributes) && Objects.equals(available, other.available) && Objects.equals(dateCreated, other.dateCreated) && Objects.equals(dateStatusChanged, other.dateStatusChanged) && Objects.equals(dateUpdated, other.dateUpdated) && Objects.equals(friendlyName, other.friendlyName) && Objects.equals(sid, other.sid) && Objects.equals(workspaceSid, other.workspaceSid) && Objects.equals(url, other.url) && Objects.equals(links, other.links); } @Override public int hashCode() { return Objects.hash(accountSid, activityName, activitySid, attributes, available, dateCreated, dateStatusChanged, dateUpdated, friendlyName, sid, workspaceSid, url, links); } }
92447ac37cbb8a89cee1c20997183d58293c0d58
4,568
java
Java
aggregator-manager/src/test/java/org/arrowhead/wp5/agg/junit/TestFGridMapper.java
lawrizs/vme
b6eb55844304b9f477b5d82b57c065a5636be05c
[ "MIT" ]
1
2018-03-12T18:58:08.000Z
2018-03-12T18:58:08.000Z
aggregator-manager/src/test/java/org/arrowhead/wp5/agg/junit/TestFGridMapper.java
lawrizs/vme
b6eb55844304b9f477b5d82b57c065a5636be05c
[ "MIT" ]
null
null
null
aggregator-manager/src/test/java/org/arrowhead/wp5/agg/junit/TestFGridMapper.java
lawrizs/vme
b6eb55844304b9f477b5d82b57c065a5636be05c
[ "MIT" ]
3
2016-09-13T09:53:40.000Z
2019-05-21T01:28:58.000Z
30.657718
120
0.714317
1,003,028
package org.arrowhead.wp5.agg.junit; /*- * #%L * ARROWHEAD::WP5::Aggregator Manager * %% * Copyright (C) 2016 The ARROWHEAD Consortium * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import java.util.List; import junit.framework.TestCase; import org.arrowhead.wp5.agg.impl.common.AggParamAbstracter; import org.arrowhead.wp5.agg.impl.common.FGridRectangle; import org.arrowhead.wp5.agg.impl.common.FGroup; import org.arrowhead.wp5.agg.impl.grouper.FGridCellPopulated; import org.arrowhead.wp5.agg.impl.grouper.FGridMapper; import org.arrowhead.wp5.core.entities.FlexOffer; import org.junit.Before; import org.junit.Test; public class TestFGridMapper extends TestCase { private static final double AllowedDoubleError = 1E-5; @SuppressWarnings("unused") private double totalWeight = 0; private AggParamAbstracter fa2D; private FGridMapper gm; private List<FlexOffer> fl; @Override @Before public void setUp() throws Exception { this.fa2D = UtilsFoDummies.generate2DflexofferAbstracter(); this.gm = new FGridMapper(fa2D); this.fl = UtilsFoDummies.generateUniform2DFlexOffers(1234, 10000, -1, 1, -1, 1, 0, 100); // Total weight this.totalWeight = 0; for(FlexOffer f : fl) this.totalWeight += fa2D.getWeightDlg().getWeight(f); } @Test public void testCellCountsOnInserts() { gm.foClear(); // Add dummy flex-offer so that dimensions will be aligned to point (0,0) gm.foAdd(UtilsFoDummies.generateUniform2DFlexOffers(1234, 1, 0, 0, 0, 0, 0, 0)); gm.foAdd(fl); int cntCells = 0; int cntFo = 0; for(FGridCellPopulated c : gm) { cntCells ++; for(@SuppressWarnings("unused") FlexOffer f : c) cntFo ++; List<FGroup> l = c.getNeighbours(); assertEquals(3, l.size()); } assertEquals(4, cntCells); assertEquals(fl.size() + 1, cntFo); } @Test public void testCellCountsOnModify() { gm.foClear(); FlexOfferModStats stats = UtilsFoDummies.generateRandomModifications(this.fa2D, this.fl, gm, this.fl.size() * 1, 0.7); int cntFo = 0; for(FGridCellPopulated c : gm) { for(@SuppressWarnings("unused") FlexOffer f : c) cntFo ++; } assertEquals(stats.addedFOS.size() - stats.removedFOS.size(), cntFo); } @Test public void testWeightBalance() { gm.foClear(); FlexOfferModStats stats = UtilsFoDummies.generateRandomModifications(this.fa2D, this.fl, gm, this.fl.size() * 1, 0.7); double weightCells = 0; for(FGridCellPopulated c : gm) { double weightFOs = 0; for(FlexOffer f : c) weightFOs += this.fa2D.getWeightDlg().getWeight(f); assertEquals(weightFOs, c.getGroupWeight(fa2D), AllowedDoubleError); weightCells += c.getGroupWeight(fa2D); } assertEquals(weightCells, stats.addedWeight - stats.removedWeight, AllowedDoubleError); } @Test public void testMBRs() { gm.foClear(); UtilsFoDummies.generateRandomModifications(this.fa2D, this.fl, gm, this.fl.size() * 1, 0.7); for(FGridCellPopulated c : gm) { FGridRectangle r = new FGridRectangle(2); r.clearRectangle(); for(FlexOffer f : c) r.extendMBR(this.fa2D.getFlexOfferVector(f)); FGridRectangle r2 = c.getMBR(this.fa2D); for(int i=0; i<2; i++) { assertEquals(r.getVecHigh().getValues()[i], r2.getVecHigh().getValues()[i], AllowedDoubleError); assertEquals(r.getVecLow().getValues()[i], r2.getVecLow().getValues()[i], AllowedDoubleError); } } } public static void main(String[] args) { junit.textui.TestRunner.run(TestFGridMapper.class); } }
92447ac6ba7563233443a8e3325609a6b8694c43
1,666
java
Java
slb/src/main/java/com/ctrip/zeus/restful/resource/meta/SlbServersResource.java
sdgdsffdsfff/zeus
d77dda1bc523d62d1b087988324636b3cea36ce0
[ "Apache-2.0" ]
55
2015-03-03T09:55:31.000Z
2021-09-16T09:26:38.000Z
slb/src/main/java/com/ctrip/zeus/restful/resource/meta/SlbServersResource.java
sdgdsffdsfff/zeus
d77dda1bc523d62d1b087988324636b3cea36ce0
[ "Apache-2.0" ]
8
2016-11-19T14:26:01.000Z
2021-12-09T19:43:22.000Z
slb/src/main/java/com/ctrip/zeus/restful/resource/meta/SlbServersResource.java
ctripcorp/zeus
d3b8bdc25cc981765814ec8b9cdfaa867583267d
[ "Apache-2.0" ]
43
2015-03-24T08:01:35.000Z
2022-01-27T03:55:52.000Z
30.851852
104
0.657863
1,003,029
package com.ctrip.zeus.restful.resource.meta; import com.ctrip.zeus.model.model.Slb; import com.ctrip.zeus.model.model.SlbServer; import com.ctrip.zeus.service.model.IdVersion; import com.ctrip.zeus.service.model.SelectionMode; import com.ctrip.zeus.service.model.SlbRepository; import com.ctrip.zeus.service.query.SlbCriteriaQuery; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.ws.rs.Path; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author:xingchaowang * @date: 2016/8/11. */ @Component @Path("/meta/slb-servers") public class SlbServersResource extends MetaSearchResource{ @Resource private SlbRepository repository; @Resource private SlbCriteriaQuery queryCriteria; StrCache cache; public SlbServersResource() { cache = new StrCache(); } @Override MetaDataCache<List<CacheItem>> getCache() { return cache; } class StrCache extends MetaDataCache<List<CacheItem>> { @Override List<CacheItem> queryData() throws Exception { Set<IdVersion> idVersionSet = queryCriteria.queryAll(SelectionMode.OFFLINE_FIRST); List<Slb> list = repository.list(idVersionSet.toArray(new IdVersion[idVersionSet.size()])); List<CacheItem> all = new ArrayList<>(list.size()); for (Slb item : list) { for (SlbServer jtem : item.getSlbServers()) { all.add(new CacheItem(jtem.getIp(),jtem.getHostName(),null)); } } return all; } } }
92447ad842eea6e92fa1864a03d4d4d3078a5a35
490
java
Java
Chapter09/GetBitValue/src/main/java/coding/challenge/Bits.java
aishwarya4444/The-Complete-Coding-Interview-Guide-in-Java
d0f33e21c2fc03e9b8d000977e2c121c9b358418
[ "MIT" ]
196
2020-02-02T13:53:03.000Z
2022-03-31T15:08:51.000Z
Chapter09/GetBitValue/src/main/java/coding/challenge/Bits.java
aishwarya4444/The-Complete-Coding-Interview-Guide-in-Java
d0f33e21c2fc03e9b8d000977e2c121c9b358418
[ "MIT" ]
null
null
null
Chapter09/GetBitValue/src/main/java/coding/challenge/Bits.java
aishwarya4444/The-Complete-Coding-Interview-Guide-in-Java
d0f33e21c2fc03e9b8d000977e2c121c9b358418
[ "MIT" ]
162
2020-01-24T09:18:34.000Z
2022-03-30T03:10:16.000Z
19.6
88
0.5
1,003,030
package coding.challenge; public final class Bits { private Bits() { throw new AssertionError("Cannot be instantiated"); } public static char getValue(int n, int k) { if (k < 0 || k > 31) { throw new IllegalArgumentException("The position must be between 0 and 31"); } int result = 1 & (n >> k); // or, int result = n & (1 << k); if (result == 0) { return '0'; } return '1'; } }
92447b17cf050829a59f3e0ab8079a0ca46efc5a
2,403
java
Java
LaboratoryAnimalHousing/src/main/java/org/lah/AnimalBreeding/service/impl/EstrusSowServiceImpl.java
leaving-voider/LaboratoryAnimalHousing
5520a0125c6ad77a935b39ec62560f3dfe50eb07
[ "MIT" ]
null
null
null
LaboratoryAnimalHousing/src/main/java/org/lah/AnimalBreeding/service/impl/EstrusSowServiceImpl.java
leaving-voider/LaboratoryAnimalHousing
5520a0125c6ad77a935b39ec62560f3dfe50eb07
[ "MIT" ]
null
null
null
LaboratoryAnimalHousing/src/main/java/org/lah/AnimalBreeding/service/impl/EstrusSowServiceImpl.java
leaving-voider/LaboratoryAnimalHousing
5520a0125c6ad77a935b39ec62560f3dfe50eb07
[ "MIT" ]
1
2021-06-01T06:06:20.000Z
2021-06-01T06:06:20.000Z
33.84507
237
0.744902
1,003,031
package org.lah.AnimalBreeding.service.impl; import org.lah.AnimalBreeding.domain.EstrusSow; import org.lah.AnimalBreeding.domain.PageInfo; import org.lah.AnimalBreeding.mapper.EstrusSowMapper; import org.lah.AnimalBreeding.service.EstrusSowService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 发情母猪行为记录表用户Service接口实现类 */ @Service("EstrusSowService") @Transactional public class EstrusSowServiceImpl implements EstrusSowService { @Autowired private EstrusSowMapper estrusSowMapper; //分页查询发情母猪行为记录表 @Override public PageInfo<EstrusSow> findPageInfo(Integer ActionID,String AnimalNumber,String BehaviorStartTime,String BehaviorEndTime, String BehaviorDescription,String TreatmentPlan,String TreatmentResult,Integer pageIndex, Integer pageSize) { PageInfo<EstrusSow> pi = new PageInfo<EstrusSow>(); pi.setPageIndex(pageIndex); pi.setPageSize(pageSize); //获取发情母猪行为记录表总条数 Integer totalCount = estrusSowMapper.totalCount(ActionID,AnimalNumber,BehaviorStartTime); if (totalCount>0){ pi.setTotalCount(totalCount); List<EstrusSow> estrusSowList = estrusSowMapper.getEstrusSow(ActionID,AnimalNumber,BehaviorStartTime,BehaviorEndTime,BehaviorDescription,TreatmentPlan,TreatmentResult, (pi.getPageIndex()-1)*pi.getPageSize(),pi.getPageSize()); pi.setList(estrusSowList); } return pi; } //查询所有发情母猪行为记录表信息 @Override public List<EstrusSow> getAll(){ List<EstrusSow> estrusSowList = estrusSowMapper.getAll(); return estrusSowList; } //通过编号删除发情母猪行为记录表 @Override public int deleteEstrusSow(Integer ActionID) { return estrusSowMapper.deleteEstrusSow(ActionID); } //添加发情母猪行为记录表信息 @Override public int addEstrusSow(EstrusSow estrusSow) { return estrusSowMapper.addEstrusSow(estrusSow); } //修改发情母猪行为记录表信息 @Override public int updateEstrusSow(EstrusSow estrusSow) { return estrusSowMapper.updateEstrusSow(estrusSow); } //根据ID查询发情母猪行为记录表信息 @Override public EstrusSow findEstrusSowById (Integer ActionID){ EstrusSow estrusSow = estrusSowMapper.findEstrusSowById(ActionID); return estrusSow; } }
92447caebfb2557bdb6480886f29c774e9bcd70a
1,572
java
Java
app/src/main/java/com/ybhrxjavademo/ShowViewActivity.java
yihaha/YBHRxjava
0a0526f6a8c21faa6d6db598064b7d91403fc8be
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ybhrxjavademo/ShowViewActivity.java
yihaha/YBHRxjava
0a0526f6a8c21faa6d6db598064b7d91403fc8be
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ybhrxjavademo/ShowViewActivity.java
yihaha/YBHRxjava
0a0526f6a8c21faa6d6db598064b7d91403fc8be
[ "Apache-2.0" ]
null
null
null
33.446809
92
0.709288
1,003,032
package com.ybhrxjavademo; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import com.ybhrxjavademo.viewtest.CircleData; import com.ybhrxjavademo.viewtest.CircleView; import com.ybhrxjavademo.viewtest.TestView; import java.util.ArrayList; public class ShowViewActivity extends AppCompatActivity { private CircleView mCircleView; private TestView mTestView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_view); mCircleView = (CircleView) findViewById(R.id.ycir_view); mCircleView.setVisibility(View.GONE); ArrayList<CircleData> circleDatas = new ArrayList<>(); for (int i = 1; i < 6; i++) { CircleData circleData = new CircleData(i + "", i * 10); circleDatas.add(circleData); } mCircleView.setStartAngle(10); mCircleView.setData(circleDatas); mTestView = (TestView) findViewById(R.id.testview); mTestView.setView(50); // ObjectAnimator rotation = ObjectAnimator.ofFloat(mTestView, "rotation", 0f, 360f); ObjectAnimator rotation = ObjectAnimator.ofFloat(mTestView, "scaleY", 0.5f, 3f,1f); rotation.setDuration(3000); //下面两行配合起来会不断执行动画 rotation.setRepeatCount(ValueAnimator.INFINITE); rotation.setRepeatMode(ValueAnimator.REVERSE); rotation.start(); } }
92447cd662aeb105b018102b87344fe22b36fe70
1,869
java
Java
aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/TimeRange.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/TimeRange.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/TimeRange.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
29.666667
119
0.65115
1,003,033
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.macie2.model; import javax.annotation.Generated; /** * <p> * An inclusive time period that Amazon Macie usage data applies to. Possible values are: * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum TimeRange { MONTH_TO_DATE("MONTH_TO_DATE"), PAST_30_DAYS("PAST_30_DAYS"); private String value; private TimeRange(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return TimeRange corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static TimeRange fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (TimeRange enumEntry : TimeRange.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
92447f2cfda932606c7cd10af9f67e35dfcf190e
1,453
java
Java
src/main/java/simulator/guis/components/Ball.java
abysmli/Simulator-FDS
bc080c50201f9f9faf9177c2bd63cc521eea121c
[ "MIT" ]
null
null
null
src/main/java/simulator/guis/components/Ball.java
abysmli/Simulator-FDS
bc080c50201f9f9faf9177c2bd63cc521eea121c
[ "MIT" ]
null
null
null
src/main/java/simulator/guis/components/Ball.java
abysmli/Simulator-FDS
bc080c50201f9f9faf9177c2bd63cc521eea121c
[ "MIT" ]
null
null
null
30.914894
96
0.615967
1,003,034
package simulator.guis.components; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; public class Ball extends SimulationComponent { private static final long serialVersionUID = 1L; private boolean state; public Ball(int x, int y, int width, int height, double pipeWidthPorcentage, String name) { super(x, y, width, height, pipeWidthPorcentage); } @Override protected void paintComponent(Graphics _g) { Graphics2D g = (Graphics2D) _g; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paintComponent(g); if (state) { g.setColor(Color.black); g.drawRect(0, 0, this.getWidthComponent(), this.getWidthComponent()); g.setColor(Color.green); g.fillRect(1, 1, this.getWidthComponent() - 1, this.getWidthComponent() - 1); } else { g.setColor(Color.black); g.drawRect(0, 0, this.getWidthComponent(), this.getWidthComponent()); g.setColor(Color.gray); g.fillRect(1, 1, this.getWidthComponent() - 1, this.getWidthComponent() - 1); } } /** * * @param state: true means pump on and false means pump off. */ public void setBallState(boolean state) { this.state = state; repaint(); } }
92447fb511289df2f9f0a6bc9233467a74dd836c
1,790
java
Java
2471 The Trip, 2007/Main.java
ysp2000/tju-solutions
3abdc4e93da1698b12377de844eb806fff63ea59
[ "MIT" ]
null
null
null
2471 The Trip, 2007/Main.java
ysp2000/tju-solutions
3abdc4e93da1698b12377de844eb806fff63ea59
[ "MIT" ]
null
null
null
2471 The Trip, 2007/Main.java
ysp2000/tju-solutions
3abdc4e93da1698b12377de844eb806fff63ea59
[ "MIT" ]
null
null
null
19.247312
63
0.532402
1,003,035
import java.io.*; import java.util.*; import java.util.Map.Entry; import static java.lang.Math.*; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) { System.setIn(new FileInputStream("input.txt")); } } catch (SecurityException e) { } new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); boolean blank = false; for (int n = nextInt(); n > 0; n = nextInt()) { if (blank) { out.println(); } blank = true; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); int ans = 0; for (int i = 0; i < n; i++) { int x = nextInt(); if (!map.containsKey(x)) { map.put(x, 1); } else { map.put(x, map.get(x) + 1); } ans = max(ans, map.get(x)); } int[][] a = new int [ans][n / ans + 1]; int[] sz = new int [ans]; int ca = 0; for (Entry<Integer, Integer> e : map.entrySet()) { int num = e.getKey(); int cnt = e.getValue(); for (int i = 0; i < cnt; i++) { a[ca][sz[ca]++] = num; ca++; if (ca >= ans) { ca = 0; } } } out.println(ans); for (int i = 0; i < ans; i++) { for (int j = 0; j < sz[i]; j++) { out.print((j > 0 ? " " : "") + a[i][j]); } out.println(); } } out.close(); } String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } }
92447fe0a5fcd5fa86a18d13f76655e9d41e8d3a
3,957
java
Java
merchantapp/com/google/android/libraries/commerce/hce/ndef/NdefRecords.java
ydong08/GooglePay_AP
8063f2946cb74a070f2009cefae29887bfae0dbb
[ "MIT" ]
null
null
null
merchantapp/com/google/android/libraries/commerce/hce/ndef/NdefRecords.java
ydong08/GooglePay_AP
8063f2946cb74a070f2009cefae29887bfae0dbb
[ "MIT" ]
null
null
null
merchantapp/com/google/android/libraries/commerce/hce/ndef/NdefRecords.java
ydong08/GooglePay_AP
8063f2946cb74a070f2009cefae29887bfae0dbb
[ "MIT" ]
null
null
null
39.57
224
0.607026
1,003,036
package com.google.android.libraries.commerce.hce.ndef; import android.nfc.FormatException; import android.nfc.NdefRecord; import com.google.android.libraries.commerce.hce.common.SmartTap2Values; import com.google.android.libraries.logging.text.FormattingLogger; import com.google.android.libraries.logging.text.FormattingLoggers; import com.google.common.primitives.Bytes; import java.util.Arrays; public class NdefRecords { private static final FormattingLogger LOG = FormattingLoggers.newContextLogger(); public static final byte[] TYPE_PRIMITIVE = "P".getBytes(SmartTap2Values.TYPE_CHARSET); private NdefRecords() { } public static byte[] getType(NdefRecord ndefRecord, short s) { if (s == (short) 0) { return ndefRecord.getId(); } return ndefRecord.getType(); } public static NdefRecord compose(byte[] bArr, byte[] bArr2, short s) { if (s == (short) 0) { return new NdefRecord((short) 4, null, bArr, bArr2); } return new NdefRecord((short) 4, bArr, null, bArr2); } public static NdefRecord createText(byte[] bArr, Format format, byte[] bArr2, byte[] bArr3, short s) throws FormatException { int i = 128; if (bArr3 == null) { throw new NullPointerException("textBytes is null"); } else if (bArr2 == null) { throw new NullPointerException("languageBytes is null"); } else if (bArr2.length >= 128) { throw new IllegalArgumentException("language code is too long, must be < 256 bytes."); } else if (s == (short) 0) { r0 = new byte[3][]; r0[0] = new byte[]{(byte) bArr2.length}; r0[1] = bArr2; r0[2] = bArr3; return createPrimitive(bArr, format, Bytes.concat(r0), s); } else { if (format == Format.ASCII || format == Format.UTF_8) { i = 0; } else if (format != Format.UTF_16) { String valueOf = String.valueOf(format.name()); throw new FormatException(new StringBuilder(String.valueOf(valueOf).length() + 75).append("Unexpected format for text NdefRecord: ").append(valueOf).append(". Only UTF 8 or UTF 16 are expected.").toString()); } r2 = new byte[3][]; r2[0] = new byte[]{(byte) ((char) (i + bArr2.length))}; r2[1] = bArr2; r2[2] = bArr3; return new NdefRecord((short) 1, NdefRecord.RTD_TEXT, bArr, Bytes.concat(r2)); } } public static NdefRecord createPrimitive(byte[] bArr, Format format, byte[] bArr2, short s) { r0 = new byte[2][]; r0[0] = new byte[]{format.value()}; r0[1] = bArr2; byte[] concat = Bytes.concat(r0); if (s == (short) 0) { return new NdefRecord((short) 4, TYPE_PRIMITIVE, bArr, concat); } if (!format.isText()) { return compose(bArr, concat, s); } try { return createText(bArr, format, new byte[0], bArr2, s); } catch (Throwable e) { LOG.e(e, "Should not happen! Internally used format is not supported.", new Object[0]); throw new IllegalStateException("Should not happen! Internally used format is not supported.", e); } } public static byte getByte(NdefRecord ndefRecord) { return getByte(ndefRecord, 0); } public static byte getByte(NdefRecord ndefRecord, int i) { return ndefRecord.getPayload()[i]; } public static byte[] getBytes(NdefRecord ndefRecord, int i) { return getBytes(ndefRecord, 0, i); } public static byte[] getAllBytes(NdefRecord ndefRecord, int i) { return getBytes(ndefRecord, i, ndefRecord.getPayload().length - i); } public static byte[] getBytes(NdefRecord ndefRecord, int i, int i2) { return Arrays.copyOfRange(ndefRecord.getPayload(), i, i + i2); } }
924481d225fbd09cf592402d9422f3d829bb2a7b
2,054
java
Java
smqtt-bootstrap/src/test/java/ClusterNode1.java
quickmsg/smqtt
a29e51672143cc2093cefdca0c11c95ae867c2e9
[ "Apache-2.0" ]
332
2021-04-29T08:13:06.000Z
2022-03-31T03:35:23.000Z
smqtt-bootstrap/src/test/java/ClusterNode1.java
luckyDTF/smqtt
a29e51672143cc2093cefdca0c11c95ae867c2e9
[ "Apache-2.0" ]
8
2021-06-07T04:11:09.000Z
2021-10-30T07:56:14.000Z
smqtt-bootstrap/src/test/java/ClusterNode1.java
luckyDTF/smqtt
a29e51672143cc2093cefdca0c11c95ae867c2e9
[ "Apache-2.0" ]
110
2021-04-30T02:36:40.000Z
2022-03-30T08:11:12.000Z
38.037037
132
0.360759
1,003,037
import ch.qos.logback.classic.Level; import io.github.quickmsg.common.config.BootstrapConfig; import io.github.quickmsg.core.Bootstrap; /** * @author luxurong */ public class ClusterNode1 { public static void main(String[] args) throws InterruptedException { Bootstrap bootstrap = Bootstrap.builder() .rootLevel(Level.INFO) .websocketConfig( BootstrapConfig.WebsocketConfig .builder() .enable(false) .path("/mqtt") .port(8888) .build() ) .tcpConfig( BootstrapConfig .TcpConfig .builder() .port(8882) .username("smqtt") .password("smqtt") .build()) .httpConfig( BootstrapConfig .HttpConfig .builder() .enable(false) .accessLog(true) .admin(BootstrapConfig.HttpAdmin.builder().enable(true).username("smqtt").password("smqtt").build()) .build()) .clusterConfig( BootstrapConfig. ClusterConfig .builder() .enable(false) .namespace("smqtt") .node("node-1") .port(7773) .url("127.0.0.1:7771,127.0.0.1:7772"). build()) .build() .start().block(); assert bootstrap != null; Thread.sleep(10000000); } }
924481db627bcfee85d04fbd52160d42d76d9cfc
3,735
java
Java
src/main/java/frc/robot/subsystems/drive/DriveSubsystem.java
mtjones330/MyRobot
4d7cce45747efd5e978e1038211a7903374d6d86
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/subsystems/drive/DriveSubsystem.java
mtjones330/MyRobot
4d7cce45747efd5e978e1038211a7903374d6d86
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/subsystems/drive/DriveSubsystem.java
mtjones330/MyRobot
4d7cce45747efd5e978e1038211a7903374d6d86
[ "BSD-3-Clause" ]
1
2021-07-28T22:45:22.000Z
2021-07-28T22:45:22.000Z
28.730769
131
0.749665
1,003,038
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems.drive; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.geometry.Pose2d; import edu.wpi.first.wpilibj.kinematics.DifferentialDriveOdometry; import edu.wpi.first.wpilibj.kinematics.DifferentialDriveWheelSpeeds; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants.DriveConstants; public class DriveSubsystem extends SubsystemBase { private final SixWheelDifferentialDrivetrain drivetrain = new SixWheelDifferentialDrivetrain(); private final Encoder leftEncoder = new Encoder(DriveConstants.EncoderChannels.LEFT_A, DriveConstants.EncoderChannels.LEFT_B); private final Encoder rightEncoder = new Encoder(DriveConstants.EncoderChannels.RIGHT_A, DriveConstants.EncoderChannels.RIGHT_B); private final AnalogGyro gyro = new AnalogGyro(DriveConstants.GYRO_CHANNEL); private final DifferentialDriveOdometry odometry = new DifferentialDriveOdometry(gyro.getRotation2d()); private final DriveSubsystemSimulation simulation = new DriveSubsystemSimulation( gyro, leftEncoder, rightEncoder, () -> drivetrain.getLeftSpeed(), () -> drivetrain.getRightSpeed() ); private Field2d field = new Field2d(); public DriveSubsystem() { setSlowSpeed(); initEncoders(); initDashboard(); } @Override public void periodic() { updateOdometry(); updateRobotPositionOnField(); } public void arcadeDrive(double speed, double rotation) { drivetrain.arcadeDrive(speed, rotation); } public void tankDriveVolts(double leftVoltage, double rightVoltage) { drivetrain.tankDriveVolts(leftVoltage, rightVoltage); } public void setSlowSpeed() { drivetrain.setMaxOutput(DriveConstants.SLOW_SPEED); } public void setFastSpeed() { drivetrain.setMaxOutput(DriveConstants.FAST_SPEED); } public void setMaxOutput(double maxOutput) { drivetrain.setMaxOutput(maxOutput); } public void zeroHeading() { gyro.reset(); } public double getHeading() { return gyro.getRotation2d().getDegrees(); } public double getTurnRate() { return -gyro.getRate(); } public void simulationPeriodic() { simulation.update(); } public Pose2d getPose() { return odometry.getPoseMeters(); } public DifferentialDriveWheelSpeeds getWheelSpeeds() { return new DifferentialDriveWheelSpeeds(leftEncoder.getRate(), rightEncoder.getRate()); } public void resetOdometry(Pose2d pose) { resetEncoders(); odometry.resetPosition(pose, gyro.getRotation2d()); } public double getAverageEncoderDistance() { return (leftEncoder.getDistance() + rightEncoder.getDistance()) / 2.0; } private void initEncoders() { double distancePerPulse = Math.PI * DriveConstants.WHEEL_DIAMETER / DriveConstants.ENCODER_RESOLUTION; leftEncoder.setDistancePerPulse(distancePerPulse); rightEncoder.setDistancePerPulse(distancePerPulse); resetEncoders(); } private void initDashboard() { SmartDashboard.putData("Field", field); } private void updateOdometry() { odometry.update( gyro.getRotation2d(), leftEncoder.getDistance(), rightEncoder.getDistance() ); } private void updateRobotPositionOnField() { Pose2d pose = getPose(); field.setRobotPose(pose); } private void resetEncoders() { leftEncoder.reset(); rightEncoder.reset(); } }
9244823dcbfa5dbba155e50439ae57e3a19732ad
2,516
java
Java
src/src/org/graalvm/compiler/replacements/amd64/PluginFactory_AMD64StringIndexOfNode.java
HurleyWong/RTFSC-JDK
9bb72042116ff3dbb8f71c2372c8697629f4d730
[ "MIT" ]
null
null
null
src/src/org/graalvm/compiler/replacements/amd64/PluginFactory_AMD64StringIndexOfNode.java
HurleyWong/RTFSC-JDK
9bb72042116ff3dbb8f71c2372c8697629f4d730
[ "MIT" ]
null
null
null
src/src/org/graalvm/compiler/replacements/amd64/PluginFactory_AMD64StringIndexOfNode.java
HurleyWong/RTFSC-JDK
9bb72042116ff3dbb8f71c2372c8697629f4d730
[ "MIT" ]
null
null
null
53.531915
296
0.77663
1,003,039
// CheckStyle: stop header check // CheckStyle: stop line length check // GENERATED CONTENT - DO NOT EDIT // GENERATORS: org.graalvm.compiler.replacements.processor.ReplacementsAnnotationProcessor, org.graalvm.compiler.replacements.processor.PluginGenerator package org.graalvm.compiler.replacements.amd64; import jdk.vm.ci.meta.ResolvedJavaMethod; import java.lang.annotation.Annotation; import org.graalvm.compiler.nodes.ValueNode; import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext; import org.graalvm.compiler.nodes.graphbuilderconf.GeneratedInvocationPlugin; import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin; import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins; import org.graalvm.compiler.nodes.graphbuilderconf.NodeIntrinsicPluginFactory; import jdk.vm.ci.meta.JavaKind; public class PluginFactory_AMD64StringIndexOfNode implements NodeIntrinsicPluginFactory { // class: org.graalvm.compiler.replacements.amd64.AMD64StringIndexOfNode // method: optimizedStringIndexPointer(jdk.internal.vm.compiler.word.Pointer,int,jdk.internal.vm.compiler.word.Pointer,int) // generated-by: org.graalvm.compiler.replacements.processor.GeneratedNodeIntrinsicPlugin$ConstructorPlugin private static final class AMD64StringIndexOfNode_optimizedStringIndexPointer extends GeneratedInvocationPlugin { @Override public boolean execute(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode[] args) { ValueNode arg0 = args[0]; ValueNode arg1 = args[1]; ValueNode arg2 = args[2]; ValueNode arg3 = args[3]; org.graalvm.compiler.replacements.amd64.AMD64StringIndexOfNode node = new org.graalvm.compiler.replacements.amd64.AMD64StringIndexOfNode(arg0, arg1, arg2, arg3); b.addPush(JavaKind.Int, node); return true; } @Override public Class<? extends Annotation> getSource() { return org.graalvm.compiler.graph.Node.NodeIntrinsic.class; } } @Override public void registerPlugins(InvocationPlugins plugins, InjectionProvider injection) { plugins.register(new AMD64StringIndexOfNode_optimizedStringIndexPointer(), org.graalvm.compiler.replacements.amd64.AMD64StringIndexOfNode.class, "optimizedStringIndexPointer", jdk.internal.vm.compiler.word.Pointer.class, int.class, jdk.internal.vm.compiler.word.Pointer.class, int.class); } }
9244835c31f90cca22e31249b1b0697d0cb1f758
1,900
java
Java
src/java/org/jivesoftware/openfire/handler/IQSessionEstablishmentHandler.java
CMingTseng/OpenFire
f0db0f60492c5ca66faca0fa4c65b6b9afea6e35
[ "Apache-2.0" ]
2,496
2015-01-02T16:13:08.000Z
2022-03-31T08:05:23.000Z
src/java/org/jivesoftware/openfire/handler/IQSessionEstablishmentHandler.java
CMingTseng/OpenFire
f0db0f60492c5ca66faca0fa4c65b6b9afea6e35
[ "Apache-2.0" ]
993
2015-01-10T10:15:39.000Z
2022-03-31T08:33:30.000Z
src/java/org/jivesoftware/openfire/handler/IQSessionEstablishmentHandler.java
CMingTseng/OpenFire
f0db0f60492c5ca66faca0fa4c65b6b9afea6e35
[ "Apache-2.0" ]
1,539
2015-01-04T13:11:28.000Z
2022-03-31T07:35:27.000Z
34.545455
94
0.736316
1,003,040
/* * Copyright (C) 2005-2008 Jive Software. All rights reserved. * * 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.jivesoftware.openfire.handler; import org.jivesoftware.openfire.IQHandlerInfo; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.xmpp.packet.IQ; /** * Activate client sessions once resource binding has been done. Clients need to active their * sessions in order to engage in instant messaging and presence activities. The server may * deny sessions activations if the max number of sessions in the server has been reached or * if a user does not have permissions to create sessions.<p> * * Current implementation does not check any of the above conditions. However, future versions * may add support for those checkings. * * @author Gaston Dombiak */ public class IQSessionEstablishmentHandler extends IQHandler { private IQHandlerInfo info; public IQSessionEstablishmentHandler() { super("Session Establishment handler"); info = new IQHandlerInfo("session", "urn:ietf:params:xml:ns:xmpp-session"); } @Override public IQ handleIQ(IQ packet) throws UnauthorizedException { // Just answer that the session has been activated IQ reply = IQ.createResultIQ(packet); return reply; } @Override public IQHandlerInfo getInfo() { return info; } }
924483783c6448a17e0631e8b47323545223d3d2
2,700
java
Java
sample/src/main/java/com/facebook/samples/litho/stats/StatsSpec.java
jinjiankla/litho
3ea9a7a2ea083f28b1cdfe3f6c4bfe912d893e3d
[ "Apache-2.0" ]
1
2019-10-25T08:13:39.000Z
2019-10-25T08:13:39.000Z
sample/src/main/java/com/facebook/samples/litho/stats/StatsSpec.java
laonianren/litho
6f81097f51d2fb325add75e8d40bc8e9ae56230c
[ "Apache-2.0" ]
null
null
null
sample/src/main/java/com/facebook/samples/litho/stats/StatsSpec.java
laonianren/litho
6f81097f51d2fb325add75e8d40bc8e9ae56230c
[ "Apache-2.0" ]
null
null
null
36.986301
100
0.627037
1,003,041
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.samples.litho.stats; import android.graphics.Color; import android.graphics.Typeface; import com.facebook.litho.Column; import com.facebook.litho.Component; import com.facebook.litho.ComponentContext; import com.facebook.litho.annotations.LayoutSpec; import com.facebook.litho.annotations.OnCreateLayout; import com.facebook.litho.stats.LithoStats; import com.facebook.litho.widget.Text; import com.facebook.yoga.YogaEdge; @LayoutSpec public class StatsSpec { @OnCreateLayout static Component onCreateLayout(ComponentContext c) { return Column.create(c) .backgroundColor(Color.WHITE) .paddingDip(YogaEdge.ALL, 5f) .child(Text.create(c).textSizeSp(20).text("LITHO STATS").marginDip(YogaEdge.BOTTOM, 10f)) .child( Text.create(c) .textSizeSp(14) .textColor(Color.DKGRAY) .textStyle(Typeface.ITALIC) .typeface(Typeface.MONOSPACE) .text( "Total applied state updates: " + LithoStats.getAppliedStateUpdates())) .child( Text.create(c) .textSizeSp(14) .textColor(Color.DKGRAY) .textStyle(Typeface.ITALIC) .typeface(Typeface.MONOSPACE) .text("Total triggered *sync* state updates: " + LithoStats.getStateUpdatesSync())) .child( Text.create(c) .textSizeSp(14) .textColor(Color.DKGRAY) .textStyle(Typeface.ITALIC) .typeface(Typeface.MONOSPACE) .text( "Total triggered *async* state updates: " + LithoStats.getStateUpdatesAsync())) .child( Text.create(c) .textSizeSp(14) .textColor(Color.DKGRAY) .textStyle(Typeface.ITALIC) .typeface(Typeface.MONOSPACE) .text("Total triggered *lazy* state updates: " + LithoStats.getStateUpdatesLazy())) .build(); } }
92448392f60402abd1ab281b8faf489b54b89cce
1,024
java
Java
src/test/java/ru/stqa/pft/sandbox/PointTests.java
ssboyko/java_pft
4af32c9d13386f5dbb1b3b460edad758e4783a92
[ "Apache-2.0" ]
null
null
null
src/test/java/ru/stqa/pft/sandbox/PointTests.java
ssboyko/java_pft
4af32c9d13386f5dbb1b3b460edad758e4783a92
[ "Apache-2.0" ]
null
null
null
src/test/java/ru/stqa/pft/sandbox/PointTests.java
ssboyko/java_pft
4af32c9d13386f5dbb1b3b460edad758e4783a92
[ "Apache-2.0" ]
null
null
null
26.25641
64
0.633789
1,003,042
package ru.stqa.pft.sandbox; import org.testng.Assert; import org.testng.annotations.Test; import ru.stqa.pft.sandbox.Point; public class PointTests { @Test public void testDistanceFirstPointMoreThanSecond() { Point p1 = new Point(11.0, 10.0); Point p2 = new Point(3.0, 6.0); Assert.assertEquals(p1.distance(p2),8.94427190999916); } @Test public void testDistanceBothPointsAtSamePosition() { Point p1 = new Point(11.0, 10.0); Point p2 = new Point(11.0, 10.0); Assert.assertEquals(p1.distance(p2),0.0); } @Test public void testDistanceSecondPointMoreThanFirst() { Point p1 = new Point(10.0, 9.0); Point p2 = new Point(11.0, 10.0); Assert.assertEquals(p1.distance(p2),1.4142135623730951); } @Test public void testDistanceMinusCoordinates() { Point p1 = new Point(-10.0, -9.0); Point p2 = new Point(-11.0, -10.0); Assert.assertEquals(p1.distance(p2),1.4142135623730951); } }
9244844134bc240a272af40306349858ae7fab78
667
java
Java
TeamCode/src/main/java/prhs/robotics/autonomous/commands/SetFlippers.java
pr-robowolves/SkyStone
8ea0867409e7ff642a0ff35770e513715077ea98
[ "MIT" ]
1
2021-12-10T21:11:23.000Z
2021-12-10T21:11:23.000Z
TeamCode/src/main/java/prhs/robotics/autonomous/commands/SetFlippers.java
pr-robowolves/SkyStone
8ea0867409e7ff642a0ff35770e513715077ea98
[ "MIT" ]
null
null
null
TeamCode/src/main/java/prhs/robotics/autonomous/commands/SetFlippers.java
pr-robowolves/SkyStone
8ea0867409e7ff642a0ff35770e513715077ea98
[ "MIT" ]
null
null
null
21.516129
80
0.674663
1,003,043
package prhs.robotics.autonomous.commands; import java.util.Locale; import prhs.robotics.autonomous.Command; import prhs.robotics.autonomous.CommandContext; public class SetFlippers implements Command { private double pos; public SetFlippers(double pos) { this.pos = pos; } @Override public void run(CommandContext ctx) { ctx.flipper_pos = pos; } // TODO: maybe wait for position to be reached @Override public boolean poll(CommandContext _ctx) { return true; } @Override public String toString() { return String.format(Locale.ENGLISH, "Move flippers to %.2f", this.pos); } }
9244879bdbb055b12579955912a0c8c260eb7b6b
1,292
java
Java
src/main/java/chapter1/Task7.java
krzysztofpolek/giit.java.course
394c16172310e976e1a38f8d2c8ce62acd5372f2
[ "Unlicense" ]
null
null
null
src/main/java/chapter1/Task7.java
krzysztofpolek/giit.java.course
394c16172310e976e1a38f8d2c8ce62acd5372f2
[ "Unlicense" ]
null
null
null
src/main/java/chapter1/Task7.java
krzysztofpolek/giit.java.course
394c16172310e976e1a38f8d2c8ce62acd5372f2
[ "Unlicense" ]
null
null
null
39.151515
126
0.69582
1,003,044
package chapter1; import java.util.Scanner; public class Task7 { public static void main(String[] args) { // Napisz program, który wczytuje dwie liczby z zakresu od 0 do 65 535, zapisuje je // w zmiennych typu short, a następnie oblicza bez znaku ich sumę, różnicę, iloczyn, // iloraz i resztę z dzielenia bez konwertowania ich do typu int. Scanner scanner = new Scanner(System.in); System.out.print("Podaj pierwszą liczbę całkowitą z zakresu 0 - 65535: "); short numberFirst = (short) scanner.nextInt(); System.out.print("Podaj drugą liczbę całkowitą z zakresu 0 - 65535: "); short numberSecond = (short) scanner.nextInt(); System.out.println("Suma: " + (Short.toUnsignedLong(numberFirst) + Short.toUnsignedLong(numberSecond))); System.out.println("Różnica: " + (Short.toUnsignedLong(numberFirst) - Short.toUnsignedLong(numberSecond))); System.out.println("Iloczyn: " + (Short.toUnsignedLong(numberFirst) * Short.toUnsignedLong(numberSecond))); System.out.println("Iloraz: " + (Short.toUnsignedLong(numberFirst) / Short.toUnsignedLong(numberSecond))); System.out.println("Reszta z dzielenia: " + (Short.toUnsignedLong(numberFirst) % Short.toUnsignedLong(numberSecond))); } }
9244894d122590bde0c41861f91715403d46b87f
627
java
Java
java/test/cloud-contract-consumer-rest/src/main/java/com/github/freshchen/keeping/UserClient.java
freshchen/dev-tools
f1e564dd61a2c17ce992c436c9db7bde0e00bacc
[ "Apache-2.0" ]
2
2021-01-16T15:33:55.000Z
2021-12-22T15:15:01.000Z
java/test/cloud-contract-consumer-rest/src/main/java/com/github/freshchen/keeping/UserClient.java
freshchen/dev-tools
f1e564dd61a2c17ce992c436c9db7bde0e00bacc
[ "Apache-2.0" ]
1
2021-09-08T08:40:52.000Z
2021-09-08T08:40:52.000Z
java/test/cloud-contract-consumer-rest/src/main/java/com/github/freshchen/keeping/UserClient.java
freshchen/dev-tools
f1e564dd61a2c17ce992c436c9db7bde0e00bacc
[ "Apache-2.0" ]
1
2021-09-23T09:12:35.000Z
2021-09-23T09:12:35.000Z
27.26087
81
0.684211
1,003,045
package com.github.freshchen.keeping; import com.github.freshchen.keeping.model.JsonResult; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import java.io.IOException; /** * @author darcy * @since 2020/12/12 **/ public class UserClient { public static JsonResult createUser(User user) throws IOException { UserApi userApi = new Retrofit.Builder().baseUrl("http://127.0.0.1:8880") .addConverterFactory(GsonConverterFactory.create()) .build() .create(UserApi.class); return userApi.create(user).execute().body(); } }
924489bd0330ec287aa981b3a43caf34f86f0c69
2,641
java
Java
src/main/java/me/ajlane/neo4j/GraphLoadingTester.java
lanecodes/agrosuccess-sim
c9af27607f712751a603ac7ad21db284c8ac0009
[ "MIT" ]
null
null
null
src/main/java/me/ajlane/neo4j/GraphLoadingTester.java
lanecodes/agrosuccess-sim
c9af27607f712751a603ac7ad21db284c8ac0009
[ "MIT" ]
null
null
null
src/main/java/me/ajlane/neo4j/GraphLoadingTester.java
lanecodes/agrosuccess-sim
c9af27607f712751a603ac7ad21db284c8ac0009
[ "MIT" ]
null
null
null
27.8
96
0.668686
1,003,046
package me.ajlane.neo4j; import org.apache.log4j.Logger; import org.neo4j.graphdb.Result; import org.neo4j.graphdb.Transaction; import me.ajlane.neo4j.GraphLoaderFactory; import me.ajlane.neo4j.GraphLoaderType; /** Manual tests used to help understand how to use the Neo4j embedded * graph database. This logic should be moved into formal unit tests. * * @author andrew * */ public class GraphLoadingTester { final static Logger logger = Logger.getLogger(GraphLoadingTester.class); static String projectRoot = "/home/andrew/AgroSuccess/"; static String cypherRoot = projectRoot + "views"; static String fnameSuffix = "_w"; static String globalParamFile = projectRoot + "global_parameters.json"; public static GraphLoaderType constructGraphLoader() { GraphLoaderFactory factory = new GraphLoaderFactory(); GraphLoaderType graphLoader = factory.create(cypherRoot, fnameSuffix, globalParamFile); return graphLoader; } /** Prints out the queries provided by a GraphLoaderType without * putting them anywhere near a database. The check here is whether * or not the correct *number* of queries are coming out of the graph * loader. * */ private static void print(GraphLoaderType graphLoader) { Boolean moreQueries = true; int queryNo = 0; while (moreQueries) { String nextQuery = graphLoader.getNextQuery(); if (nextQuery == null) { logger.debug("Null query!"); //moreQueries = false; moreQueries = false; } else { logger.debug("Query No " + queryNo + ":\n" + nextQuery); queryNo++; } } } /** * Checks that, after loading real data into the embedded database, * the expected number of nodes are present. * * @param graph */ private static void testQueryOnData(EmbeddedGraphInstance graph) { try ( Transaction tx = graph.beginTx() ) { String query = "MATCH (n:LandCoverType {model_ID:\"AgroSuccess-dev\"}) RETURN n;"; Result res = graph.execute(query); while (res.hasNext()) { logger.debug(res.next()); } tx.success(); } } public static void main(String[] args) { boolean printLoadedQueries = false; boolean loadData = false; EmbeddedGraphInstance graph = new EmbeddedGraphInstance("output/databases/agrosuccess.db"); if (loadData) { graph.insertExternalCypher(cypherRoot, fnameSuffix, globalParamFile); } if (printLoadedQueries) { print(constructGraphLoader()); } testQueryOnData(graph); graph.shutdown(); } }
92448ab5bbc32a64f7850cc93f58aa30fd2d45b0
4,189
java
Java
platform/vcs-log/impl/src/com/intellij/vcs/log/visible/filters/VcsLogBranchFilterImpl.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
platform/vcs-log/impl/src/com/intellij/vcs/log/visible/filters/VcsLogBranchFilterImpl.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
null
null
null
platform/vcs-log/impl/src/com/intellij/vcs/log/visible/filters/VcsLogBranchFilterImpl.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-10-15T05:56:42.000Z
2020-10-15T05:56:42.000Z
35.201681
140
0.686321
1,003,047
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.visible.filters; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcs.log.VcsLogBranchFilter; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; class VcsLogBranchFilterImpl implements VcsLogBranchFilter { @NotNull private final List<String> myBranches; @NotNull private final List<Pattern> myPatterns; @NotNull private final List<String> myExcludedBranches; @NotNull private final List<Pattern> myExcludedPatterns; VcsLogBranchFilterImpl(@NotNull List<String> branches, @NotNull List<Pattern> patterns, @NotNull List<String> excludedBranches, @NotNull List<Pattern> excludedPatterns) { myBranches = branches; myPatterns = patterns; myExcludedBranches = excludedBranches; myExcludedPatterns = excludedPatterns; } @NotNull @Override public Collection<String> getTextPresentation() { List<String> result = new ArrayList<>(); result.addAll(myBranches); result.addAll(ContainerUtil.map(myPatterns, pattern -> pattern.pattern())); result.addAll(ContainerUtil.map(myExcludedBranches, branchName -> "-" + branchName)); result.addAll(ContainerUtil.map(myExcludedPatterns, pattern -> "-" + pattern.pattern())); return result; } @Override public boolean isEmpty() { return myBranches.isEmpty() && myPatterns.isEmpty() && myExcludedBranches.isEmpty() && myExcludedPatterns.isEmpty(); } @Override @NonNls public String toString() { String result = ""; if (!myPatterns.isEmpty()) { result += "on patterns: " + StringUtil.join(myPatterns, ", "); } if (!myBranches.isEmpty()) { if (!result.isEmpty()) result += "; "; result += "on branches: " + StringUtil.join(myBranches, ", "); } if (!myExcludedPatterns.isEmpty()) { if (result.isEmpty()) result += "; "; result += "not on patterns: " + StringUtil.join(myExcludedPatterns, ", "); } if (!myExcludedBranches.isEmpty()) { if (result.isEmpty()) result += "; "; result += "not on branches: " + StringUtil.join(myExcludedBranches, ", "); } return result; } @Override public boolean matches(@NotNull String name) { return isIncluded(name) && !isExcluded(name); } private boolean isIncluded(@NotNull String name) { if (myPatterns.isEmpty() && myBranches.isEmpty()) return true; return isMatched(name, myBranches, myPatterns); } private boolean isExcluded(@NotNull String name) { return isMatched(name, myExcludedBranches, myExcludedPatterns); } private static boolean isMatched(@NotNull String name, @NotNull List<String> branches, @NotNull List<Pattern> patterns) { if (branches.contains(name)) return true; for (Pattern regexp : patterns) { if (regexp.matcher(name).matches()) return true; } return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VcsLogBranchFilterImpl filter = (VcsLogBranchFilterImpl)o; return Comparing.haveEqualElements(myBranches, filter.myBranches) && Comparing.haveEqualElements(myPatterns, filter.myPatterns) && Comparing.haveEqualElements(myExcludedBranches, filter.myExcludedBranches) && Comparing.haveEqualElements(myExcludedPatterns, filter.myExcludedPatterns); } @Override public int hashCode() { return Objects.hash(Comparing.unorderedHashcode(myBranches), Comparing.unorderedHashcode(myPatterns), Comparing.unorderedHashcode(myExcludedBranches), Comparing.unorderedHashcode(myExcludedPatterns)); } }
92448b3ad815e438ff798d05b6ab5bfc9943d62b
417
java
Java
src/main/java/com/bytegriffin/datatunnel/core/Worker.java
mustang2247/DataTunnel
5eace3001798482d207def96e9d87be2eb1ad91a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/bytegriffin/datatunnel/core/Worker.java
mustang2247/DataTunnel
5eace3001798482d207def96e9d87be2eb1ad91a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/bytegriffin/datatunnel/core/Worker.java
mustang2247/DataTunnel
5eace3001798482d207def96e9d87be2eb1ad91a
[ "Apache-2.0" ]
null
null
null
18.954545
68
0.645084
1,003,048
package com.bytegriffin.datatunnel.core; public class Worker implements Runnable { private HandlerContext next; private Param msg; private Handler handler; public Worker(Handler handler, HandlerContext next, Param msg) { this.handler = handler; this.next = next; this.msg = msg; } @Override public void run() { handler.channelRead(next, msg); } }
92448b61af892360a6a239ed25baf23f7700db39
15,879
java
Java
Components/LearningCore/Source/gov/sandia/cognition/statistics/distribution/UniformIntegerDistribution.java
Markoy8/Foundry
c3ec00a8efe08a25dd5eae7150b788e4486c0e6e
[ "BSD-3-Clause" ]
122
2015-01-19T17:36:40.000Z
2022-02-25T20:22:22.000Z
Components/LearningCore/Source/gov/sandia/cognition/statistics/distribution/UniformIntegerDistribution.java
Markoy8/Foundry
c3ec00a8efe08a25dd5eae7150b788e4486c0e6e
[ "BSD-3-Clause" ]
45
2015-01-23T06:28:33.000Z
2021-05-18T19:11:29.000Z
Components/LearningCore/Source/gov/sandia/cognition/statistics/distribution/UniformIntegerDistribution.java
Markoy8/Foundry
c3ec00a8efe08a25dd5eae7150b788e4486c0e6e
[ "BSD-3-Clause" ]
42
2015-01-20T03:07:17.000Z
2021-08-18T08:51:55.000Z
28.818512
87
0.573777
1,003,049
/* * File: UniformIntegerDistribution.java * Authors: Justin Basilico * Project: Cognitive Foundry * * Copyright 2015 Cognitive Foundry. All rights reserved. */ package gov.sandia.cognition.statistics.distribution; import gov.sandia.cognition.annotation.PublicationReference; import gov.sandia.cognition.annotation.PublicationType; import gov.sandia.cognition.collection.IntegerSpan; import gov.sandia.cognition.math.LogMath; import gov.sandia.cognition.math.MathUtil; import gov.sandia.cognition.math.UnivariateStatisticsUtil; import gov.sandia.cognition.math.matrix.Vector; import gov.sandia.cognition.math.matrix.VectorFactory; import gov.sandia.cognition.statistics.AbstractClosedFormIntegerDistribution; import gov.sandia.cognition.statistics.ClosedFormCumulativeDistributionFunction; import gov.sandia.cognition.statistics.ClosedFormDiscreteUnivariateDistribution; import gov.sandia.cognition.statistics.DistributionEstimator; import gov.sandia.cognition.statistics.EstimableDistribution; import gov.sandia.cognition.statistics.ProbabilityMassFunction; import gov.sandia.cognition.util.AbstractCloneableSerializable; import gov.sandia.cognition.util.Pair; import java.util.Collection; import java.util.Random; import java.util.Set; /** * Contains the (very simple) definition of a continuous Uniform distribution, * parameterized between the minimum and maximum bounds. The uniform * distribution has equal mass on all of the integers between the two bounds, * and including them. For example, if the bounds were (10, 14) then the values * 10, 11, 12, 13, and 14 would all have probability 1/5 of being sampled. * * @author Justin Basilico * @since 3.4.3 */ @PublicationReference( author="Wikipedia", title="Uniform distribution (discrete)", type=PublicationType.WebPage, year=2015, url="https://en.wikipedia.org/wiki/Uniform_distribution_(discrete)" ) public class UniformIntegerDistribution extends AbstractClosedFormIntegerDistribution implements ClosedFormDiscreteUnivariateDistribution<Number>, EstimableDistribution<Number, UniformIntegerDistribution> { /** The default minimum support is {@value}. */ public static final int DEFAULT_MIN_SUPPORT = 0; /** The default maximum support is {@value}. */ public static final int DEFAULT_MAX_SUPPORT = 0; /** The minimum bound on the distribution (inclusive). */ private int minSupport; /** The maximum bound on the distribution (inclusive). */ private int maxSupport; /** * Creates a new {@link UniformIntegerDistribution} with default parameters. */ public UniformIntegerDistribution() { this(DEFAULT_MIN_SUPPORT, DEFAULT_MAX_SUPPORT); } /** * Creates a new {@link UniformIntegerDistribution} with the given bounds. * * @param minSupport * The minimum bound on the distribution (inclusive). * @param maxSupport * The maximum bound on the distribution (exclusive). */ public UniformIntegerDistribution( final int minSupport, final int maxSupport) { super(); this.setMinSupport(minSupport); this.setMaxSupport(maxSupport); } /** * Creates a new {@link UniformIntegerDistribution} that is a copy of the * given other distribution. * * @param other * The distribution to copy. */ public UniformIntegerDistribution( final UniformIntegerDistribution other) { this(other.getMinSupport(), other.getMaxSupport()); } @Override public UniformIntegerDistribution clone() { return (UniformIntegerDistribution) super.clone(); } @Override public UniformIntegerDistribution.PMF getProbabilityFunction() { return new UniformIntegerDistribution.PMF(this); } @Override public UniformIntegerDistribution.CDF getCDF() { return new UniformIntegerDistribution.CDF(this); } @Override public Number getMean() { return this.getMeanAsDouble(); } @Override public Vector convertToVector() { return VectorFactory.getDenseDefault().copyValues( this.getMinSupport(), this.getMaxSupport()); } @Override public void convertFromVector( final Vector parameters) { parameters.assertDimensionalityEquals(2); final int a = (int) parameters.getElement(0); final int b = (int) parameters.getElement(1); this.setMinSupport(Math.min(a, b)); this.setMaxSupport(Math.max(a, b)); } @Override public Integer getMinSupport() { return this.minSupport; } /** * Sets the minimum support. It is the smallest value in the uniform * distribution, and is inclusive. It should be less than (or equal to) * the maximum support. * * @param minSupport * The minimum support. */ public void setMinSupport( final int minSupport) { this.minSupport = minSupport; } @Override public Integer getMaxSupport() { return this.maxSupport; } /** * Sets the maximum support. It is the largest value in the uniform * distribution, and is inclusive. It should be greater than (or equal to) * the minimum support. * * @param maxSupport * The maximum support. */ public void setMaxSupport( final int maxSupport) { this.maxSupport = maxSupport; } @Override public double getMeanAsDouble() { return (this.maxSupport + this.minSupport) / 2.0; } @Override public double getVariance() { final double difference = this.maxSupport - this.minSupport + 1; return (difference * difference - 1) / 12.0; } @Override public Set<? extends Number> getDomain() { return new IntegerSpan(this.minSupport, this.maxSupport); } @Override public int getDomainSize() { return (this.maxSupport - this.minSupport + 1); } @Override public int sampleAsInt( final Random random) { return this.minSupport + random.nextInt(this.maxSupport - this.minSupport + 1); } @Override public void sampleInto( final Random random, final int sampleCount, final Collection<? super Number> output) { for (int i = 0; i < sampleCount; i++) { output.add(this.sampleAsInt(random)); } } @Override public UniformIntegerDistribution.MaximumLikelihoodEstimator getEstimator() { return new MaximumLikelihoodEstimator(); } /** * Probability mass function of a discrete uniform distribution. */ public static class PMF extends UniformIntegerDistribution implements ProbabilityMassFunction<Number> { /** * Creates a new {@link UniformIntegerDistribution.PMF} with min and * max 0. */ public PMF() { super(); } /** * Creates a new {@link UniformIntegerDistribution.PMF} with the given * min and max. * * @param minSupport * The minimum support. Should be less-than-or-equal to the max * support. * @param maxSupport * The maximum support. Should be greater-than-or-equal to the min * support. */ public PMF( final int minSupport, final int maxSupport) { super(minSupport, maxSupport); } /** * Creates a new {@link UniformIntegerDistribution.PMF} as a copy * of the given other uniform distribution. * * @param other * The other distribution. */ public PMF( final UniformIntegerDistribution other) { super(other); } @Override public double getEntropy() { return MathUtil.log2(this.getDomainSize()); } @Override public double logEvaluate( final Number input) { return logEvaluate(input.intValue(), this.getMinSupport(), this.getMaxSupport()); } @Override public Double evaluate( final Number input) { return this.evaluateAsDouble(input.intValue()); } /** * Evaluates the input value for the PMF to compute its mass as a * double. * * @param input * The input value. * @return * The probability mass for the input value. */ public double evaluateAsDouble( final int input) { return evaluate(input, this.getMinSupport(), this.getMaxSupport()); } /** * Evaluates the probability mass function of the discrete uniform * distribution. The mass is a uniform value if the input is between * the supports (inclusive) and 0 if it is not. * * @param input * The input value. * @param minSupport * The minimum support. Should be less-than-or-equal to the max * support. * @param maxSupport * The maximum support. Should be greater-than-or-equal to the min * support. * @return * The probability mass value for the input. */ public static double evaluate( final int input, final int minSupport, final int maxSupport) { if (input < minSupport || input > maxSupport) { // Outside the support range. return 0.0; } else { // Uniform within support range. return 1.0 / (maxSupport - minSupport + 1); } } /** * Evaluates the log of the probability mass function of the discrete * uniform distribution. The mass is a uniform value if the input is * between the supports (inclusive) and 0 if it is not. * * @param input * The input value. * @param minSupport * The minimum support. Should be less-than-or-equal to the max * support. * @param maxSupport * The maximum support. Should be greater-than-or-equal to the min * support. * @return * The log of the probability mass value for the input. */ public static double logEvaluate( final int input, final int minSupport, final int maxSupport) { if (input < minSupport || input > maxSupport) { return LogMath.LOG_0; } else { return -Math.log(maxSupport - minSupport + 1); } } @Override public PMF getProbabilityFunction() { return this; } } /** * Implements the cumulative distribution function for the discrete * uniform distribution. */ public static class CDF extends UniformIntegerDistribution implements ClosedFormCumulativeDistributionFunction<Number> { /** * Creates a new {@link UniformIntegerDistribution.PMF} with min and * max 0. */ public CDF() { super(); } /** * Creates a new {@link UniformIntegerDistribution.CDF} with the given * min and max. * * @param minSupport * The minimum support. Should be less-than-or-equal to the max * support. * @param maxSupport * The maximum support. Should be greater-than-or-equal to the min * support. */ public CDF( final int minSupport, final int maxSupport) { super(minSupport, maxSupport); } /** * Creates a new {@link UniformIntegerDistribution.CDF} as a copy * of the given other uniform distribution. * * @param other * The other distribution. */ public CDF( final UniformIntegerDistribution other) { super(other); } @Override public Double evaluate( final Number input) { return this.evaluateAsDouble(input.intValue()); } /** * Evaluates the cumulative distribution function for the input. * * @param input * The input value. * @return * The cumulative distribution value at the input. */ public double evaluateAsDouble( final int input) { return evaluate(input, this.getMinSupport(), this.getMaxSupport()); } /** * Evaluates the cumulative density function of the discrete uniform * distribution. * * @param input * The input value. * @param minSupport * The minimum support. Should be less-than-or-equal to the max * support. * @param maxSupport * The maximum support. Should be greater-than-or-equal to the min * support. * @return * The cumulative density value for the input. */ public static double evaluate( final int input, final int minSupport, final int maxSupport) { final double p; if (input < minSupport) { // Before the support range. p = 0.0; } else if (input > maxSupport) { // After the support range. p = 1.0; } else { // Within the support range. p = (input - minSupport + 1.0) / (maxSupport - minSupport + 1.0); } return p; } @Override public UniformIntegerDistribution.CDF getCDF() { return this; } } /** * Implements a maximum likelihood estimator for the discrete uniform * distribution. */ @PublicationReference( author="Wikipedia", title="German tank problem", type=PublicationType.WebPage, year=2010, url="http://en.wikipedia.org/wiki/German_tank_problem" ) public static class MaximumLikelihoodEstimator extends AbstractCloneableSerializable implements DistributionEstimator<Number, UniformIntegerDistribution> { /** * Creates a new {@link UniformIntegerDistribution.MaximumLikelihoodEstimator}. */ public MaximumLikelihoodEstimator() { super(); } @Override public UniformIntegerDistribution.PMF learn( final Collection<? extends Number> data) { final Pair<Double,Double> result = UnivariateStatisticsUtil.computeMinAndMax(data); final int min = result.getFirst().intValue(); final int max = result.getSecond().intValue(); return new UniformIntegerDistribution.PMF(min, max); } } }
92448bf4390bdf53345d99e3fda27c8a0fa0c718
4,767
java
Java
kits/src/main/java/cn/ymex/kits/widget/CountDownTextView.java
ymex/cute
ce16c9e55e4d148d05dcc9a9c465c506ca898ebc
[ "Apache-2.0" ]
3
2017-11-12T11:30:05.000Z
2019-12-17T03:26:19.000Z
kits/src/main/java/cn/ymex/kits/widget/CountDownTextView.java
ymex/kits
ce16c9e55e4d148d05dcc9a9c465c506ca898ebc
[ "Apache-2.0" ]
null
null
null
kits/src/main/java/cn/ymex/kits/widget/CountDownTextView.java
ymex/kits
ce16c9e55e4d148d05dcc9a9c465c506ca898ebc
[ "Apache-2.0" ]
null
null
null
24.95288
101
0.579941
1,003,050
/* * Copyright (c) 2015. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. * * Email:[email protected] (www.ymex.cn) * @author ymex */ package cn.ymex.kits.widget; import android.content.Context; import android.os.CountDownTimer; import android.util.AttributeSet; /** * 文本计时器控件 */ public class CountDownTextView extends android.support.v7.widget.AppCompatTextView { private CountDownTimer mTimer; private final static int DEFAULT_TAG = -0x11; private boolean countDownIng = false; private boolean stopNormal = true; public CountDownTextView(Context context) { super(context); initView(context); } public CountDownTextView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public CountDownTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context); } private void initView(Context context) { } /** * 设置时间 * * @param time 单位:毫秒 */ public synchronized void setTimer(long time) { setTimer(time, 1000, DEFAULT_TAG); } /** * @param time * @param tag */ public synchronized void setTimer(final long time, final long countDownInterval, final int tag) { if (mTimer != null) { mTimer.cancel(); } countDownIng = true; stopNormal = true; mTimer = new CountDownTimer(time, countDownInterval) { @Override public void onTick(long millisUntilFinished) { if (timeFormat != null) { setText(timeFormat.formtDownTime(millisUntilFinished)); } else { setText(formtDownTime(millisUntilFinished / 1000));//默认格式方法 } } @Override public void onFinish() { countDownIng = false; if (onTickStopListener != null) { onTickStopListener.onTickStop(tag, null, stopNormal); } } }; mTimer.start(); } public boolean isCountDownIng() { return countDownIng; } /** * 销毁计时器 */ public void destroyTimer() { countDownIng = false; setOnTickStopListener(null); if (mTimer != null) { mTimer.cancel(); } } /** * 主动停止计时 */ public void stopCountDown() { if (mTimer != null) { countDownIng = false; stopNormal = false; mTimer.cancel(); mTimer.onFinish(); } } /** * 返回时间格式 * * @param day * @param hour * @param minute * @param second * @return */ private String formtDownTime(int day, int hour, int minute, int second) { char spilt = ':'; StringBuilder builder = new StringBuilder(); builder.append(fillZero(day)).append(spilt); builder.append(fillZero(hour)).append(spilt); builder.append(fillZero(minute)).append(spilt); builder.append(fillZero(second)); return builder.toString(); } private String formtDownTime(long time) { int second = (int) (time % 60); int minute = (int) (time % 3600 / 60); int hour = (int) (time / 3600 % 24); int day = (int) (time / 3600 / 24); return formtDownTime(day, hour, minute, second); } /** * 数字填充 0 * * @param num * @return */ private String fillZero(long num) { if (num < 10) { return "0" + num; } return String.valueOf(num); } private OnTickStopListener onTickStopListener; public void setOnTickStopListener(OnTickStopListener onTickStopListener) { this.onTickStopListener = onTickStopListener; } public interface OnTickStopListener { /** * 计时停止回调 * * @param itag * @param otag * @param normalStop */ void onTickStop(int itag, Object otag, boolean normalStop); } public CountDownTimer getTimer() { return mTimer; } private TimeFormat timeFormat; public void setTimeFormat(TimeFormat timeFormat) { this.timeFormat = timeFormat; } /** * 时间格式化接口 */ public interface TimeFormat { String formtDownTime(long time); } }
92448c3b48b261cd61c4db41722f248fdac88507
2,193
java
Java
xmpbox/src/test/java/net/padaf/xmpbox/parser/PropMappingTest.java
gbm-bailleul/padaf
525407ea9f7ae917475461e06aeae76e8c367b55
[ "BSD-3-Clause" ]
9
2015-11-05T12:43:07.000Z
2021-06-09T16:19:38.000Z
xmpbox/src/test/java/net/padaf/xmpbox/parser/PropMappingTest.java
gbm-bailleul/padaf
525407ea9f7ae917475461e06aeae76e8c367b55
[ "BSD-3-Clause" ]
1
2015-06-14T08:46:37.000Z
2015-10-26T08:10:50.000Z
xmpbox/src/test/java/net/padaf/xmpbox/parser/PropMappingTest.java
gbm-bailleul/padaf
525407ea9f7ae917475461e06aeae76e8c367b55
[ "BSD-3-Clause" ]
1
2016-05-08T17:40:40.000Z
2016-05-08T17:40:40.000Z
30.887324
85
0.686275
1,003,051
/******************************************************************************* * Copyright 2010 Atos Worldline SAS * * Licensed by Atos Worldline SAS under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Atos Worldline SAS 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 net.padaf.xmpbox.parser; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; public class PropMappingTest { protected PropMapping propMap; protected String nsURI = "http://www.test.org/PropMap#"; @Before public void init() { propMap = new PropMapping(nsURI); } @Test public void testURI() { Assert.assertEquals(nsURI, propMap.getConcernedNamespace()); } @Test public void testPropMapAdding() { String name = "propName"; String type = "PropType"; propMap.addNewProperty(name, type, null); Assert.assertEquals(1, propMap.getPropertiesName().size()); Assert.assertEquals(name, propMap.getPropertiesName().get(0)); Assert.assertNull(propMap.getPropertyAttributes(name)); Assert.assertEquals(type, propMap.getPropertyType(name)); } @Test public void testPropMapAttr() { String name = "propName"; String type = "PropType"; List<String> attr = new ArrayList<String>(); String att1 = "attr1"; String att2 = "attr2"; attr.add(att1); attr.add(att2); propMap.addNewProperty(name, type, attr); Assert.assertEquals(attr, propMap.getPropertyAttributes(name)); } }
92448e723a106df95d34f7b20596d62a4f8359cb
974
java
Java
geode-core/src/main/java/org/apache/geode/management/BackupStatus.java
Kris-10-0/geode
7ccdc8297b1ded06175f41543884d945d5995c60
[ "Apache-2.0" ]
1,475
2016-12-06T06:10:53.000Z
2022-03-30T09:55:23.000Z
geode-core/src/main/java/org/apache/geode/management/BackupStatus.java
Kris-10-0/geode
7ccdc8297b1ded06175f41543884d945d5995c60
[ "Apache-2.0" ]
2,809
2016-12-06T19:24:26.000Z
2022-03-31T22:02:20.000Z
geode-core/src/main/java/org/apache/geode/management/BackupStatus.java
Kris-10-0/geode
7ccdc8297b1ded06175f41543884d945d5995c60
[ "Apache-2.0" ]
531
2016-12-06T05:48:47.000Z
2022-03-31T23:06:37.000Z
40.583333
100
0.761807
1,003,052
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management; /** * The status of a backup operation. * * @since Geode 1.4 */ public interface BackupStatus extends org.apache.geode.admin.BackupStatus { }
92448f3bd882e6801b2d24cb249449147b916484
918
java
Java
terasoluna-batch/src/test/java/jp/terasoluna/fw/batch/executor/B000004BLogic.java
terasoluna-batch/terasoluna-batch
e0bd4a05ab9f2f98ed053c6b316064a354e9a35b
[ "Apache-2.0" ]
15
2015-06-11T02:22:08.000Z
2020-09-08T05:12:14.000Z
terasoluna-batch/src/test/java/jp/terasoluna/fw/batch/executor/B000004BLogic.java
terasoluna-batch/terasoluna-batch
e0bd4a05ab9f2f98ed053c6b316064a354e9a35b
[ "Apache-2.0" ]
3
2016-08-31T02:25:57.000Z
2020-04-18T08:51:05.000Z
terasoluna-batch/src/test/java/jp/terasoluna/fw/batch/executor/B000004BLogic.java
terasoluna-batch/terasoluna-batch
e0bd4a05ab9f2f98ed053c6b316064a354e9a35b
[ "Apache-2.0" ]
11
2016-02-26T02:01:09.000Z
2021-07-19T02:33:11.000Z
26.228571
75
0.71024
1,003,053
/* * Copyright (c) 2011 NTT DATA Corporation * * 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 jp.terasoluna.fw.batch.executor; import jp.terasoluna.fw.batch.blogic.BLogic; import jp.terasoluna.fw.batch.blogic.vo.BLogicParam; /** * */ public class B000004BLogic implements BLogic { /** * {@inheritDoc} */ public int execute(BLogicParam param) { return 0; } }
9244903f926caf1b52ee4d65c129a171c04b8930
64,949
java
Java
plugins/memory/src/main/java/greycat/memory/OffHeapENode.java
bluezio/greycat
6b5b427a7cae8a39f97d6ff95a87ff6a32b006a2
[ "Apache-2.0" ]
106
2017-02-03T11:45:22.000Z
2022-03-24T01:00:23.000Z
plugins/memory/src/main/java/greycat/memory/OffHeapENode.java
bluezio/greycat
6b5b427a7cae8a39f97d6ff95a87ff6a32b006a2
[ "Apache-2.0" ]
78
2017-02-10T17:38:17.000Z
2022-02-09T01:00:08.000Z
plugins/memory/src/main/java/greycat/memory/OffHeapENode.java
bluezio/greycat
6b5b427a7cae8a39f97d6ff95a87ff6a32b006a2
[ "Apache-2.0" ]
38
2017-02-10T11:02:38.000Z
2022-02-11T00:34:49.000Z
45.578246
171
0.450985
1,003,054
/** * Copyright 2017-2019 The GreyCat Authors. All rights reserved. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 greycat.memory; import greycat.Constants; import greycat.Container; import greycat.Graph; import greycat.Type; import greycat.internal.CoreConstants; import greycat.memory.primary.POffHeapDoubleArray; import greycat.memory.primary.POffHeapIntArray; import greycat.memory.primary.POffHeapLongArray; import greycat.memory.primary.POffHeapString; import greycat.plugin.NodeStateCallback; import greycat.plugin.Resolver; import greycat.struct.*; import greycat.utility.Base64; import java.util.HashSet; import java.util.Set; public class OffHeapENode implements ENode, OffHeapContainer { private static final byte LOAD_WAITING_ALLOC = 0; private static final byte LOAD_WAITING_TYPE = 1; private static final byte LOAD_WAITING_KEY = 2; private static final byte LOAD_WAITING_VALUE = 3; private static final int DIRTY = 0; private static final int SIZE = 1; private static final int CAPACITY = 2; private static final int SUBHASH = 3; private static final int OFFSET = 4; private static final int ELEM_SIZE = 3; final long index; private final OffHeapEGraph _eGraph; private final Graph graph; OffHeapENode(final long p_index, OffHeapEGraph eGraph, Graph graph) { index = p_index; this._eGraph = eGraph; this.graph = graph; } private long allocate(final long addr, final long newCapacity) { if (addr == OffHeapConstants.NULL_PTR) { //nothing before, initial allocation... final long new_addr = POffHeapLongArray.allocate(OFFSET + (newCapacity * ELEM_SIZE)); POffHeapLongArray.set(new_addr, CAPACITY, newCapacity); POffHeapLongArray.set(new_addr, DIRTY, 0); POffHeapLongArray.set(new_addr, SIZE, 0); if (newCapacity > Constants.MAP_INITIAL_CAPACITY) { POffHeapLongArray.set(new_addr, SUBHASH, POffHeapLongArray.allocate(newCapacity * 3)); } else { POffHeapLongArray.set(new_addr, SUBHASH, OffHeapConstants.NULL_PTR); } _eGraph.setAddrByIndex(index, new_addr); return new_addr; } else { //reallocation or overallocation long previousCapacity = POffHeapLongArray.get(addr, CAPACITY); if (previousCapacity < newCapacity) { // long graphAddr = _eGraph.getAddr(); final long new_addr = POffHeapLongArray.reallocate(addr, OFFSET + (newCapacity * ELEM_SIZE)); POffHeapLongArray.set(new_addr, CAPACITY, newCapacity); long subHash_ptr = POffHeapLongArray.get(new_addr, SUBHASH); if (subHash_ptr == OffHeapConstants.NULL_PTR) { subHash_ptr = POffHeapLongArray.allocate(newCapacity * 3); } else { subHash_ptr = POffHeapLongArray.reallocate(subHash_ptr, newCapacity * 3); POffHeapLongArray.reset(subHash_ptr, newCapacity * 3); } POffHeapLongArray.set(new_addr, SUBHASH, subHash_ptr); //reHash final long size = POffHeapLongArray.get(new_addr, SIZE); final long hash_capacity = newCapacity * 2; for (long i = 0; i < size; i++) { long keyHash = key(new_addr, i) % hash_capacity; if (keyHash < 0) { keyHash = keyHash * -1; } setNext(subHash_ptr, i, hash(subHash_ptr, newCapacity, keyHash)); setHash(subHash_ptr, newCapacity, keyHash, i); } _eGraph.setAddrByIndex(index, new_addr); return new_addr; } else { return addr; } } } @Override public void declareDirty() { long addr = _eGraph.addrByIndex(index); long dirty = POffHeapLongArray.get(addr, DIRTY); if (dirty == 0) { POffHeapLongArray.set(addr, DIRTY, 1); _eGraph.declareDirty(); } } private static long value(final long addr, final long index) { return POffHeapLongArray.get(addr, OFFSET + (index * ELEM_SIZE) + 2); } private static void setValue(final long addr, final long index, final long insertValue) { POffHeapLongArray.set(addr, OFFSET + (index * ELEM_SIZE) + 2, insertValue); } private static long key(final long addr, final long index) { return POffHeapLongArray.get(addr, OFFSET + (index * ELEM_SIZE)); } private static void setKey(final long addr, final long index, final long insertKey) { POffHeapLongArray.set(addr, OFFSET + (index * ELEM_SIZE), insertKey); } private static long next(final long hashAddr, final long index) { return POffHeapLongArray.get(hashAddr, index); } private static void setNext(final long hashAddr, final long index, final long insertNext) { POffHeapLongArray.set(hashAddr, index, insertNext); } private static long hash(final long hashAddr, final long capacity, final long index) { return POffHeapLongArray.get(hashAddr, capacity + index); } private static void setHash(final long hashAddr, final long capacity, final long index, final long insertHash) { POffHeapLongArray.set(hashAddr, capacity + index, insertHash); } private static byte type(final long addr, final long index) { return (byte) POffHeapLongArray.get(addr, OFFSET + (index * ELEM_SIZE) + 1); } private static void setType(final long addr, final long index, final long insertType) { POffHeapLongArray.set(addr, OFFSET + (index * ELEM_SIZE) + 1, insertType); } private static double doubleValue(final long addr, final long index) { return POffHeapDoubleArray.get(addr, OFFSET + (index * ELEM_SIZE) + 2); } private static void setDoubleValue(final long addr, final long index, final double insertValue) { POffHeapDoubleArray.set(addr, OFFSET + (index * ELEM_SIZE) + 2, insertValue); } @Override public ENode set(String name, byte type, Object value) { internal_set(graph.resolver().stringToHash(name, true), type, value, true, false); return this; } @SuppressWarnings("Duplicates") private long internal_set(final long p_key, final byte p_type, final Object p_unsafe_elem, boolean replaceIfPresent, boolean initial) { long addr = _eGraph.addrByIndex(index); if (addr == OffHeapConstants.NULL_PTR) { addr = allocate(addr, Constants.MAP_INITIAL_CAPACITY); } long entry = -1; long prev_entry = -1; long hashIndex = -1; long size = POffHeapLongArray.get(addr, SIZE); long capacity = POffHeapLongArray.get(addr, CAPACITY); long subhash_ptr = POffHeapLongArray.get(addr, SUBHASH); if (subhash_ptr == OffHeapConstants.NULL_PTR) { for (int i = 0; i < size; i++) { if (key(addr, i) == p_key) { entry = i; break; } } } else { hashIndex = p_key % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } long m = hash(subhash_ptr, capacity, hashIndex); while (m != -1) { if (key(addr, m) == p_key) { entry = m; break; } prev_entry = m; m = next(subhash_ptr, m); } } //case already present if (entry != -1) { final byte found_type = type(addr, entry); if (replaceIfPresent || (p_type != found_type)) { if (p_unsafe_elem == null) { /* Case: suppression of a value */ //freeThePreviousValue freeElement(value(addr, entry), found_type); //then clean the acces chain if (subhash_ptr != OffHeapConstants.NULL_PTR) { //unHash previous if (prev_entry != -1) { setNext(subhash_ptr, prev_entry, next(subhash_ptr, entry)); } else { setHash(subhash_ptr, capacity, hashIndex, -1); } } long indexVictim = size - 1; //just pop the last value if (entry == indexVictim) { setKey(addr, entry, OffHeapConstants.NULL_PTR); setValue(addr, entry, OffHeapConstants.NULL_PTR); setType(addr, entry, (byte) OffHeapConstants.NULL_PTR); } else { //we need to reHash the new last element at our place setKey(addr, entry, key(addr, indexVictim)); final byte typeOfVictim = type(addr, indexVictim); if (typeOfVictim == Type.DOUBLE) { final double victimDoubleValue = doubleValue(addr, indexVictim); setDoubleValue(addr, entry, victimDoubleValue); } else { setValue(addr, entry, value(addr, indexVictim)); } setType(addr, entry, typeOfVictim); if (subhash_ptr != OffHeapConstants.NULL_PTR) { setNext(addr, entry, next(subhash_ptr, indexVictim)); long victimHash = key(addr, entry) % (capacity * 2); if (victimHash < 0) { victimHash = victimHash * -1; } long m = hash(subhash_ptr, capacity, victimHash); if (m == indexVictim) { //the victim was the head of hashing list setHash(subhash_ptr, capacity, victimHash, entry); } else { //the victim is in the next, rechain it while (m != -1) { if (next(addr, m) == indexVictim) { setNext(subhash_ptr, m, entry); break; } m = next(subhash_ptr, m); } } } setKey(addr, indexVictim, OffHeapConstants.NULL_PTR); freeElement(value(addr, indexVictim), type(addr, indexVictim)); setValue(addr, indexVictim, OffHeapConstants.NULL_PTR); setType(addr, indexVictim, OffHeapConstants.NULL_PTR); } POffHeapLongArray.set(addr, SIZE, size - 1); } else { final long previous_value = value(addr, entry); //freeThePreviousValue if (p_type == Type.DOUBLE) { setDoubleValue(addr, entry, toDoubleValue(p_unsafe_elem)); } else { setValue(addr, entry, toAddr(p_type, p_unsafe_elem)); } freeElement(previous_value, found_type); if (found_type != p_type) { setType(addr, entry, p_type); } } } if (!initial) { declareDirty(); } } if (size >= capacity) { long newCapacity = capacity * 2; addr = allocate(addr, newCapacity); subhash_ptr = POffHeapLongArray.get(addr, SUBHASH); capacity = newCapacity; hashIndex = p_key % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } } final long insert_index = size; setKey(addr, insert_index, p_key); if (p_type == Type.DOUBLE) { setDoubleValue(addr, insert_index, toDoubleValue(p_unsafe_elem)); } else { setValue(addr, insert_index, toAddr(p_type, p_unsafe_elem)); } setType(addr, insert_index, p_type); if (subhash_ptr != OffHeapConstants.NULL_PTR) { setNext(subhash_ptr, insert_index, hash(subhash_ptr, capacity, hashIndex)); setHash(subhash_ptr, capacity, hashIndex, insert_index); } size++; POffHeapLongArray.set(addr, SIZE, size); if (!initial) { declareDirty(); } return insert_index; } @SuppressWarnings("Duplicates") private long toAddr(final byte p_type, final Object p_unsafe_elem) { long param_elem = -1; if (p_unsafe_elem != null) { try { switch (p_type) { case Type.BOOL: param_elem = ((boolean) p_unsafe_elem) ? 1 : 0; break; case Type.LONG: if (p_unsafe_elem instanceof Long) { param_elem = (long) p_unsafe_elem; } else if (p_unsafe_elem instanceof Double) { param_elem = (long) (double) p_unsafe_elem; } else if (p_unsafe_elem instanceof Float) { param_elem = (long) (float) p_unsafe_elem; } else if (p_unsafe_elem instanceof Integer) { param_elem = (long) (int) p_unsafe_elem; } else if (p_unsafe_elem instanceof Byte) { param_elem = (long) (byte) p_unsafe_elem; } else { param_elem = (long) p_unsafe_elem; } break; case Type.INT: if (p_unsafe_elem instanceof Integer) { param_elem = (int) p_unsafe_elem; } else if (p_unsafe_elem instanceof Double) { param_elem = (int) (double) p_unsafe_elem; } else if (p_unsafe_elem instanceof Float) { param_elem = (int) (float) p_unsafe_elem; } else if (p_unsafe_elem instanceof Long) { param_elem = (int) (long) p_unsafe_elem; } else if (p_unsafe_elem instanceof Byte) { param_elem = (int) (byte) p_unsafe_elem; } else { param_elem = (int) p_unsafe_elem; } break; case Type.STRING: param_elem = POffHeapString.fromObject((String) p_unsafe_elem); break; case Type.DOUBLE_ARRAY: param_elem = POffHeapDoubleArray.fromObject((double[]) p_unsafe_elem); break; case Type.LONG_ARRAY: param_elem = POffHeapLongArray.fromObject((long[]) p_unsafe_elem); break; case Type.INT_ARRAY: param_elem = POffHeapIntArray.fromObject((int[]) p_unsafe_elem); break; case Type.ENODE: param_elem = ((OffHeapENode) p_unsafe_elem).index; break; case Type.ERELATION: OffHeapERelation eRelation = ((OffHeapERelation) p_unsafe_elem); param_elem = addrByIndex(eRelation.index()); break; case Type.RELATION: case Type.DMATRIX: case Type.LMATRIX: case Type.STRING_TO_INT_MAP: case Type.LONG_TO_LONG_MAP: case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: //throw new RuntimeException("mwDB usage error, set method called with type " + Type.typeName(p_type) + ", is getOrCreate method instead"); param_elem = OffHeapConstants.NULL_PTR; //empty initial ptr break; default: throw new RuntimeException("Internal Exception, unknown type"); } } catch (Exception e) { throw new RuntimeException("mwDB usage error, set method called with type " + Type.typeName(p_type) + " while param object is " + p_unsafe_elem); } } return param_elem; } @Override public ENode setAt(int key, byte type, Object value) { internal_set(key, type, value, true, false); return this; } @Override public Object get(String name) { return internal_get(graph.resolver().stringToHash(name, false)); } @Override public byte type(String name) { return typeAt(graph.resolver().stringToHash(name, false)); } @Override public final byte typeAt(int key) { long addr = _eGraph.addrByIndex(index); long typeIndex = internal_find(key); return type(addr, typeIndex); } @Override public Container remove(String name) { return removeAt(graph.resolver().stringToHash(name, false)); } @Override public Container removeAt(int index) { internal_set(index, Type.INT, null, true, false); return this; } private Object internal_get(long p_key) { long addr = _eGraph.addrByIndex(index); //TODO check why allocation here? if (addr == OffHeapConstants.NULL_PTR) { addr = allocate(addr, Constants.MAP_INITIAL_CAPACITY); } long size = POffHeapLongArray.get(addr, SIZE); //empty chunk, we return immediately if (size == 0) { return null; } long index = internal_find(p_key); if (index != -1) { int type = type(addr, index); long rawValue = value(addr, index); switch (type) { case Type.BOOL: return rawValue == 1; case Type.DOUBLE: return doubleValue(addr, index); case Type.LONG: return rawValue; case Type.INT: return (int) rawValue; case Type.STRING: return POffHeapString.asObject(rawValue); case Type.DOUBLE_ARRAY: return POffHeapDoubleArray.asObject(rawValue); case Type.LONG_ARRAY: return POffHeapLongArray.asObject(rawValue); case Type.INT_ARRAY: return POffHeapIntArray.asObject(rawValue); case Type.RELATION: return new OffHeapRelation(this, index); case Type.ERELATION: return new OffHeapERelation(this, index, _eGraph, graph); case Type.ENODE: return new OffHeapENode(rawValue, _eGraph, graph); case Type.DMATRIX: return new OffHeapDMatrix(this, index); case Type.LMATRIX: return new OffHeapLMatrix(this, index); case Type.STRING_TO_INT_MAP: return new OffHeapStringIntMap(this, index); case Type.LONG_TO_LONG_MAP: return new OffHeapLongLongMap(this, index); case Type.LONG_TO_LONG_ARRAY_MAP: return new OffHeapLongLongArrayMap(this, index); case Type.RELATION_INDEXED: return new OffHeapRelationIndexed(this, index, graph); case OffHeapConstants.NULL_PTR: return null; default: throw new RuntimeException("Should never happen " + type); } } return null; } @SuppressWarnings("Duplicates") private long internal_find(long p_key) { long addr = _eGraph.addrByIndex(index); if(addr == OffHeapConstants.NULL_PTR){ return OffHeapConstants.NULL_PTR; } final long size = POffHeapLongArray.get(addr, SIZE); final long subhash_ptr = POffHeapLongArray.get(addr, SUBHASH); if (size == 0) { return -1; } else if (subhash_ptr == OffHeapConstants.NULL_PTR) { for (int i = 0; i < size; i++) { if (key(addr, i) == p_key) { return i; } } return -1; } else { final long capacity = POffHeapLongArray.get(addr, CAPACITY); long hashIndex = p_key % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } long m = hash(subhash_ptr, capacity, hashIndex); while (m >= 0) { if (p_key == key(addr, m)) { return m; } else { m = next(subhash_ptr, m); } } return -1; } } @Override public Object getAt(int key) { return internal_get(key); } @Override public Object getRawAt(int key) { return internal_get(key); } @Override public Object getTypedRawAt(int p_key, byte type) { long addr = _eGraph.addrByIndex(index); long found = internal_find(p_key); if(found == OffHeapConstants.NULL_PTR){ return null; } if(type(addr, found) != type){ return null; } return internal_get(p_key); } @Override public <A> A getWithDefault(String key, A defaultValue) { final Object result = get(key); if (result == null) { return defaultValue; } else { return (A) result; } } @Override public <A> A getAtWithDefault(int key, A defaultValue) { final Object result = getAt(key); if (result == null) { return defaultValue; } else { return (A) result; } } @Override public final Container rephase() { return this; } @Override public Object getOrCreate(String key, byte type) { Object previous = get(key); if (previous != null) { return previous; } else { return getOrCreateAt(_eGraph.graph().resolver().stringToHash(key, true), type); } } @Override public Object getOrCreateAt(int key, byte type) { long addr = _eGraph.addrByIndex(index); long index = POffHeapLongArray.get(addr, SIZE); long found = internal_find(key); if (found != -1) { Object elem = internal_get(key); if (elem != null) { return elem; } } Object toSet = null; switch (type) { case Type.ERELATION: toSet = new OffHeapERelation(this, index, _eGraph, graph); break; case Type.RELATION: toSet = new OffHeapRelation(this, index); break; case Type.RELATION_INDEXED: toSet = new OffHeapRelationIndexed(this, index, graph); break; case Type.DMATRIX: toSet = new OffHeapDMatrix(this, index); break; case Type.LMATRIX: toSet = new OffHeapLMatrix(this, index); break; case Type.STRING_TO_INT_MAP: toSet = new OffHeapStringIntMap(this, index); break; case Type.LONG_TO_LONG_MAP: toSet = new OffHeapLongLongMap(this, index); break; case Type.LONG_TO_LONG_ARRAY_MAP: toSet = new OffHeapLongLongArrayMap(this, index); break; } internal_set(key, type, toSet, true, false); return toSet; } @Override public void drop() { _eGraph.drop(this); } @Override public EGraph egraph() { return _eGraph; } @Override public void each(NodeStateCallback callBack) { long addr = _eGraph.addrByIndex(index); long size = POffHeapLongArray.get(addr, SIZE); for (long i = 0; i < size; i++) { if (value(addr, i) != OffHeapConstants.NULL_PTR) { long key = key(addr, i); byte type = type(addr, i); Object elem = internal_get(key); callBack.on((int) key, type, elem); } } } @Override public ENode clear() { long addr = _eGraph.addrByIndex(index); long subhash = POffHeapLongArray.get(addr, SUBHASH); long size = POffHeapLongArray.get(addr, SIZE); POffHeapLongArray.set(addr, CAPACITY, 0); POffHeapLongArray.set(addr, SIZE, 0); POffHeapLongArray.set(addr, SUBHASH, OffHeapConstants.NULL_PTR); for (long i = 0; i < size; i++) { freeElement(value(addr, i), type(addr, i)); setKey(addr, i, OffHeapConstants.NULL_PTR); setValue(addr, i, OffHeapConstants.NULL_PTR); setType(addr, i, OffHeapConstants.NULL_PTR); } if (subhash != OffHeapConstants.NULL_PTR) { POffHeapLongArray.free(subhash); POffHeapLongArray.set(addr, SUBHASH, OffHeapConstants.NULL_PTR); } POffHeapLongArray.free(addr); return this; } @SuppressWarnings("Duplicates") private double toDoubleValue(final Object p_unsafe_elem) { if (p_unsafe_elem instanceof Double) { return (double) p_unsafe_elem; } else if (p_unsafe_elem instanceof Integer) { return (double) (int) p_unsafe_elem; } else if (p_unsafe_elem instanceof Float) { return (double) (float) p_unsafe_elem; } else if (p_unsafe_elem instanceof Long) { return (double) (long) p_unsafe_elem; } else if (p_unsafe_elem instanceof Byte) { return (double) (byte) p_unsafe_elem; } return (double) p_unsafe_elem; } /* static void rebase(long addr, long eGraphAddr) { long size = POffHeapLongArray.get(addr, SIZE); for (int i = 0; i < size; i++) { int type = type(addr, i); switch (type) { case Type.ERELATION: final long previousERel_ptr = value(addr, i); OffHeapERelation.rebase(previousERel_ptr, eGraphAddr); break; case Type.ENODE: final long previousENode_ptr = value(addr, i); final long previousENodeId = OffHeapENode.getId(previousENode_ptr); setValue(addr, i, OffHeapEGraph.nodeAddrAt(eGraphAddr, previousENodeId)); break; } } }*/ @SuppressWarnings("Duplicates") static void free(long addr) { if (addr != OffHeapConstants.NULL_PTR) { final long subhash_ptr = POffHeapLongArray.get(addr, SUBHASH); final long size = POffHeapLongArray.get(addr, SIZE); for (long i = 0; i < size; i++) { long value = value(addr, i); byte type = type(addr, i); if (value != OffHeapConstants.NULL_PTR) { freeElement(value, type); } } if (subhash_ptr != OffHeapConstants.NULL_PTR) { POffHeapLongArray.free(subhash_ptr); } POffHeapLongArray.free(addr); } } @SuppressWarnings("Duplicates") private static void freeElement(final long addr, final byte elemType) { switch (elemType) { case Type.BOOL: case Type.LONG: case Type.INT: case Type.DOUBLE: break; case Type.STRING: POffHeapString.free(addr); break; case Type.DOUBLE_ARRAY: POffHeapDoubleArray.freeObject(addr); break; case Type.RELATION: OffHeapRelation.free(addr); case Type.ERELATION: OffHeapERelation.free(addr); break; case Type.DMATRIX: OffHeapDMatrix.free(addr); break; case Type.LMATRIX: OffHeapLMatrix.free(addr); break; case Type.LONG_ARRAY: POffHeapLongArray.freeObject(addr); break; case Type.INT_ARRAY: POffHeapIntArray.freeObject(addr); break; case Type.STRING_TO_INT_MAP: OffHeapStringIntMap.free(addr); break; case Type.LONG_TO_LONG_MAP: OffHeapLongLongMap.free(addr); break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: OffHeapLongLongArrayMap.free(addr); break; } } @Override public String toString() { final long addr = _eGraph.addrByIndex(index); final StringBuilder builder = new StringBuilder(); final boolean[] isFirst = {true}; boolean isFirstField = true; long size = POffHeapLongArray.get(addr, SIZE); builder.append("{"); for (int i = 0; i < size; i++) { final long elem = value(addr, i); final Resolver resolver = graph.resolver(); final long attributeKey = key(addr, i); final byte elemType = type(addr, i); if (elem != OffHeapConstants.NULL_PTR) { if (isFirstField) { isFirstField = false; } else { builder.append(","); } String resolveName = resolver.hashToString((int) attributeKey); if (resolveName == null) { resolveName = attributeKey + ""; } switch (elemType) { case Type.BOOL: { builder.append("\""); builder.append(resolveName); builder.append("\":"); if (elem == 1) { builder.append("1"); } else { builder.append("0"); } break; } case Type.STRING: { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append("\""); builder.append(POffHeapString.asObject(elem)); builder.append("\""); break; } case Type.LONG: { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append(elem); break; } case Type.INT: { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append(elem); break; } case Type.DOUBLE: { if (!Constants.isNaN((double) elem)) { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append(elem); } break; } case Type.DOUBLE_ARRAY: { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append("["); double[] castedArr = POffHeapDoubleArray.asObject(elem); for (int j = 0; j < castedArr.length; j++) { if (j != 0) { builder.append(","); } builder.append(castedArr[j]); } builder.append("]"); break; } case Type.RELATION: builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append("["); OffHeapRelation castedRelArr = new OffHeapRelation(this, i); for (int j = 0; j < castedRelArr.size(); j++) { if (j != 0) { builder.append(","); } builder.append(castedRelArr.get(j)); } builder.append("]"); break; case Type.ERELATION: builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append("["); OffHeapERelation castedERel = new OffHeapERelation(this, i, _eGraph, graph); for (int j = 0; j < castedERel.size(); j++) { if (j != 0) { builder.append(","); } long eRelAddr = addrByIndex(castedERel.index()); long nodeIndex = OffHeapERelation.nodeIndexAt(eRelAddr, j); builder.append(nodeIndex); } builder.append("]"); break; case Type.LONG_ARRAY: { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append("["); long[] castedArr2 = POffHeapLongArray.asObject(elem); for (int j = 0; j < castedArr2.length; j++) { if (j != 0) { builder.append(","); } builder.append(castedArr2[j]); } builder.append("]"); break; } case Type.INT_ARRAY: { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append("["); int[] castedArr3 = POffHeapIntArray.asObject(elem); for (int j = 0; j < castedArr3.length; j++) { if (j != 0) { builder.append(","); } builder.append(castedArr3[j]); } builder.append("]"); break; } case Type.LONG_TO_LONG_MAP: { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append("{"); OffHeapLongLongMap castedMapL2L = new OffHeapLongLongMap(this, i); isFirst[0] = true; castedMapL2L.each(new LongLongMapCallBack() { @Override public void on(long key, long value) { if (!isFirst[0]) { builder.append(","); } else { isFirst[0] = false; } builder.append("\""); builder.append(key); builder.append("\":"); builder.append(value); } }); builder.append("}"); break; } case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append("{"); OffHeapLongLongArrayMap castedMapL2LA = new OffHeapLongLongArrayMap(this, i); isFirst[0] = true; Set<Long> keys = new HashSet<Long>(); castedMapL2LA.each(new LongLongArrayMapCallBack() { @Override public void on(long key, long value) { keys.add(key); } }); final Long[] flatKeys = keys.toArray(new Long[keys.size()]); for (int k = 0; k < flatKeys.length; k++) { long[] values = castedMapL2LA.get(flatKeys[k]); if (!isFirst[0]) { builder.append(","); } else { isFirst[0] = false; } builder.append("\""); builder.append(flatKeys[k]); builder.append("\":["); for (int j = 0; j < values.length; j++) { if (j != 0) { builder.append(","); } builder.append(values[j]); } builder.append("]"); } builder.append("}"); break; } case Type.STRING_TO_INT_MAP: { builder.append("\""); builder.append(resolveName); builder.append("\":"); builder.append("{"); OffHeapStringIntMap castedMapS2L = new OffHeapStringIntMap(this, i); isFirst[0] = true; castedMapS2L.each(new StringLongMapCallBack() { @Override public void on(String key, long value) { if (!isFirst[0]) { builder.append(","); } else { isFirst[0] = false; } builder.append("\""); builder.append(key); builder.append("\":"); builder.append(value); } }); builder.append("}"); break; } } } } builder.append("}"); return builder.toString(); } @SuppressWarnings("Duplicates") final void save(final Buffer buffer) { final long addr = _eGraph.addrByIndex(index); int size = (int) POffHeapLongArray.get(addr, SIZE); Base64.encodeIntToBuffer(size, buffer); for (int i = 0; i < size; i++) { if (value(addr, i) != OffHeapConstants.NULL_PTR) { //there is a real value final long loopValue = value(addr, i); if (loopValue != OffHeapConstants.NULL_PTR) { buffer.write(CoreConstants.CHUNK_ESEP); Base64.encodeIntToBuffer(type(addr, i), buffer); buffer.write(CoreConstants.CHUNK_ESEP); Base64.encodeLongToBuffer(key(addr, i), buffer); buffer.write(CoreConstants.CHUNK_ESEP); switch (type(addr, i)) { //additional types for embedded case Type.ENODE: Base64.encodeIntToBuffer((int) loopValue, buffer); break; case Type.ERELATION: OffHeapERelation castedLongArrERel = new OffHeapERelation(this, i, _eGraph, graph); Base64.encodeIntToBuffer(castedLongArrERel.size(), buffer); for (int j = 0; j < castedLongArrERel.size(); j++) { buffer.write(CoreConstants.CHUNK_VAL_SEP); int nodeIndex = (int) OffHeapERelation.nodeIndexAt(loopValue, j); Base64.encodeIntToBuffer(nodeIndex, buffer); } break; //common types case Type.STRING: POffHeapString.save(loopValue, buffer); break; case Type.BOOL: if (loopValue == 1) { Base64.encodeIntToBuffer(CoreConstants.BOOL_TRUE, buffer); } else { Base64.encodeIntToBuffer(CoreConstants.BOOL_FALSE, buffer); } break; case Type.LONG: Base64.encodeLongToBuffer(loopValue, buffer); break; case Type.DOUBLE: Base64.encodeDoubleToBuffer(doubleValue(addr, i), buffer); break; case Type.INT: Base64.encodeIntToBuffer((int) loopValue, buffer); break; case Type.DOUBLE_ARRAY: POffHeapDoubleArray.save(loopValue, buffer); break; case Type.RELATION: OffHeapRelation.save(loopValue, buffer); break; case Type.LONG_ARRAY: POffHeapLongArray.save(loopValue, buffer); break; case Type.INT_ARRAY: POffHeapIntArray.save(loopValue, buffer); break; case Type.DMATRIX: OffHeapDMatrix.save(loopValue, buffer); break; case Type.LMATRIX: OffHeapLMatrix.save(loopValue, buffer); break; case Type.STRING_TO_INT_MAP: OffHeapStringIntMap.save(loopValue, buffer); break; case Type.LONG_TO_LONG_MAP: OffHeapLongLongMap.save(loopValue, buffer); break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: OffHeapLongLongArrayMap.save(loopValue, buffer); break; default: break; } } } } POffHeapLongArray.set(addr, DIRTY, 0); } @SuppressWarnings("Duplicates") public final long load(final Buffer buffer, final long currentCursor) { long addr = _eGraph.addrByIndex(index); final boolean initial = addr == OffHeapConstants.NULL_PTR; final long payloadSize = buffer.length(); long cursor = currentCursor; long previous = cursor; byte state = LOAD_WAITING_ALLOC; byte read_type = -1; long read_key = -1; while (cursor < payloadSize) { byte current = buffer.read(cursor); if (current == Constants.CHUNK_ENODE_SEP || current == Constants.CHUNK_SEP) { break; } else if (current == Constants.CHUNK_ESEP) { switch (state) { case LOAD_WAITING_ALLOC: addr = allocate(OffHeapConstants.NULL_PTR, Base64.decodeToLongWithBounds(buffer, previous, cursor)); state = LOAD_WAITING_TYPE; cursor++; previous = cursor; break; case LOAD_WAITING_TYPE: read_type = (byte) Base64.decodeToIntWithBounds(buffer, previous, cursor); state = LOAD_WAITING_KEY; cursor++; previous = cursor; break; case LOAD_WAITING_KEY: read_key = Base64.decodeToLongWithBounds(buffer, previous, cursor); //primitive default loader switch (read_type) { //primitive types case Type.BOOL: case Type.INT: case Type.DOUBLE: case Type.LONG: case Type.STRING: case Type.ENODE: state = LOAD_WAITING_VALUE; cursor++; previous = cursor; break; //arrays case Type.DOUBLE_ARRAY: double[] doubleArrayLoaded = null; int doubleArrayIndex = 0; cursor++; previous = cursor; current = buffer.read(cursor); while (cursor < payloadSize && current != Constants.CHUNK_SEP && current != Constants.CHUNK_ENODE_SEP && current != Constants.CHUNK_ESEP) { if (current == Constants.CHUNK_VAL_SEP) { if (doubleArrayLoaded == null) { doubleArrayLoaded = new double[(int) Base64.decodeToLongWithBounds(buffer, previous, cursor)]; } else { doubleArrayLoaded[doubleArrayIndex] = Base64.decodeToDoubleWithBounds(buffer, previous, cursor); doubleArrayIndex++; } previous = cursor + 1; } cursor++; if (cursor < payloadSize) { current = buffer.read(cursor); } } if (doubleArrayLoaded == null) { doubleArrayLoaded = new double[(int) Base64.decodeToLongWithBounds(buffer, previous, cursor)]; } else { doubleArrayLoaded[doubleArrayIndex] = Base64.decodeToDoubleWithBounds(buffer, previous, cursor); } internal_set(read_key, read_type, doubleArrayLoaded, true, initial); if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } break; case Type.LONG_ARRAY: long[] longArrayLoaded = null; int longArrayIndex = 0; cursor++; previous = cursor; current = buffer.read(cursor); while (cursor < payloadSize && current != Constants.CHUNK_SEP && current != Constants.CHUNK_ENODE_SEP && current != Constants.CHUNK_ESEP) { if (current == Constants.CHUNK_VAL_SEP) { if (longArrayLoaded == null) { longArrayLoaded = new long[(int) Base64.decodeToLongWithBounds(buffer, previous, cursor)]; } else { longArrayLoaded[longArrayIndex] = Base64.decodeToLongWithBounds(buffer, previous, cursor); longArrayIndex++; } previous = cursor + 1; } cursor++; if (cursor < payloadSize) { current = buffer.read(cursor); } } if (longArrayLoaded == null) { longArrayLoaded = new long[(int) Base64.decodeToLongWithBounds(buffer, previous, cursor)]; } else { longArrayLoaded[longArrayIndex] = Base64.decodeToLongWithBounds(buffer, previous, cursor); } internal_set(read_key, read_type, longArrayLoaded, true, initial); if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } break; case Type.INT_ARRAY: int[] intArrayLoaded = null; int intArrayIndex = 0; cursor++; previous = cursor; current = buffer.read(cursor); while (cursor < payloadSize && current != Constants.CHUNK_SEP && current != Constants.CHUNK_ENODE_SEP && current != Constants.CHUNK_ESEP) { if (current == Constants.CHUNK_VAL_SEP) { if (intArrayLoaded == null) { intArrayLoaded = new int[(int) Base64.decodeToLongWithBounds(buffer, previous, cursor)]; } else { intArrayLoaded[intArrayIndex] = Base64.decodeToIntWithBounds(buffer, previous, cursor); intArrayIndex++; } previous = cursor + 1; } cursor++; if (cursor < payloadSize) { current = buffer.read(cursor); } } if (intArrayLoaded == null) { intArrayLoaded = new int[(int) Base64.decodeToLongWithBounds(buffer, previous, cursor)]; } else { intArrayLoaded[intArrayIndex] = Base64.decodeToIntWithBounds(buffer, previous, cursor); } internal_set(read_key, read_type, intArrayLoaded, true, initial); if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } break; case Type.RELATION: OffHeapRelation relation = new OffHeapRelation(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = relation.load(buffer, cursor, payloadSize); cursor++; previous = cursor; state = LOAD_WAITING_TYPE; break; case Type.DMATRIX: OffHeapDMatrix matrix = new OffHeapDMatrix(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = matrix.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.LMATRIX: OffHeapLMatrix lmatrix = new OffHeapLMatrix(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = lmatrix.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.LONG_TO_LONG_MAP: OffHeapLongLongMap l2lmap = new OffHeapLongLongMap(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = l2lmap.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.LONG_TO_LONG_ARRAY_MAP: OffHeapLongLongArrayMap l2lrmap = new OffHeapLongLongArrayMap(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = l2lrmap.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.RELATION_INDEXED: OffHeapRelationIndexed relationIndexed = new OffHeapRelationIndexed(this, internal_set(read_key, read_type, null, true, initial), graph); cursor++; cursor = relationIndexed.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.STRING_TO_INT_MAP: OffHeapStringIntMap s2lmap = new OffHeapStringIntMap(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = s2lmap.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.ERELATION: OffHeapERelation eRelation = null; cursor++; previous = cursor; current = buffer.read(cursor); while (cursor < payloadSize && current != Constants.CHUNK_SEP && current != Constants.CHUNK_ENODE_SEP && current != Constants.CHUNK_ESEP) { if (current == Constants.CHUNK_VAL_SEP) { if (eRelation == null) { eRelation = new OffHeapERelation(this, internal_set(read_key, read_type, null, true, initial), _eGraph, graph); eRelation.allocate(Base64.decodeToIntWithBounds(buffer, previous, cursor)); } else { //TODO optimize eRelation.add(_eGraph.nodeByIndex((int) Base64.decodeToLongWithBounds(buffer, previous, cursor), true)); } previous = cursor + 1; } cursor++; if (cursor < payloadSize) { current = buffer.read(cursor); } } if (eRelation == null) { eRelation = new OffHeapERelation(this, internal_set(read_key, read_type, null, true, initial), _eGraph, graph); eRelation.allocate(Base64.decodeToIntWithBounds(buffer, previous, cursor)); } else { //TODO optimize eRelation.add(_eGraph.nodeByIndex(Base64.decodeToIntWithBounds(buffer, previous, cursor), true)); } if (current == Constants.CHUNK_ESEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } break; default: throw new RuntimeException("Not implemented yet!!!"); } break; case LOAD_WAITING_VALUE: load_primitive(read_key, read_type, buffer, previous, cursor, initial); state = LOAD_WAITING_TYPE; cursor++; previous = cursor; break; } } else { cursor++; } } if (state == LOAD_WAITING_VALUE) { load_primitive(read_key, read_type, buffer, previous, cursor, initial); } return cursor; } @SuppressWarnings("Duplicates") private void load_primitive(final long read_key, final byte read_type, final Buffer buffer, final long previous, final long cursor, final boolean initial) { switch (read_type) { case Type.BOOL: internal_set(read_key, read_type, (((byte) Base64.decodeToIntWithBounds(buffer, previous, cursor)) == CoreConstants.BOOL_TRUE), true, initial); break; case Type.INT: internal_set(read_key, read_type, Base64.decodeToIntWithBounds(buffer, previous, cursor), true, initial); break; case Type.DOUBLE: internal_set(read_key, read_type, Base64.decodeToDoubleWithBounds(buffer, previous, cursor), true, initial); break; case Type.LONG: internal_set(read_key, read_type, Base64.decodeToLongWithBounds(buffer, previous, cursor), true, initial); break; case Type.STRING: internal_set(read_key, read_type, Base64.decodeToStringWithBounds(buffer, previous, cursor), true, initial); break; case Type.ENODE: final OffHeapENode eNode = _eGraph.nodeByIndex(Base64.decodeToIntWithBounds(buffer, previous, cursor), true); internal_set(read_key, read_type, eNode, true, initial); break; } } @Override public long addrByIndex(long elemIndex) { return value(_eGraph.addrByIndex(index), elemIndex); } @Override public void setAddrByIndex(long elemIndex, long newAddr) { setValue(_eGraph.addrByIndex(index), elemIndex, newAddr); } @Override public void lock() { // no locking for OffHeapENode } @Override public void unlock() { // no locking for OffHeapENode } static long cloneENode(final long previousAddr) { //TODO return -1; } }
9244907783617502a13eaa789b914c3396e752e0
2,734
java
Java
TopicosI/app/src/main/java/dominando/android/topicosi/MainActivity.java
luciano/studying_android
c4ed2f5257d8de5fb4209346c4ba4dd6dbb6f733
[ "MIT" ]
null
null
null
TopicosI/app/src/main/java/dominando/android/topicosi/MainActivity.java
luciano/studying_android
c4ed2f5257d8de5fb4209346c4ba4dd6dbb6f733
[ "MIT" ]
null
null
null
TopicosI/app/src/main/java/dominando/android/topicosi/MainActivity.java
luciano/studying_android
c4ed2f5257d8de5fb4209346c4ba4dd6dbb6f733
[ "MIT" ]
null
null
null
36.945946
89
0.680322
1,003,055
package dominando.android.topicosi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ScrollView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private EditText etPrecoUnitario; private EditText etCustoFixo; private EditText etCustoVariavel; private TextView tvResultado; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); View layout = LayoutInflater.from(this).inflate(R.layout.activity_main, null); etPrecoUnitario = (EditText) layout.findViewById(R.id.precoVariavel); etCustoFixo = (EditText) layout.findViewById(R.id.custoFixo); etCustoVariavel = (EditText) layout.findViewById(R.id.custoVariavel); tvResultado = (TextView) layout.findViewById(R.id.resultado); ScrollView mScrollView = new ScrollView(this); mScrollView.addView(layout); setContentView(mScrollView); } public void onCalcular(View view) { double precoUnitario = Double.parseDouble(etPrecoUnitario.getText().toString()); double custoFixo = Double.parseDouble(etCustoFixo.getText().toString()); double custoVariavel = Double.parseDouble(etCustoVariavel.getText().toString()); StringBuilder builder = new StringBuilder(); double margemContribuicao = (precoUnitario - custoVariavel); double quantidadeEquilibrio = custoFixo / margemContribuicao; double receitaTotal = precoUnitario * quantidadeEquilibrio; double custoTotal = custoFixo + (custoVariavel * quantidadeEquilibrio); builder.append("Quantidade Equilibrio: " + quantidadeEquilibrio); builder.append("\n\n"); builder.append("Margem de Contribuição: " + margemContribuicao); builder.append("\n\n"); builder.append("Receita Total: " + receitaTotal); builder.append("\n\n"); builder.append("Custo Total: " + custoTotal); builder.append("\n\n"); builder.append("\n\nAdicionando um na Quantidade:\n\n"); ++quantidadeEquilibrio; receitaTotal = precoUnitario * quantidadeEquilibrio; custoTotal = custoFixo + (custoVariavel * quantidadeEquilibrio); builder.append("Receita Total: " + receitaTotal); builder.append("\n\n"); builder.append("Custo Total: " + custoTotal); builder.append("\n\n"); tvResultado.setText(builder.toString()); } }
9244909c6212e09032a699547c75d91ef540ae45
3,209
java
Java
java/episim-persist/src/main/java/nl/rivm/cib/episim/persist/dimension/CbsSpaceDimensionDao.java
krevelen/rivm-vacsim
73b7910ecba030b4e1d5870a2f550f71941e5a76
[ "Apache-2.0" ]
1
2019-02-28T11:06:52.000Z
2019-02-28T11:06:52.000Z
java/episim-persist/src/main/java/nl/rivm/cib/episim/persist/dimension/CbsSpaceDimensionDao.java
krevelen/rivm-vacsim
73b7910ecba030b4e1d5870a2f550f71941e5a76
[ "Apache-2.0" ]
2
2020-05-15T20:28:35.000Z
2021-01-20T22:33:23.000Z
java/episim-persist/src/main/java/nl/rivm/cib/episim/persist/dimension/CbsSpaceDimensionDao.java
krevelen/rivm-vacsim
73b7910ecba030b4e1d5870a2f550f71941e5a76
[ "Apache-2.0" ]
1
2016-06-07T11:49:19.000Z
2016-06-07T11:49:19.000Z
32.744898
77
0.751948
1,003,056
package nl.rivm.cib.episim.persist.dimension; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.coala.bind.BindableDao; import io.coala.bind.LocalBinder; import nl.rivm.cib.episim.model.locate.Place; import nl.rivm.cib.episim.persist.AbstractDao; import nl.rivm.cib.episim.persist.dao.PlaceDao; import nl.rivm.cib.episim.persist.dao.RegionDao; /** * {@link CbsSpaceDimensionDao} is a data access object for the location * dimension * * @version $Id: 9244909c6212e09032a699547c75d91ef540ae45 $ * @author Rick van Krevelen */ @JsonIgnoreProperties( { "hibernateLazyInitializer", "handler" } ) @Entity @Table( name = "DIM_SPACE" ) public class CbsSpaceDimensionDao extends AbstractDao implements BindableDao<Place, CbsSpaceDimensionDao> { @Id @GeneratedValue @Column( name = "ID" ) protected long id; @Embedded protected PlaceDao place; @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) @JoinColumn( name = "WIJK", updatable = false ) protected RegionDao wijk; // code vs pc6 @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) @JoinColumn( name = "BRT", updatable = false ) protected RegionDao buurt; // code vs pc4 @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) @JoinColumn( name = "GEM", updatable = false ) protected RegionDao gemeente; @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) @JoinColumn( name = "COROP", updatable = false ) protected RegionDao corop; @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) @JoinColumn( name = "GGD", updatable = false ) protected RegionDao ggd; @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) @JoinColumn( name = "PROV", updatable = false ) protected RegionDao provincie; @ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST ) @JoinColumn( name = "DEEL", updatable = false ) protected RegionDao landsdeel; public static CbsSpaceDimensionDao of( final EntityManager em, final Place location ) { // TODO resolve regional levels recursively final CbsSpaceDimensionDao result = new CbsSpaceDimensionDao(); result.place = null;//PlaceDao.of( em, location.regions().get( Geography ); result.wijk = null;//WijkDao.of( location.zipCode() ); result.buurt = null;//BuurtDao.of( location.zipCode() ); result.gemeente = null;//GemeenteDao.of( location.zipCode() ); result.corop = null;//GgdDao.of( location.zipCode() ); result.ggd = null;//GgdDao.of( location.zipCode() ); result.provincie = null;//ProvincieDao.of( location.zipCode() ); result.landsdeel = null;//LandsdeelDao.of( location.zipCode() ); em.persist( result ); return result; } @Override public Place restore( final LocalBinder binder ) { // TODO Auto-generated method stub return null; } }
924490cb131851ae25486cdea610cd90ba37256e
508
java
Java
client/src/test/java/org/ehrbase/client/classgenerator/examples/openereactcarecomposition/definition/SepsisScreeningA999FlagElement.java
bratwurzt/openEHR_SDK
33aa4167264f002d7ce56e2b7234760af4b662b0
[ "Apache-2.0" ]
null
null
null
client/src/test/java/org/ehrbase/client/classgenerator/examples/openereactcarecomposition/definition/SepsisScreeningA999FlagElement.java
bratwurzt/openEHR_SDK
33aa4167264f002d7ce56e2b7234760af4b662b0
[ "Apache-2.0" ]
null
null
null
client/src/test/java/org/ehrbase/client/classgenerator/examples/openereactcarecomposition/definition/SepsisScreeningA999FlagElement.java
bratwurzt/openEHR_SDK
33aa4167264f002d7ce56e2b7234760af4b662b0
[ "Apache-2.0" ]
null
null
null
26.736842
88
0.769685
1,003,057
package org.ehrbase.client.classgenerator.examples.openereactcarecomposition.definition; import org.ehrbase.client.annotations.Entity; import org.ehrbase.client.annotations.Path; @Entity public class SepsisScreeningA999FlagElement { @Path("/value|defining_code") private Definingcode4 definingcode; public void setDefiningcode(Definingcode4 definingcode) { this.definingcode = definingcode; } public Definingcode4 getDefiningcode() { return this.definingcode; } }
924490fc5c9f5f232b31d51d49f562aab9f9ee61
10,882
java
Java
shell/ssh/src/main/java/org/apache/karaf/shell/ssh/KarafJaasAuthenticator.java
sho25/karaf
95110009181760c3e7ef86e96834a763899962db
[ "Apache-2.0" ]
null
null
null
shell/ssh/src/main/java/org/apache/karaf/shell/ssh/KarafJaasAuthenticator.java
sho25/karaf
95110009181760c3e7ef86e96834a763899962db
[ "Apache-2.0" ]
null
null
null
shell/ssh/src/main/java/org/apache/karaf/shell/ssh/KarafJaasAuthenticator.java
sho25/karaf
95110009181760c3e7ef86e96834a763899962db
[ "Apache-2.0" ]
null
null
null
13.792142
815
0.804448
1,003,058
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|karaf operator|. name|shell operator|. name|ssh package|; end_package begin_import import|import name|java operator|. name|security operator|. name|Principal import|; end_import begin_import import|import name|java operator|. name|security operator|. name|PublicKey import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|Subject import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|callback operator|. name|Callback import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|callback operator|. name|CallbackHandler import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|callback operator|. name|NameCallback import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|callback operator|. name|PasswordCallback import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|callback operator|. name|UnsupportedCallbackException import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|login operator|. name|FailedLoginException import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|login operator|. name|LoginContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|jaas operator|. name|boot operator|. name|principal operator|. name|ClientPrincipal import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|jaas operator|. name|modules operator|. name|publickey operator|. name|PublickeyCallback import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|sshd operator|. name|common operator|. name|session operator|. name|Session import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|sshd operator|. name|server operator|. name|auth operator|. name|password operator|. name|PasswordAuthenticator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|sshd operator|. name|server operator|. name|auth operator|. name|pubkey operator|. name|PublickeyAuthenticator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|sshd operator|. name|server operator|. name|session operator|. name|ServerSession import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_class specifier|public class|class name|KarafJaasAuthenticator implements|implements name|PasswordAuthenticator implements|, name|PublickeyAuthenticator block|{ specifier|public specifier|static specifier|final name|Session operator|. name|AttributeKey argument_list|< name|Subject argument_list|> name|SUBJECT_ATTRIBUTE_KEY init|= operator|new name|Session operator|. name|AttributeKey argument_list|<> argument_list|() decl_stmt|; specifier|private specifier|final name|Logger name|LOGGER init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|KarafJaasAuthenticator operator|. name|class argument_list|) decl_stmt|; specifier|private name|String name|realm decl_stmt|; specifier|private name|String name|role decl_stmt|; specifier|private name|Class argument_list|< name|? argument_list|> index|[] name|roleClasses decl_stmt|; specifier|public name|KarafJaasAuthenticator parameter_list|( name|String name|realm parameter_list|, name|String name|role parameter_list|, name|Class argument_list|< name|? argument_list|> index|[] name|roleClasses parameter_list|) block|{ name|this operator|. name|realm operator|= name|realm expr_stmt|; name|this operator|. name|role operator|= name|role expr_stmt|; name|this operator|. name|roleClasses operator|= name|roleClasses expr_stmt|; block|} specifier|public name|boolean name|authenticate parameter_list|( specifier|final name|String name|username parameter_list|, specifier|final name|String name|password parameter_list|, specifier|final name|ServerSession name|session parameter_list|) block|{ name|CallbackHandler name|callbackHandler init|= name|callbacks lambda|-> block|{ for|for control|( name|Callback name|callback range|: name|callbacks control|) block|{ if|if condition|( name|callback operator|instanceof name|NameCallback condition|) block|{ operator|( operator|( name|NameCallback operator|) name|callback operator|) operator|. name|setName argument_list|( name|username argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|callback operator|instanceof name|PasswordCallback condition|) block|{ operator|( operator|( name|PasswordCallback operator|) name|callback operator|) operator|. name|setPassword argument_list|( name|password operator|. name|toCharArray argument_list|() argument_list|) expr_stmt|; block|} else|else block|{ throw|throw operator|new name|UnsupportedCallbackException argument_list|( name|callback argument_list|) throw|; block|} block|} block|} decl_stmt|; return|return name|doLogin argument_list|( name|session argument_list|, name|callbackHandler argument_list|) return|; block|} specifier|public name|boolean name|authenticate parameter_list|( specifier|final name|String name|username parameter_list|, specifier|final name|PublicKey name|key parameter_list|, specifier|final name|ServerSession name|session parameter_list|) block|{ name|CallbackHandler name|callbackHandler init|= name|callbacks lambda|-> block|{ for|for control|( name|Callback name|callback range|: name|callbacks control|) block|{ if|if condition|( name|callback operator|instanceof name|NameCallback condition|) block|{ operator|( operator|( name|NameCallback operator|) name|callback operator|) operator|. name|setName argument_list|( name|username argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|callback operator|instanceof name|PublickeyCallback condition|) block|{ operator|( operator|( name|PublickeyCallback operator|) name|callback operator|) operator|. name|setPublicKey argument_list|( name|key argument_list|) expr_stmt|; block|} else|else block|{ throw|throw operator|new name|UnsupportedCallbackException argument_list|( name|callback argument_list|) throw|; block|} block|} block|} decl_stmt|; return|return name|doLogin argument_list|( name|session argument_list|, name|callbackHandler argument_list|) return|; block|} specifier|private name|boolean name|doLogin parameter_list|( specifier|final name|ServerSession name|session parameter_list|, name|CallbackHandler name|callbackHandler parameter_list|) block|{ try|try block|{ name|Subject name|subject init|= operator|new name|Subject argument_list|() decl_stmt|; name|subject operator|. name|getPrincipals argument_list|() operator|. name|add argument_list|( operator|new name|ClientPrincipal argument_list|( literal|"ssh" argument_list|, name|session operator|. name|getClientAddress argument_list|() operator|. name|toString argument_list|() argument_list|) argument_list|) expr_stmt|; name|LoginContext name|loginContext init|= operator|new name|LoginContext argument_list|( name|realm argument_list|, name|subject argument_list|, name|callbackHandler argument_list|) decl_stmt|; name|loginContext operator|. name|login argument_list|() expr_stmt|; name|assertRolePresent argument_list|( name|subject argument_list|) expr_stmt|; name|session operator|. name|setAttribute argument_list|( name|SUBJECT_ATTRIBUTE_KEY argument_list|, name|subject argument_list|) expr_stmt|; return|return literal|true return|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|LOGGER operator|. name|debug argument_list|( literal|"User authentication failed with " operator|+ name|e operator|. name|getMessage argument_list|() argument_list|, name|e argument_list|) expr_stmt|; return|return literal|false return|; block|} block|} specifier|private name|void name|assertRolePresent parameter_list|( name|Subject name|subject parameter_list|) throws|throws name|FailedLoginException block|{ name|boolean name|hasCorrectRole init|= name|role operator|== literal|null operator||| name|role operator|. name|isEmpty argument_list|() operator||| name|roleClasses operator|. name|length operator|== literal|0 decl_stmt|; name|int name|roleCount init|= literal|0 decl_stmt|; for|for control|( name|Principal name|principal range|: name|subject operator|. name|getPrincipals argument_list|() control|) block|{ for|for control|( name|Class argument_list|< name|? argument_list|> name|roleClass range|: name|roleClasses control|) block|{ if|if condition|( name|roleClass operator|. name|isInstance argument_list|( name|principal argument_list|) condition|) block|{ if|if condition|( operator|! name|hasCorrectRole condition|) block|{ name|hasCorrectRole operator|= name|role operator|. name|equals argument_list|( name|principal operator|. name|getName argument_list|() argument_list|) expr_stmt|; block|} name|roleCount operator|++ expr_stmt|; block|} block|} block|} if|if condition|( name|roleCount operator|== literal|0 condition|) block|{ throw|throw operator|new name|FailedLoginException argument_list|( literal|"User doesn't have role defined" argument_list|) throw|; block|} if|if condition|( operator|! name|hasCorrectRole condition|) block|{ throw|throw operator|new name|FailedLoginException argument_list|( literal|"User doesn't have the required role " operator|+ name|role argument_list|) throw|; block|} block|} block|} end_class end_unit
92449184561f8cb4b7cfdeedc65a27c9520347d5
5,130
java
Java
src/main/java/pk/com/habsoft/robosim/filters/core/ui/StateRenderLayer.java
habsoft/robosim
30d172757ab59671d7ace6163d549b667435943a
[ "Apache-2.0" ]
22
2016-03-18T05:08:09.000Z
2022-01-14T20:10:10.000Z
src/main/java/pk/com/habsoft/robosim/filters/core/ui/StateRenderLayer.java
habsoft/robosim
30d172757ab59671d7ace6163d549b667435943a
[ "Apache-2.0" ]
11
2016-03-01T18:15:11.000Z
2016-05-13T16:33:22.000Z
src/main/java/pk/com/habsoft/robosim/filters/core/ui/StateRenderLayer.java
habsoft/robosim
30d172757ab59671d7ace6163d549b667435943a
[ "Apache-2.0" ]
18
2016-03-01T16:06:39.000Z
2021-03-10T16:21:20.000Z
31.666667
87
0.65848
1,003,059
package pk.com.habsoft.robosim.filters.core.ui; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import pk.com.habsoft.robosim.filters.core.ObjectInstance; import pk.com.habsoft.robosim.filters.core.State; /** * This class provides 2D visualization of states by being provided a set of * classes that can paint ObjectInstnaces to the canvas as well as classes that * can paint general domain information. Painters for object classes as well as * specific object instances can be provided. If there is a painter for an * object class and a painter for a specific object instance of that same class, * then the specific object instance painter will be used to pain that object * instead of the painter for that instnace's OO-MDP class. * <p> * The order of painting is first the static painters, in the order they were * added; then the object class painters in the order they were painted (except * for objects that have specific object painter); finally, the object instances * that have specific painter associated with them, in the order that they * appear in the state object list. * * @author James MacGlashan * */ public class StateRenderLayer implements RenderLayer { /** * the current state to be painted next */ protected State curState; /** * list of static painters that pain static non-object defined properties of * the domain */ protected List<StaticPainter> staticPainters; /** * Ordered list of painters for each object class */ protected List<ObjectPainterAndClassNamePair> objectClassPainterList; /** * Map of painters that define how to paint specific objects; if an object * it appears in both specific and general lists, the specific painter is * used */ protected Map<String, ObjectPainter> specificObjectPainters; public StateRenderLayer() { curState = null; staticPainters = new ArrayList<StaticPainter>(); specificObjectPainters = new HashMap<String, ObjectPainter>(); objectClassPainterList = new ArrayList<ObjectPainterAndClassNamePair>(); } /** * Adds a static painter for the domain. * * @param sp * the static painter to add. */ public void addStaticPainter(StaticPainter sp) { staticPainters.add(sp); } /** * Adds a class that will paint objects that belong to a given OO-MDPclass. * * @param className * the name of the class that the provided painter can paint * @param op * the painter */ public void addObjectClassPainter(String className, ObjectPainter op) { objectClassPainterList.add(new ObjectPainterAndClassNamePair(className, op)); } /** * Adds a painter that will be used to paint a specific object in states * * @param objectName * the name of the object this painter is used to paint * @param op * the painter */ public void addSpecificObjectPainter(String objectName, ObjectPainter op) { specificObjectPainters.put(objectName, op); } /** * Updates the state that needs to be painted * * @param s * the state to paint */ public void updateState(State s) { curState = s; } public State getCurState() { return curState; } public List<StaticPainter> getStaticPainters() { return staticPainters; } public List<ObjectPainterAndClassNamePair> getObjectClassPainterList() { return objectClassPainterList; } public Map<String, ObjectPainter> getSpecificObjectPainters() { return specificObjectPainters; } @Override public void render(Graphics2D g2, float width, float height) { if (this.curState == null) { return; // don't render anything if there is no state to render } // draw the static properties for (StaticPainter sp : staticPainters) { sp.paint(g2, curState, width, height); } // draw each object by class order and if there is not a specific // painter for for (ObjectPainterAndClassNamePair op : this.objectClassPainterList) { List<ObjectInstance> objects = curState.getObjectsOfClass(op.className); for (ObjectInstance o : objects) { if (!this.specificObjectPainters.containsKey(o.getName())) { op.painter.paintObject(g2, curState, o, width, height); } } } } /** * A pair of the name of an object class to paint, and the * {@link burlap.oomdp.visualizer.ObjectPainter} to use to paint it. */ public static class ObjectPainterAndClassNamePair { String className; ObjectPainter painter; public ObjectPainterAndClassNamePair(String className, ObjectPainter painter) { this.className = className; this.painter = painter; } } }
92449377124a3ae0dade967b74e7ba82cad58707
1,137
java
Java
nats/nats-vs-rest/nats-service/src/main/java/com/vinsguru/square/service/NatsSquareService.java
yliu138/vinsguru-blog-code-samples
e4727a3f1b60ddeeace59e25176c9ccc27e0a4d6
[ "Apache-2.0" ]
null
null
null
nats/nats-vs-rest/nats-service/src/main/java/com/vinsguru/square/service/NatsSquareService.java
yliu138/vinsguru-blog-code-samples
e4727a3f1b60ddeeace59e25176c9ccc27e0a4d6
[ "Apache-2.0" ]
null
null
null
nats/nats-vs-rest/nats-service/src/main/java/com/vinsguru/square/service/NatsSquareService.java
yliu138/vinsguru-blog-code-samples
e4727a3f1b60ddeeace59e25176c9ccc27e0a4d6
[ "Apache-2.0" ]
null
null
null
35.53125
138
0.674582
1,003,060
package com.vinsguru.square.service; import com.google.protobuf.InvalidProtocolBufferException; import com.vinsguru.model.Input; import com.vinsguru.model.Output; import io.nats.client.Connection; import io.nats.client.Dispatcher; import io.nats.client.Nats; import java.io.IOException; import java.util.Objects; public class NatsSquareService { public static void main(String[] args) throws IOException, InterruptedException { String natsServer = Objects.toString(System.getenv("NATS_SERVER"), "nats://localhost:4222"); Connection nats = Nats.connect(natsServer); Dispatcher dispatcher = nats.createDispatcher(msg -> {}); dispatcher.subscribe("nats.square.service", (msg) -> { try { Input input = Input.parseFrom(msg.getData()); Output output = Output.newBuilder().setNumber(input.getNumber()).setResult(input.getNumber() * input.getNumber()).build(); nats.publish(msg.getReplyTo(), output.toByteArray()); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } }); } }
92449389d4bdb35351c383e631ae91c7ebc9490a
284
java
Java
project/app/src/main/java/com/xxyuan/project/ui/h5/DefaultHandler.java
xiaoyuan94/android2
12fde2434a47e679ad528684c7a5dd1dccc63065
[ "Apache-2.0" ]
null
null
null
project/app/src/main/java/com/xxyuan/project/ui/h5/DefaultHandler.java
xiaoyuan94/android2
12fde2434a47e679ad528684c7a5dd1dccc63065
[ "Apache-2.0" ]
null
null
null
project/app/src/main/java/com/xxyuan/project/ui/h5/DefaultHandler.java
xiaoyuan94/android2
12fde2434a47e679ad528684c7a5dd1dccc63065
[ "Apache-2.0" ]
null
null
null
21.846154
65
0.676056
1,003,061
package com.xxyuan.project.ui.h5; public class DefaultHandler implements BridgeHandler{ @Override public void handler(String data, CallBackFunction function) { if(function != null){ function.onCallBack("DefaultHandler response data"); } } }
924493d99bc41c455360952d21ae4963bf91fe72
314
java
Java
src/main/java/com/stripe/model/oauth/TokenResponse.java
codylerum/stripe-java
110ae567c68aa67cfe697a6309d35e3d13c5e419
[ "MIT" ]
540
2015-01-09T15:09:34.000Z
2022-03-29T15:00:26.000Z
src/main/java/com/stripe/model/oauth/TokenResponse.java
codylerum/stripe-java
110ae567c68aa67cfe697a6309d35e3d13c5e419
[ "MIT" ]
825
2015-01-05T19:25:18.000Z
2022-03-31T21:31:29.000Z
src/main/java/com/stripe/model/oauth/TokenResponse.java
codylerum/stripe-java
110ae567c68aa67cfe697a6309d35e3d13c5e419
[ "MIT" ]
315
2015-01-22T05:28:10.000Z
2022-03-23T07:49:57.000Z
19.625
49
0.805732
1,003,062
package com.stripe.model.oauth; import com.stripe.model.StripeObject; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Getter @Setter @EqualsAndHashCode(callSuper = false) public class TokenResponse extends StripeObject { Boolean livemode; String scope; String stripeUserId; }
92449439b5e084c99cc2090a1deaba97543d483f
871
java
Java
src/java/servicesUtilidad/trainingFromWSDL.java
ea2305/JavaTestWebServices
37cc935037770bb16297af2b9ac8c363bd95bfdb
[ "MIT" ]
null
null
null
src/java/servicesUtilidad/trainingFromWSDL.java
ea2305/JavaTestWebServices
37cc935037770bb16297af2b9ac8c363bd95bfdb
[ "MIT" ]
null
null
null
src/java/servicesUtilidad/trainingFromWSDL.java
ea2305/JavaTestWebServices
37cc935037770bb16297af2b9ac8c363bd95bfdb
[ "MIT" ]
null
null
null
37.869565
356
0.746269
1,003,063
/* * 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 servicesUtilidad; import javax.jws.WebService; /** * * @author andre */ @WebService(serviceName = "trainingWSDLService", portName = "trainingWSDLPort", endpointInterface = "org.netbeans.j2ee.wsdl.javatestwebservices.wsdlutilidad.trainingwsdl.TrainingWSDLPortType", targetNamespace = "http://j2ee.netbeans.org/wsdl/JavaTestWebServices/WSDLUtilidad/trainingWSDL", wsdlLocation = "WEB-INF/wsdl/trainingFromWSDL/trainingWSDL.wsdl") public class trainingFromWSDL { public boolean trainingWSDLOperation(java.lang.String skill) { //TODO implement this method throw new UnsupportedOperationException("Not implemented yet."); } }
9244950ea8c88e0d38c8f8faeb63a0b77e91a1e8
3,493
java
Java
app/src/main/java/site/team2dev/nemubengkel/RegisterActivity.java
sogatanco/nemu-bengkel
73dff3c505274f511cd73e1e78d01319879af141
[ "MIT" ]
1
2019-08-23T17:31:01.000Z
2019-08-23T17:31:01.000Z
app/src/main/java/site/team2dev/nemubengkel/RegisterActivity.java
sogatanco/nemu-bengkel
73dff3c505274f511cd73e1e78d01319879af141
[ "MIT" ]
1
2019-07-25T16:13:14.000Z
2019-08-10T07:42:11.000Z
app/src/main/java/site/team2dev/nemubengkel/RegisterActivity.java
sogatanco/nemu-bengkel
73dff3c505274f511cd73e1e78d01319879af141
[ "MIT" ]
null
null
null
33.266667
122
0.636988
1,003,064
package site.team2dev.nemubengkel; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; import javax.xml.transform.ErrorListener; public class RegisterActivity extends AppCompatActivity { private EditText email, password1, password2; private RequestQueue requestQueue; private static String URL=""; private StringRequest stringRequest; Fungsi fungsi = new Fungsi(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); URL=getString(R.string.base_url)+"api/register"; email=(EditText)findViewById(R.id.regemail); password1=(EditText)findViewById(R.id.regpassword1); password2=(EditText)findViewById(R.id.regpassword2); requestQueue= Volley.newRequestQueue(this); fungsi.checkEmail(email); fungsi.lengthPass(password1); } public void goLogin(View view) { Intent intent =new Intent(this,LoginActivity.class); startActivity(intent); } public void addUser(View view) { EditText[] editTexts={email,password2, password1}; fungsi.emptyChecker(editTexts); fungsi.matchPass(password1, password2); if(!fungsi.isHasError(editTexts)){ stringRequest=new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject=new JSONObject(response); Toast.makeText(getApplicationContext(),jsonObject.getString("message"), Toast.LENGTH_LONG).show(); } catch (JSONException e) { e.printStackTrace(); } Intent intent=new Intent(RegisterActivity.this, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Field ", Toast.LENGTH_LONG).show(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> hashMap=new HashMap<String, String>(); hashMap.put("email",email.getText().toString()); hashMap.put("pass",password1.getText().toString()); hashMap.put("token", "1234567"); return hashMap; } }; requestQueue.add(stringRequest); } } }
92449549fb61d8ea53a09f99de70e402ad37e4bd
7,364
java
Java
app/src/main/java/com/elsonsmith/IRRESTAPIServer/SimpleWebServer.java
ecs87/Java-Infared-REST-API-for-Android
064b68d72d5eb1ce09e21ec9ae3b3e7f4ed10f4c
[ "MIT" ]
2
2020-10-21T15:03:42.000Z
2021-05-06T07:15:20.000Z
app/src/main/java/com/elsonsmith/IRRESTAPIServer/SimpleWebServer.java
ecs87/Java-Infared-REST-API-for-Android
064b68d72d5eb1ce09e21ec9ae3b3e7f4ed10f4c
[ "MIT" ]
null
null
null
app/src/main/java/com/elsonsmith/IRRESTAPIServer/SimpleWebServer.java
ecs87/Java-Infared-REST-API-for-Android
064b68d72d5eb1ce09e21ec9ae3b3e7f4ed10f4c
[ "MIT" ]
1
2021-05-07T08:40:37.000Z
2021-05-07T08:40:37.000Z
32.157205
145
0.563009
1,003,065
package com.elsonsmith.IRRESTAPIServer; import android.content.Context; import android.hardware.ConsumerIrManager; import android.text.TextUtils; import android.util.Log; import org.apache.commons.lang3.ArrayUtils; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /* * Copyright (C) 2014 The Android Open Source Project * * 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. */ /** * Implementation of a very basic HTTP server. The contents are loaded from the assets folder. This * server handles one request at a time. It only supports GET method. */ public class SimpleWebServer implements Runnable { public static MainActivity context = null; private static final String TAG = "SimpleInfaredRESTAPI"; /** * The port number we listen to */ private final int mPort; /** * True if the server is running. */ private boolean mIsRunning; /** * The {@link java.net.ServerSocket} that we listen to. */ private ServerSocket mServerSocket; /** * WebServer constructor. */ public SimpleWebServer(int port) { mPort = port; } /** * This method starts the web server listening to the specified port. */ public void start() { mIsRunning = true; new Thread(this).start(); } /** * This method stops the web server */ public void stop() { try { mIsRunning = false; if (null != mServerSocket) { mServerSocket.close(); mServerSocket = null; } } catch (IOException e) { Log.e(TAG, "Error closing the server socket.", e); } } public int getPort() { return mPort; } @Override public void run() { try { mServerSocket = new ServerSocket(mPort); while (mIsRunning) { Socket socket = mServerSocket.accept(); handle(socket); socket.close(); } } catch (SocketException e) { // The server was stopped; ignore. } catch (IOException e) { Log.e(TAG, "Web server error.", e); } } private void handle(Socket socket) throws IOException { BufferedReader reader = null; PrintStream output = null; try { String route = null; // Read HTTP headers and parse out the route. reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; while (!TextUtils.isEmpty(line = reader.readLine())) { if (line.startsWith("GET /")) { int start = line.indexOf('/') + 1; int end = line.indexOf(' ', start); route = line.substring(start, end); break; } } // Output stream that we send the response to output = new PrintStream(socket.getOutputStream()); // Prepare the content to send. if (null == route) { writeServerError(output); return; } byte[] bytes = loadContent(route); if (null == bytes) { writeServerError(output); return; } // Send out the content. output.println("HTTP/1.0 200 OK"); output.println("Content-Type: " + detectMimeType(route)); output.println("Content-Length: " + bytes.length); output.println(); output.write(bytes); output.flush(); } finally { if (null != output) { output.close(); } if (null != reader) { reader.close(); } } } private void writeServerError(PrintStream output) { output.println("HTTP/1.0 500 Internal Server Error"); output.flush(); } protected int[] dec2SamsungIRDec(double[] irDec) { int[] pattern = new int[irDec.length]; for (int i = 0; i < irDec.length; i++) { irDec[i] = irDec[i] * 26.3; pattern[i] += (int)Math.rint(irDec[i]); } return pattern; } private byte[] loadContent(String fileName) throws IOException { InputStream input = null; final ConsumerIrManager mCIR; mCIR = (ConsumerIrManager)SimpleWebServer.context.getSystemService(Context.CONSUMER_IR_SERVICE); try { ByteArrayOutputStream output = new ByteArrayOutputStream(); if (fileName.equals("") || fileName.equals("/")) { input = new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8)); } else if (fileName.toLowerCase().contains("sendIRcmd/".toLowerCase()) || fileName.toLowerCase().contains("sendIRcmd".toLowerCase())) { try { int start = fileName.lastIndexOf('/') + 1; String IRcmdPre = fileName.substring(start); List<String> IRcmdProcess = Arrays.asList(IRcmdPre.split(",")); List<Double> IRcmds = new ArrayList<>(); for (String IRcmd : IRcmdProcess) { IRcmds.add(Double.valueOf(IRcmd)); } Double[] IRcmdsArray = IRcmds.toArray(new Double[0]); double[] IRcmdsArrayFinal = ArrayUtils.toPrimitive(IRcmdsArray); int[] pattern = dec2SamsungIRDec(IRcmdsArrayFinal); mCIR.transmit(38000, pattern); input = new ByteArrayInputStream("IR cmd sent".getBytes(StandardCharsets.UTF_8)); } catch (Exception ex) { Log.d(TAG, "FAILED"); input = new ByteArrayInputStream("IR cmd failed".getBytes(StandardCharsets.UTF_8)); } } byte[] buffer = new byte[1024]; int size; while (-1 != (size = input.read(buffer))) { output.write(buffer, 0, size); } output.flush(); return output.toByteArray(); } catch (Exception e) { return null; } finally { if (null != input) { input.close(); } } } private String detectMimeType(String fileName) { return null; } }
92449668da265ff683f1693076e5ef779d7a3381
2,154
java
Java
org/apache/fop/pdf/PDFEncryptionParams.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
1
2022-02-24T01:32:41.000Z
2022-02-24T01:32:41.000Z
org/apache/fop/pdf/PDFEncryptionParams.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
org/apache/fop/pdf/PDFEncryptionParams.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
26.592593
176
0.706592
1,003,066
package org.apache.fop.pdf; public class PDFEncryptionParams { private String userPassword = ""; private String ownerPassword = ""; private boolean allowPrint = true; private boolean allowCopyContent = true; private boolean allowEditContent = true; private boolean allowEditAnnotations = true; public PDFEncryptionParams(String userPassword, String ownerPassword, boolean allowPrint, boolean allowCopyContent, boolean allowEditContent, boolean allowEditAnnotations) { this.setUserPassword(userPassword); this.setOwnerPassword(ownerPassword); this.setAllowPrint(allowPrint); this.setAllowCopyContent(allowCopyContent); this.setAllowEditContent(allowEditContent); this.setAllowEditAnnotations(allowEditAnnotations); } public PDFEncryptionParams() { } public boolean isAllowCopyContent() { return this.allowCopyContent; } public boolean isAllowEditAnnotations() { return this.allowEditAnnotations; } public boolean isAllowEditContent() { return this.allowEditContent; } public boolean isAllowPrint() { return this.allowPrint; } public String getOwnerPassword() { return this.ownerPassword; } public String getUserPassword() { return this.userPassword; } public void setAllowCopyContent(boolean allowCopyContent) { this.allowCopyContent = allowCopyContent; } public void setAllowEditAnnotations(boolean allowEditAnnotations) { this.allowEditAnnotations = allowEditAnnotations; } public void setAllowEditContent(boolean allowEditContent) { this.allowEditContent = allowEditContent; } public void setAllowPrint(boolean allowPrint) { this.allowPrint = allowPrint; } public void setOwnerPassword(String ownerPassword) { if (ownerPassword == null) { this.ownerPassword = ""; } else { this.ownerPassword = ownerPassword; } } public void setUserPassword(String userPassword) { if (userPassword == null) { this.userPassword = ""; } else { this.userPassword = userPassword; } } }
924496b5be0228d92688d9a378d828f6a3b3f382
1,357
java
Java
projetHadl/src/M2/Objet_Architectural/Configuration/PackageComposant/Composant.java
kirapoetica974/projet_HADL
81fdfdf14058c7a8292163b7e36dfe56000a9487
[ "MIT" ]
null
null
null
projetHadl/src/M2/Objet_Architectural/Configuration/PackageComposant/Composant.java
kirapoetica974/projet_HADL
81fdfdf14058c7a8292163b7e36dfe56000a9487
[ "MIT" ]
null
null
null
projetHadl/src/M2/Objet_Architectural/Configuration/PackageComposant/Composant.java
kirapoetica974/projet_HADL
81fdfdf14058c7a8292163b7e36dfe56000a9487
[ "MIT" ]
null
null
null
22.245902
72
0.723655
1,003,067
package M2.Objet_Architectural.Configuration.PackageComposant; import java.util.ArrayList; import java.util.List; import M2.Objet_Architectural.Objet_Architectural; public abstract class Composant extends Objet_Architectural { private List<Propriete> listePropriete = new ArrayList<Propriete>(); private List<Contrainte> listeContrainte = new ArrayList<Contrainte>(); /** * @return la listePropriete */ public List<Propriete> getListePropriete() { return listePropriete; } /** * @param listePropriete * la listePropriete à modifier */ public void setListePropriete(List<Propriete> listePropriete) { this.listePropriete = listePropriete; } /** * @param propriete * ajout de propriete dans listePropriete */ public void addPropriete(Propriete propriete) { this.listePropriete.add(propriete); } /** * @return la listeContrainte */ public List<Contrainte> getListeContrainte() { return listeContrainte; } /** * @param listeContrainte * la listeContrainte à modifier */ public void setListeContrainte(List<Contrainte> listeContrainte) { this.listeContrainte = listeContrainte; } /** * @param contrainte * ajout de contrainte dans listeContrainte */ public void addContrainte(Contrainte contrainte) { this.listeContrainte.add(contrainte); } }
9244972364e55ad9166eaa4118d2a25121dfd419
3,224
java
Java
src/cn/wizool/schooltimetable/Rules/UniformRules/UniformRulesInfoUpload.java
pljay/SchoolTimetable
6a3ec8517a1e7dbdc39420feb8593ccff939c99a
[ "MIT" ]
null
null
null
src/cn/wizool/schooltimetable/Rules/UniformRules/UniformRulesInfoUpload.java
pljay/SchoolTimetable
6a3ec8517a1e7dbdc39420feb8593ccff939c99a
[ "MIT" ]
null
null
null
src/cn/wizool/schooltimetable/Rules/UniformRules/UniformRulesInfoUpload.java
pljay/SchoolTimetable
6a3ec8517a1e7dbdc39420feb8593ccff939c99a
[ "MIT" ]
null
null
null
32.897959
159
0.721464
1,003,068
package cn.wizool.schooltimetable.Rules.UniformRules; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; 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 org.apache.log4j.Logger; import cn.wizool.schooltimetable.bean.Common; import cn.wizool.schooltimetable.bean.JieciCommon; import cn.wizool.schooltimetable.jdbc.Mysql; import cn.wizool.schooltimetable.utils.JieciTypeUtils; import cn.wizool.schooltimetable.utils.JsonUtils; import cn.wizool.schooltimetable.utils.ResponseUtils; /** * Servlet implementation class UniformRulesInfo */ @WebServlet(description = "统一设置规则", urlPatterns = { "/UniformRulesInfo" }) public class UniformRulesInfoUpload extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger logger=Logger.getLogger(UniformRulesInfoUpload.class); /** * @see HttpServlet#HttpServlet() */ public UniformRulesInfoUpload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub logger.info(request.getParameter("strJson")); Common common= JsonUtils.jsonToPojo(request.getParameter("strJson"), Common.class); logger.info(common.getSchoolid()+"\r"+common.getTaskid()); Connection connection = Mysql.getInstance().getConnection(); try { String sql1="DELETE \r\n" + "FROM\r\n" + " xiaoxuan.`时间统一设置`\r\n" + "WHERE\r\n" + " xiaoxuan.`时间统一设置`.task_id = '"+common.getTaskid()+"'\r\n" + "AND school_id = '"+common.getSchoolid()+"'"; logger.info(sql1); PreparedStatement prepareStatement2 = connection.prepareStatement(sql1); prepareStatement2.execute(); prepareStatement2.close(); for (JieciCommon jieciCommon :common.getbanlist()) { String sql="INSERT INTO `xiaoxuan`.`时间统一设置` (\r\n" + " `school_id`,\r\n" + " `task_id`,\r\n" + " `jieci_id`,\r\n" + " `type`\r\n" + ")\r\n" + "VALUES\r\n" + " ( '"+common.getSchoolid()+"', '"+common.getTaskid()+"', '"+jieciCommon.getId()+"', '"+new JieciTypeUtils().GetNumber(jieciCommon.getCoursetype())+"')"; logger.info(sql); PreparedStatement prepareStatement = connection.prepareStatement(sql); prepareStatement.execute(); prepareStatement.close(); } ResponseUtils.renderJson(response, "success"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doGet(req, resp); } }
92449936db1fe07951cc60b0d4e0161297dfc03c
2,479
java
Java
src/main/java/org/wyw/lanplay/config/WebSocketConfig.java
wuydit/lanPlay
d60e457e776e60e5fb957a61ae687c531f037bdf
[ "Apache-2.0" ]
null
null
null
src/main/java/org/wyw/lanplay/config/WebSocketConfig.java
wuydit/lanPlay
d60e457e776e60e5fb957a61ae687c531f037bdf
[ "Apache-2.0" ]
null
null
null
src/main/java/org/wyw/lanplay/config/WebSocketConfig.java
wuydit/lanPlay
d60e457e776e60e5fb957a61ae687c531f037bdf
[ "Apache-2.0" ]
null
null
null
38.734375
117
0.732957
1,003,069
package org.wyw.lanplay.config; import org.apache.tomcat.util.net.openssl.ciphers.Authentication; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.web.socket.config.annotation.*; import org.wyw.lanplay.entity.UserRecordEntity; import org.wyw.lanplay.service.CommonService; import java.security.Principal; @Configuration @EnableWebSocket @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { private CommonService commonService; public WebSocketConfig(CommonService commonService) { this.commonService = commonService; } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/socket") .setAllowedOrigins("*") .addInterceptors(new TokenAuthHandshakeInterceptor(commonService)) .withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.setApplicationDestinationPrefixes("/app"); config.enableSimpleBroker("/room","/user","/sysMsg"); config.setUserDestinationPrefix("/room"); config.setUserDestinationPrefix("/user"); } @Override public void configureClientInboundChannel(ChannelRegistration registration) { registration.interceptors(new ChannelInterceptor() { @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); if (StompCommand.CONNECT.equals(accessor.getCommand())) { UserRecordEntity userRecordEntity = (UserRecordEntity)accessor.getSessionAttributes().get("user"); accessor.setUser(userRecordEntity); } return message; } }); } }
92449a0e6048fd7416e2c9f6c56437a73238728c
4,776
java
Java
app/common/util/src/main/java/com/bbd/bdsso/common/util/email/SimpleMailSender.java
jinghuaaa/sso
9d00fecf6fd80d1788ef3eb3f4c1c9418ddc667c
[ "Apache-2.0" ]
null
null
null
app/common/util/src/main/java/com/bbd/bdsso/common/util/email/SimpleMailSender.java
jinghuaaa/sso
9d00fecf6fd80d1788ef3eb3f4c1c9418ddc667c
[ "Apache-2.0" ]
null
null
null
app/common/util/src/main/java/com/bbd/bdsso/common/util/email/SimpleMailSender.java
jinghuaaa/sso
9d00fecf6fd80d1788ef3eb3f4c1c9418ddc667c
[ "Apache-2.0" ]
null
null
null
35.641791
97
0.600503
1,003,070
/** * BBD Service Inc * All Rights Reserved @2016 * */ package com.bbd.bdsso.common.util.email; import java.util.Date; import java.util.List; import java.util.Properties; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.bbd.bdsso.common.util.enums.BdssoResultEnum; import com.bbd.bdsso.common.util.exception.BdssoBaseException; /** * 邮件发送器 * * @author byron * @version $Id: SimpleMailSender.java, v 0.1 Nov 28, 2016 10:37:32 AM byron Exp $ */ public class SimpleMailSender { /** * 发送文本邮件 * * @param mailInfo * @return */ public boolean sendTextMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address[] tos = getTos(mailInfo); mailMessage.addRecipients(Message.RecipientType.TO, tos); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { throw new BdssoBaseException(BdssoResultEnum.SEND_EMAIL_FAIL, ex.getMessage()); } } /** * 以HTML格式发送邮件 * * @param mailInfo 待发送的邮件信息 * @return */ public boolean sendHtmlMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); //如果需要身份认证,则创建一个密码验证器 if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address[] tos = getTos(mailInfo); mailMessage.addRecipients(Message.RecipientType.TO, tos); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 设置HTML内容 html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { throw new BdssoBaseException(BdssoResultEnum.SEND_EMAIL_FAIL, ex.getMessage()); } } private Address[] getTos(MailSenderInfo mailInfo) throws AddressException { List<String> emails = mailInfo.getToAddresses(); int size = emails.size(); Address[] tos = new InternetAddress[size]; for (int i = 0; i < size; i++) { tos[i] = new InternetAddress(emails.get(i)); } return tos; } }
92449a90b1677e3795445dfe4a78abb3aa7b249c
1,850
java
Java
src/main/java/br/sistemalojaroupas/model/services/SaleService.java
silascunha/sistema-loja-de-roupas
3dd0f5ab7dc228baeac22ec5efdce744a8c0043f
[ "MIT" ]
6
2021-01-09T10:22:22.000Z
2021-11-25T21:04:30.000Z
src/main/java/br/sistemalojaroupas/model/services/SaleService.java
MarianaGJ/sistema-loja-de-roupas
3dd0f5ab7dc228baeac22ec5efdce744a8c0043f
[ "MIT" ]
6
2020-12-09T01:23:06.000Z
2020-12-09T01:24:44.000Z
src/main/java/br/sistemalojaroupas/model/services/SaleService.java
MarianaGJ/sistema-loja-de-roupas
3dd0f5ab7dc228baeac22ec5efdce744a8c0043f
[ "MIT" ]
4
2021-11-23T19:35:05.000Z
2021-12-27T00:06:30.000Z
29.83871
79
0.624324
1,003,071
/* * 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 br.sistemalojaroupas.model.services; import br.sistemalojaroupas.model.dao.ProductDao; import br.sistemalojaroupas.model.dao.SaleDao; import br.sistemalojaroupas.model.entities.Product; import br.sistemalojaroupas.model.entities.Sale; import br.sistemalojaroupas.model.entities.SaleItem; import java.util.Date; import java.util.LinkedList; import java.util.List; /** * * @author silas */ public class SaleService { public static void confirmSale(Sale sale) { sale.getItems().forEach(x -> { Product product = x.getProduct(); product.setQuantity(product.getQuantity() - x.getQuantity()); ProductDao.update(product); }); sale.setMoment(new Date()); SaleDao.insert(sale); } public static Double ticketMedio() { Long totalSales = SaleDao.size(); Double revenues = SaleDao.revenues(0); Double result = 0.0; result = revenues / totalSales; return (totalSales != 0) ? result : 0.0; } public static Double receitaLiquida() { Double revenues = SaleDao.revenues(0); Double receitaLiquida = 0.0; List<SaleItem> items = new LinkedList<>(); SaleDao.findAll().forEach(s -> { items.addAll(s.getItems()); }); for (SaleItem item : items) { Double subTotal = item.getSubTotal(); Integer quantity = item.getQuantity(); Double totalCost = item.getProduct().getCostPrice() * quantity; receitaLiquida += subTotal - totalCost; } return receitaLiquida; } }
92449d36d4905afdfc1cecb7aa1db0304005fe95
1,268
java
Java
core/src/main/java/net/consensys/eventeum/chain/factory/DefaultBlockDetailsFactory.java
medicalchain/eventeum
afab911441e1318a67a928e9a3a25e6aa8d829d6
[ "Apache-2.0" ]
260
2018-05-26T13:42:29.000Z
2020-11-16T08:06:22.000Z
core/src/main/java/net/consensys/eventeum/chain/factory/DefaultBlockDetailsFactory.java
medicalchain/eventeum
afab911441e1318a67a928e9a3a25e6aa8d829d6
[ "Apache-2.0" ]
74
2018-05-25T23:26:22.000Z
2020-11-15T23:07:08.000Z
core/src/main/java/net/consensys/eventeum/chain/factory/DefaultBlockDetailsFactory.java
medicalchain/eventeum
afab911441e1318a67a928e9a3a25e6aa8d829d6
[ "Apache-2.0" ]
77
2018-05-30T02:49:38.000Z
2020-11-07T00:28:50.000Z
34.27027
75
0.753943
1,003,072
/* * 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 net.consensys.eventeum.chain.factory; import net.consensys.eventeum.chain.service.domain.Block; import net.consensys.eventeum.dto.block.BlockDetails; import org.springframework.stereotype.Component; import org.web3j.utils.Numeric; @Component public class DefaultBlockDetailsFactory implements BlockDetailsFactory { @Override public BlockDetails createBlockDetails(Block block) { final BlockDetails blockDetails = new BlockDetails(); blockDetails.setNumber(block.getNumber()); blockDetails.setHash(block.getHash()); blockDetails.setTimestamp(block.getTimestamp()); blockDetails.setNodeName(block.getNodeName()); return blockDetails; } }
92449d74f0865196d406464a4ab7a416158c3230
843
java
Java
java/com/android/dialer/callcomposer/camera/exif/ExifInvalidFormatException.java
unknownyard/packages_apps_Dialer
889165652e2bf4688593d590bc36741740be8890
[ "Apache-2.0" ]
34
2017-01-17T07:05:15.000Z
2022-03-04T02:45:13.000Z
java/com/android/dialer/callcomposer/camera/exif/ExifInvalidFormatException.java
unknownyard/packages_apps_Dialer
889165652e2bf4688593d590bc36741740be8890
[ "Apache-2.0" ]
10
2017-01-14T02:21:01.000Z
2020-01-19T17:08:11.000Z
java/com/android/dialer/callcomposer/camera/exif/ExifInvalidFormatException.java
unknownyard/packages_apps_Dialer
889165652e2bf4688593d590bc36741740be8890
[ "Apache-2.0" ]
285
2016-12-28T19:54:49.000Z
2022-03-26T09:24:56.000Z
33.72
75
0.744958
1,003,073
/* * Copyright (C) 2012 The Android Open Source Project * * 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.android.dialer.callcomposer.camera.exif; /** Exception for invalid exif formats. */ public class ExifInvalidFormatException extends Exception { ExifInvalidFormatException(String meg) { super(meg); } }
92449e57c42666b0ff8d22ed1fed2918c41c62ad
2,312
java
Java
otaku-admin/src/main/java/top/kairuiyang/admin/config/Swagger3Config.java
BarrelStopHere/otaku-blog
4dfb4b2604a1a2c9a28b849cfe56f7a5d19547f8
[ "Apache-2.0" ]
null
null
null
otaku-admin/src/main/java/top/kairuiyang/admin/config/Swagger3Config.java
BarrelStopHere/otaku-blog
4dfb4b2604a1a2c9a28b849cfe56f7a5d19547f8
[ "Apache-2.0" ]
null
null
null
otaku-admin/src/main/java/top/kairuiyang/admin/config/Swagger3Config.java
BarrelStopHere/otaku-blog
4dfb4b2604a1a2c9a28b849cfe56f7a5d19547f8
[ "Apache-2.0" ]
null
null
null
37.290323
119
0.663062
1,003,074
package top.kairuiyang.admin.config; import com.google.common.collect.Lists; import io.swagger.annotations.ApiOperation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import java.util.List; @Configuration class Swagger3Config { @Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30). useDefaultResponseMessages(false) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.regex("^(?!auth).*$")) .build() .securitySchemes(securitySchemes()) .securityContexts(securityContexts()); } private List<SecurityScheme> securitySchemes() { return Lists.newArrayList( new ApiKey("Authorization", "Authorization", "header")); } List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("top/kairuiyang/xo/global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return Lists.newArrayList( new SecurityReference("Authorization", authorizationScopes)); } private List<SecurityContext> securityContexts() { return Lists.newArrayList( SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("^(?!auth).*$")) .build() ); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("蘑菇博客Admin接口文档") .description("简单优雅的restful风格") .version("1.0") .build(); } }
92449e80c77de172c3bf547ced2efba2ebba084d
2,742
java
Java
me/hero/onepop/onepopclient/hacks/chat/OnePopVisualRange.java
christallinqq/CarrotHack
279cc1295a30b1c77e8b8afcc684493cd82c0141
[ "Unlicense" ]
9
2021-09-04T03:56:28.000Z
2021-09-18T21:13:34.000Z
me/hero/onepop/onepopclient/hacks/chat/OnePopVisualRange.java
christallinqq/CarrotHack
279cc1295a30b1c77e8b8afcc684493cd82c0141
[ "Unlicense" ]
2
2021-09-04T10:31:50.000Z
2021-09-11T00:06:04.000Z
me/hero/onepop/onepopclient/hacks/chat/OnePopVisualRange.java
christallinqq/CarrotHack
279cc1295a30b1c77e8b8afcc684493cd82c0141
[ "Unlicense" ]
2
2021-09-04T03:56:29.000Z
2021-09-04T11:55:04.000Z
40.323529
180
0.623632
1,003,075
package me.hero.onepop.onepopclient.hacks.chat; import com.mojang.realmsclient.gui.ChatFormatting; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import me.hero.onepop.OnePop; import me.hero.onepop.onepopclient.hacks.OnePopCategory; import me.hero.onepop.onepopclient.hacks.OnePopHack; import me.hero.onepop.onepopclient.util.OnePopFriendUtil; import me.hero.onepop.onepopclient.util.OnePopMessageUtil; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; public class OnePopVisualRange extends OnePopHack { private List<String> people; public OnePopVisualRange() { super(OnePopCategory.ONEPOP_CHAT); this.name = "Visual Range"; this.tag = "VisualRange"; this.description = "bc using ur eyes is overrated"; } public void enable() { this.people = new ArrayList(); } public void update() { if (!(mc.field_71441_e == null | mc.field_71439_g == null)) { List<String> peoplenew = new ArrayList(); List<EntityPlayer> playerEntities = mc.field_71441_e.field_73010_i; Iterator var3 = playerEntities.iterator(); while(var3.hasNext()) { Entity e = (Entity)var3.next(); if (!e.func_70005_c_().equals(mc.field_71439_g.func_70005_c_())) { peoplenew.add(e.func_70005_c_()); } } if (peoplenew.size() > 0) { var3 = peoplenew.iterator(); while(var3.hasNext()) { String name = (String)var3.next(); if (!this.people.contains(name)) { if (OnePopFriendUtil.isFriend(name)) { if (OnePop.get_setting_manager().get_setting_with_tag("GUI", "ClientLanguage").in("PT")) { OnePopMessageUtil.send_client_message("to vendo um cara chamado " + ChatFormatting.RESET + ChatFormatting.GREEN + name + ChatFormatting.RESET + " :D"); } else { OnePopMessageUtil.send_client_message(ChatFormatting.GREEN + name + ChatFormatting.RESET + " is entering your visual range :D"); } } else if (OnePop.get_setting_manager().get_setting_with_tag("GUI", "ClientLanguage").in("PT")) { OnePopMessageUtil.send_client_message("to vendo um cara chamado " + ChatFormatting.RESET + ChatFormatting.RED + name + ChatFormatting.RESET + ". negrinhokkk"); } else { OnePopMessageUtil.send_client_message(ChatFormatting.RED + name + ChatFormatting.RESET + " is entering your visual range :("); } this.people.add(name); } } } } } }
92449faa0946393c2af888e019c6e604a7de9c96
9,326
java
Java
db-6.2.32.NC/examples/sql/adf/EX_ADF/Model/src/model/entity/SuppliersEOImpl.java
secondwatchCH/JinCoin
2805e385e172f7b81f8487a3b6cbf18d7b31a606
[ "MIT" ]
1
2018-08-22T00:30:02.000Z
2018-08-22T00:30:02.000Z
deps/db-6.2.23/examples/sql/adf/EX_ADF/Model/src/model/entity/SuppliersEOImpl.java
lukechilds/node-berkeleydb
3887174343c3c57b7b343eca87696251eff13d82
[ "MIT" ]
null
null
null
deps/db-6.2.23/examples/sql/adf/EX_ADF/Model/src/model/entity/SuppliersEOImpl.java
lukechilds/node-berkeleydb
3887174343c3c57b7b343eca87696251eff13d82
[ "MIT" ]
1
2020-11-04T06:58:34.000Z
2020-11-04T06:58:34.000Z
30.778878
114
0.581064
1,003,076
package model.entity; import oracle.jbo.Key; import oracle.jbo.RowIterator; import oracle.jbo.server.AttributeDefImpl; import oracle.jbo.server.EntityDefImpl; import oracle.jbo.server.EntityImpl; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Mon Aug 19 12:03:06 CST 2013 // --- Custom code may be added to this class. // --- Warning: Do not modify method signatures of generated methods. // --------------------------------------------------------------------- public class SuppliersEOImpl extends EntityImpl { public void lock() { //super.lock(); } protected StringBuffer buildDMLStatement(int i, AttributeDefImpl[] attributeDefImpl, AttributeDefImpl[] attributeDefImpl2, AttributeDefImpl[] attributeDefImpl3, boolean b) { StringBuffer stmt = super.buildDMLStatement(i, attributeDefImpl, attributeDefImpl2, attributeDefImpl3, b); if (i == DML_UPDATE) { // Get the alias name (it is equal to the entity definition name) String alias = this.getEntityDef().getDefName(); // Remove the alias from the UPDATE statement int index = stmt.indexOf( " " + alias + " SET "); if (index != -1) stmt = stmt.replace( index, index + alias.length() + 1, ""); } return stmt; } /** * AttributesEnum: generated enum for identifying attributes and accessors. Do not modify. */ public enum AttributesEnum { SupId { public Object get(SuppliersEOImpl obj) { return obj.getSupId(); } public void put(SuppliersEOImpl obj, Object value) { obj.setSupId((Integer)value); } } , SupName { public Object get(SuppliersEOImpl obj) { return obj.getSupName(); } public void put(SuppliersEOImpl obj, Object value) { obj.setSupName((String)value); } } , Street { public Object get(SuppliersEOImpl obj) { return obj.getStreet(); } public void put(SuppliersEOImpl obj, Object value) { obj.setStreet((String)value); } } , City { public Object get(SuppliersEOImpl obj) { return obj.getCity(); } public void put(SuppliersEOImpl obj, Object value) { obj.setCity((String)value); } } , State { public Object get(SuppliersEOImpl obj) { return obj.getState(); } public void put(SuppliersEOImpl obj, Object value) { obj.setState((String)value); } } , Zip { public Object get(SuppliersEOImpl obj) { return obj.getZip(); } public void put(SuppliersEOImpl obj, Object value) { obj.setZip((String)value); } } , CoffeesEO { public Object get(SuppliersEOImpl obj) { return obj.getCoffeesEO(); } public void put(SuppliersEOImpl obj, Object value) { obj.setAttributeInternal(index(), value); } } ; private static AttributesEnum[] vals = null; private static int firstIndex = 0; public abstract Object get(SuppliersEOImpl object); public abstract void put(SuppliersEOImpl object, Object value); public int index() { return AttributesEnum.firstIndex() + ordinal(); } public static int firstIndex() { return firstIndex; } public static int count() { return AttributesEnum.firstIndex() + AttributesEnum.staticValues().length; } public static AttributesEnum[] staticValues() { if (vals == null) { vals = AttributesEnum.values(); } return vals; } } public static final int SUPID = AttributesEnum.SupId.index(); public static final int SUPNAME = AttributesEnum.SupName.index(); public static final int STREET = AttributesEnum.Street.index(); public static final int CITY = AttributesEnum.City.index(); public static final int STATE = AttributesEnum.State.index(); public static final int ZIP = AttributesEnum.Zip.index(); public static final int COFFEESEO = AttributesEnum.CoffeesEO.index(); /** * This is the default constructor (do not remove). */ public SuppliersEOImpl() { } /** * @return the definition object for this instance class. */ public static synchronized EntityDefImpl getDefinitionObject() { return EntityDefImpl.findDefObject("model.entity.SuppliersEO"); } /** * Gets the attribute value for SupId, using the alias name SupId. * @return the value of SupId */ public Integer getSupId() { return (Integer)getAttributeInternal(SUPID); } /** * Sets <code>value</code> as the attribute value for SupId. * @param value value to set the SupId */ public void setSupId(Integer value) { setAttributeInternal(SUPID, value); } /** * Gets the attribute value for SupName, using the alias name SupName. * @return the value of SupName */ public String getSupName() { return (String)getAttributeInternal(SUPNAME); } /** * Sets <code>value</code> as the attribute value for SupName. * @param value value to set the SupName */ public void setSupName(String value) { setAttributeInternal(SUPNAME, value); } /** * Gets the attribute value for Street, using the alias name Street. * @return the value of Street */ public String getStreet() { return (String)getAttributeInternal(STREET); } /** * Sets <code>value</code> as the attribute value for Street. * @param value value to set the Street */ public void setStreet(String value) { setAttributeInternal(STREET, value); } /** * Gets the attribute value for City, using the alias name City. * @return the value of City */ public String getCity() { return (String)getAttributeInternal(CITY); } /** * Sets <code>value</code> as the attribute value for City. * @param value value to set the City */ public void setCity(String value) { setAttributeInternal(CITY, value); } /** * Gets the attribute value for State, using the alias name State. * @return the value of State */ public String getState() { return (String)getAttributeInternal(STATE); } /** * Sets <code>value</code> as the attribute value for State. * @param value value to set the State */ public void setState(String value) { setAttributeInternal(STATE, value); } /** * Gets the attribute value for Zip, using the alias name Zip. * @return the value of Zip */ public String getZip() { return (String)getAttributeInternal(ZIP); } /** * Sets <code>value</code> as the attribute value for Zip. * @param value value to set the Zip */ public void setZip(String value) { setAttributeInternal(ZIP, value); } /** * getAttrInvokeAccessor: generated method. Do not modify. * @param index the index identifying the attribute * @param attrDef the attribute * @return the attribute value * @throws Exception */ protected Object getAttrInvokeAccessor(int index, AttributeDefImpl attrDef) throws Exception { if ((index >= AttributesEnum.firstIndex()) && (index < AttributesEnum.count())) { return AttributesEnum.staticValues()[index - AttributesEnum.firstIndex()].get(this); } return super.getAttrInvokeAccessor(index, attrDef); } /** * setAttrInvokeAccessor: generated method. Do not modify. * @param index the index identifying the attribute * @param value the value to assign to the attribute * @param attrDef the attribute * @throws Exception */ protected void setAttrInvokeAccessor(int index, Object value, AttributeDefImpl attrDef) throws Exception { if ((index >= AttributesEnum.firstIndex()) && (index < AttributesEnum.count())) { AttributesEnum.staticValues()[index - AttributesEnum.firstIndex()].put(this, value); return; } super.setAttrInvokeAccessor(index, value, attrDef); } /** * @return the associated entity oracle.jbo.RowIterator. */ public RowIterator getCoffeesEO() { return (RowIterator)getAttributeInternal(COFFEESEO); } /** * @param supId key constituent * @return a Key object based on given key constituents. */ public static Key createPrimaryKey(Integer supId) { return new Key(new Object[]{supId}); } }
92449fddd010937f945cf9537b9fe84afe1364b3
295
java
Java
swms-entity/src/main/java/me/zhengjie/mongo/primary/demo/dao/DemoTestMongoDao.java
dcduanchao/springboot-eladmin
825b2ac6215ae09695a19061ef6d4612dcf62038
[ "Apache-2.0" ]
null
null
null
swms-entity/src/main/java/me/zhengjie/mongo/primary/demo/dao/DemoTestMongoDao.java
dcduanchao/springboot-eladmin
825b2ac6215ae09695a19061ef6d4612dcf62038
[ "Apache-2.0" ]
null
null
null
swms-entity/src/main/java/me/zhengjie/mongo/primary/demo/dao/DemoTestMongoDao.java
dcduanchao/springboot-eladmin
825b2ac6215ae09695a19061ef6d4612dcf62038
[ "Apache-2.0" ]
null
null
null
17.352941
54
0.688136
1,003,077
package me.zhengjie.mongo.primary.demo.dao; import me.zhengjie.mongo.primary.demo.domain.DemoTest; import java.util.List; /** * @ Author :duanchao * @ Date : 14:59 2020/7/27 * @ Description: */ public interface DemoTestMongoDao { List<DemoTest> findByName(String name); }
9244a0c12b83ffcb82b4ae3a8f1acb611573bcc0
6,619
java
Java
src/main/java/UMainPack/UEmbeddedDB.java
goofyk/JStrunaBDRVITSK
e2cedcc90edf65e116d7f454329e5814a52a569f
[ "MIT" ]
null
null
null
src/main/java/UMainPack/UEmbeddedDB.java
goofyk/JStrunaBDRVITSK
e2cedcc90edf65e116d7f454329e5814a52a569f
[ "MIT" ]
null
null
null
src/main/java/UMainPack/UEmbeddedDB.java
goofyk/JStrunaBDRVITSK
e2cedcc90edf65e116d7f454329e5814a52a569f
[ "MIT" ]
null
null
null
33.770408
136
0.557939
1,003,078
package UMainPack; import javax.swing.table.TableModel; import java.sql.*; public class UEmbeddedDB { public static void main(String[] args) { connect(); createTableUsers(); createTableMatchStrunaBDRV(); //insertAdminDataToDB(); createTableDateTimeLoad(); getLastDateTimeLoad(); showData(); } static final String JDBC_DRIVER = "org.h2.Driver"; static final String FILENAME = "./DB/UStrunaBDRV"; static final String URL = "jdbc:h2:file:" + FILENAME; static final String USER = "sa"; static final String PASS = "123123"; private static Connection conn = null; static final String TABLE_MATCHES_ID = "MatchesIdStrunaBDRV"; static final String TABLE_DATETIME_LOAD = "DateTimeLoad"; public static boolean execute(String querySql){ boolean rs = true; try { Statement stmt = conn.createStatement(); rs = stmt.execute(querySql); } catch (SQLException e) { return false; } return rs; }; public static ResultSet executeQuery(String querySql){ ResultSet rs = null; try { Statement stmt = conn.createStatement(); rs = stmt.executeQuery(querySql); } catch (SQLException e) { ULogger.log.error(e.getMessage()); } return rs; }; public static void createTableUsers() { String sql = new String("CREATE TABLE IF NOT EXISTS Users(\n" + " USER_ID INT PRIMARY KEY AUTO_INCREMENT,\n" + " USERNAME VARCHAR(50) NOT NULL,\n" + " PASSWORD VARCHAR(150) NOT NULL,\n" + " );"); execute(sql); } public static void createTableMatchStrunaBDRV() { String sql = new String("CREATE TABLE IF NOT EXISTS " + TABLE_MATCHES_ID + "(\n" + " STRUNA_ID_OBJ VARCHAR(25) NOT NULL,\n" + " STRUNA_P_NAME VARCHAR(25) NOT NULL,\n" + " BDRV_P_MSD_ID VARCHAR(25)\n" + " );"); execute(sql); } public static void createTableDateTimeLoad() { String sql = new String("CREATE TABLE IF NOT EXISTS " + TABLE_DATETIME_LOAD + "(\n" + " ID INT PRIMARY KEY AUTO_INCREMENT,\n" + " DATETIMELOAD TIMESTAMP NOT NULL,\n" + " );"); execute(sql); } private static Connection connect() { try { conn = DriverManager.getConnection(URL, USER, PASS); } catch (SQLException e) { System.out.println(e.getMessage()); } return conn; } private static ResultSet showData(){ Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); String sql = new String("SELECT * FROM Users AS Users"); rs = stmt.executeQuery(sql); while(rs.next()){ String USER_ID = rs.getString("USER_ID"); String USERNAME = rs.getString("USERNAME"); String PASSWORD = rs.getString("PASSWORD"); System.out.println("USER_ID: " + USER_ID); System.out.println("USERNAME: " + USERNAME); System.out.println("PASSWORD: " + PASSWORD); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return rs; } public static void insertAdminDataToDB() { try{ conn.setAutoCommit(false); String sql = "INSERT INTO USERS(USERNAME, PASSWORD) VALUES (?,?)"; PreparedStatement pst = conn.prepareStatement(sql); String USERNAME = "Admin"; String PASSWORD = "123"; pst.setString(1, USERNAME); pst.setString(2, UCommon.md5(PASSWORD)); pst.addBatch(); pst.executeBatch(); conn.commit(); }catch(SQLException e){ e.printStackTrace(); } } public static void insertDataToTableMatchesFromTable(TableModel tableModel) { try{ conn.setAutoCommit(false); String sql = new String("INSERT INTO " + TABLE_MATCHES_ID + "(STRUNA_ID_OBJ, STRUNA_P_NAME, BDRV_P_MSD_ID) VALUES (?,?,?)"); int rowCount = tableModel.getRowCount(); PreparedStatement pst = conn.prepareStatement(sql); for(int row = 0; row < rowCount; row++){ String STRUNA_ID_OBJ = (String)tableModel.getValueAt(row, 0); String STRUNA_P_NAME = (String)tableModel.getValueAt(row, 1); String BDRV_P_MSD_ID = (String)tableModel.getValueAt(row, 2); pst.setString(1, STRUNA_ID_OBJ); pst.setString(2, STRUNA_P_NAME); pst.setString(3, BDRV_P_MSD_ID); pst.addBatch(); } pst.executeBatch(); conn.commit(); }catch(SQLException e){ e.printStackTrace(); } } public static void insertDataToTableDateTimeLoad(Timestamp dateTimeLoad) { try{ conn.setAutoCommit(false); String sql = "INSERT INTO " + TABLE_DATETIME_LOAD + "(DATETIMELOAD) VALUES (?)"; PreparedStatement pst = conn.prepareStatement(sql); pst.setTimestamp(1, dateTimeLoad); pst.addBatch(); pst.executeBatch(); conn.commit(); }catch(SQLException e){ ULogger.log.error(e.getMessage()); e.printStackTrace(); } } public static void cleareTableMatchesId(){ cleareTable(TABLE_MATCHES_ID); }; private static void cleareTable(String tableName) { String sql = new String("DROP TABLE " + tableName + ";"); execute(sql); } public static ResultSet getAllDataMatches() { String sql = "SELECT * FROM " + TABLE_MATCHES_ID; ResultSet rs = executeQuery(sql); return rs; } public static Timestamp getLastDateTimeLoad() { String sql = "SELECT * FROM " + TABLE_DATETIME_LOAD; ResultSet rs = executeQuery(sql); Timestamp lastDateTime = new Timestamp(System.currentTimeMillis()); try { rs.last(); lastDateTime = rs.getTimestamp(1); } catch (SQLException e) { e.printStackTrace(); } return lastDateTime; } static { connect(); createTableUsers(); createTableMatchStrunaBDRV(); createTableDateTimeLoad(); } }