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
list
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
list
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
list
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
924092cd985f091ac8c3dc39609796f4ef80cce7
289
java
Java
karate-robot/src/test/java/robot/core/CallerRunner.java
xjc90s/karate
3b4de72abf93431d8c9fc9301d806c6b931df004
[ "MIT" ]
5,597
2017-02-09T03:11:57.000Z
2021-10-02T01:56:43.000Z
karate-robot/src/test/java/robot/core/CallerRunner.java
xjc90s/karate
3b4de72abf93431d8c9fc9301d806c6b931df004
[ "MIT" ]
1,627
2017-02-14T12:34:41.000Z
2021-10-02T02:25:23.000Z
karate-robot/src/test/java/robot/core/CallerRunner.java
xjc90s/karate
3b4de72abf93431d8c9fc9301d806c6b931df004
[ "MIT" ]
1,503
2017-02-08T21:45:39.000Z
2021-10-01T22:23:30.000Z
18.0625
64
0.750865
1,001,572
package robot.core; import com.intuit.karate.KarateOptions; import com.intuit.karate.junit4.Karate; import org.junit.runner.RunWith; /** * * @author pthomas3 */ @RunWith(Karate.class) @KarateOptions(features = "classpath:robot/core/caller.feature") public class CallerRunner { }
9240936848e83983070bbd322b9ccfa8ee29b0f5
7,286
java
Java
app/src/main/java/com/example/leonardo/watermeter/utils/UploadTask.java
haonanshang/WaterMeter
622d1a030862fe5459bcc17b6b6e16ddc9b42e95
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/leonardo/watermeter/utils/UploadTask.java
haonanshang/WaterMeter
622d1a030862fe5459bcc17b6b6e16ddc9b42e95
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/leonardo/watermeter/utils/UploadTask.java
haonanshang/WaterMeter
622d1a030862fe5459bcc17b6b6e16ddc9b42e95
[ "Apache-2.0" ]
null
null
null
38.962567
107
0.61378
1,001,573
package com.example.leonardo.watermeter.utils; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; import com.example.leonardo.watermeter.entity.DetailData; import com.example.leonardo.watermeter.entity.UploadTaskBean; import com.example.leonardo.watermeter.ui.MonthListViewActivity; import org.ksoap2.SoapEnvelope; import org.ksoap2.SoapFault; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.litepal.LitePal; import java.util.ArrayList; import java.util.List; public class UploadTask extends AsyncTask<Void, Integer, Boolean> { public List<DetailData> uploadDataList; public MonthListViewActivity mcontext; public ProgressDialog uploadDialog; public int CurrentUploadIndex = 0; public int TotalUploadNum = 0; public boolean IsUpload = false; int uploadNum = 1; int publishProgressNum = 0; int currentUploadNum = 0; public UploadTask(List<DetailData> uploadDataList, MonthListViewActivity mcontext, int uploadNum) { this.uploadDataList = uploadDataList; this.mcontext = mcontext; TotalUploadNum = uploadDataList.size(); this.uploadNum = uploadNum; IsUpload = true; } /*使用Soap上传信息*/ public String uploadTask(String taskList, String imgBase64String, Context context) { //命名空间 String nameSpace = "http://controller.wc.modules.vmrc.com/"; //调用的方法名 String methodName = "uploadTask"; //EndPoint //String endPoint = "http://106.14.33.55:8080/services/webService?wsdl"; String endPoint = "http://" + new SharedPreUtils().GetIp(context) + "/services/webService?wsdl"; //SOAP Action String soapAction = "http://controller.wc.modules.vmrc.com/uploadTask"; //指定WebService的命名空间和调用的方法名 SoapObject rpc = new SoapObject(nameSpace, methodName); //创建HttpTransportSE对象,传递WebService服务器地址 rpc.addProperty("taskList", taskList); rpc.addProperty("imgBase64String", imgBase64String); //生成调用WebService方法的SOAP请求信息,并指定SOAP的版本 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.bodyOut = rpc; // 等价于envelope.bodyOut = rpc; //envelope.setOutputSoapObject(rpc); // 设置是否调用的是dotNet开发的WebService envelope.dotNet = false; HttpTransportSE transport = new HttpTransportSE(endPoint); transport.debug = true; try { // 调用WebService transport.call(soapAction, envelope); } catch (Exception e) { e.printStackTrace(); } // 获取返回的数据 if (envelope.bodyIn instanceof SoapFault) { final SoapFault sf = (SoapFault) envelope.bodyIn; System.out.println("检测--soap调用的返回结果是:" + sf.faultstring); System.out.println("检测--soap调用的返回结果是[全集]:" + sf.toString()); return sf.faultstring; } else { if (envelope.bodyIn != null) { //还不知道咋办 SoapObject object = (SoapObject) envelope.bodyIn; String result = object.getProperty(0).toString(); System.out.println("检测--第二种情况,结果是:" + result); return result; } else { return ""; } } } @Override protected void onPreExecute() { super.onPreExecute(); uploadDialog = new ProgressDialog(mcontext); uploadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); uploadDialog.setTitle("上传进度"); uploadDialog.setMessage("上传进行中,请勿进行其他操作!"); uploadDialog.setCancelable(false); //取消当前上传进度 uploadDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { CancelUpload(false); } return false; } }); uploadDialog.setMax(TotalUploadNum); uploadDialog.setProgress(0); uploadDialog.show(); } @Override protected Boolean doInBackground(Void... voids) { System.out.println("上传的数据总数为:" + uploadDataList.size()); List<DetailData> uploadCurrentList = new ArrayList<>(); for (int i = 0; i < uploadDataList.size(); i++) { if (IsUpload) { System.out.println("uploadCurrentList的size为:" + uploadCurrentList.size()); System.out.println("开始上传第 " + i + " 条数据"); uploadCurrentList.add(uploadDataList.get(i)); if (uploadCurrentList.size() == uploadNum || i == TotalUploadNum - 1) { currentUploadNum = uploadCurrentList.size(); publishProgressNum += currentUploadNum; UploadTaskBean bean = new JsonDataUtils().GetJsonString(uploadCurrentList, mcontext); String result = uploadTask(bean.getTaskList(), bean.getImgBase64String(), mcontext); Log.e("zksy", "上传结果为:" + result); if (result.equals("true")) { for (DetailData currentData : uploadCurrentList) { ContentValues values = new ContentValues(); values.put("isUpload", "0"); LitePal.updateAll(DetailData.class, values, "t_id = ?", currentData.getT_id()); CurrentUploadIndex += 1; } } uploadCurrentList.clear(); publishProgress(publishProgressNum); } } else { System.out.println("上传中断,当前上传进度为:" + CurrentUploadIndex); break; } } return IsUpload; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); System.out.println("----当前进度条为:" + values[0]); uploadDialog.setProgress(values[0]); } @Override protected void onPostExecute(Boolean aVoid) { super.onPostExecute(aVoid); System.out.println("上传结束"); System.out.println("CurrentUploadIndex的下标为:" + CurrentUploadIndex); if (aVoid) { if (CurrentUploadIndex == TotalUploadNum) { Toast.makeText(mcontext, "上传数据成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mcontext, "上传数据部分失败,请检查表册信息", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(mcontext, "上传数据中断", Toast.LENGTH_SHORT).show(); } publishProgressNum = 0; currentUploadNum = 0; CurrentUploadIndex = 0; TotalUploadNum = 0; uploadDialog.dismiss(); mcontext.TaskResult(); } public void CancelUpload(boolean iscancel) { IsUpload = iscancel; } }
9240937bfe38ada1bfc72f4e030724229060b5d2
5,849
java
Java
src/org/zaproxy/zap/extension/option/OptionsLocalePanel.java
magnologan/zaproxy
a7022719a0998b0604268a2af452a79ef630d63a
[ "Apache-2.0" ]
2
2018-06-12T14:13:39.000Z
2018-08-29T02:16:28.000Z
src/org/zaproxy/zap/extension/option/OptionsLocalePanel.java
ikarius6/zaproxy
8daa6845af61f5662036af10e4abfad46de87b1d
[ "ECL-2.0", "Apache-2.0", "BSD-3-Clause" ]
1
2018-06-12T13:55:16.000Z
2018-06-12T15:27:59.000Z
src/org/zaproxy/zap/extension/option/OptionsLocalePanel.java
j4nnis/bproxy
5acf3e50ccee750de3d42f0bcbc7925b1e2f7401
[ "Apache-2.0" ]
1
2021-09-03T07:02:26.000Z
2021-09-03T07:02:26.000Z
31.616216
95
0.688152
1,001,574
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2010 [email protected] * * 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.zaproxy.zap.extension.option; import java.awt.CardLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import org.parosproxy.paros.Constant; import org.parosproxy.paros.model.OptionsParam; import org.parosproxy.paros.view.AbstractParamPanel; import org.zaproxy.zap.utils.LocaleUtils; import org.zaproxy.zap.view.ViewLocale; public class OptionsLocalePanel extends AbstractParamPanel { private static final long serialVersionUID = 1L; private JPanel panelMisc = null; private JComboBox<ViewLocale> localeSelect = null; private JLabel localeLabel = null; private JLabel localeChangeLabel = null; public OptionsLocalePanel() { super(); initialize(); } /** * This method initializes this */ private void initialize() { this.setLayout(new CardLayout()); this.setName(Constant.messages.getString("view.options.title")); this.add(getPanelMisc(), getPanelMisc().getName()); } /** * This method initializes panelMisc * * @return javax.swing.JPanel */ private JPanel getPanelMisc() { if (panelMisc == null) { panelMisc = new JPanel(); panelMisc.setLayout(new GridBagLayout()); panelMisc.setSize(114, 132); panelMisc.setName(Constant.messages.getString("view.options.misc.title")); GridBagConstraints gbc0 = new GridBagConstraints(); GridBagConstraints gbc1_0 = new GridBagConstraints(); GridBagConstraints gbc1_1 = new GridBagConstraints(); GridBagConstraints gbc2 = new GridBagConstraints(); GridBagConstraints gbcX = new GridBagConstraints(); gbc0.gridx = 0; gbc0.gridy = 0; gbc0.ipadx = 0; gbc0.ipady = 0; gbc0.insets = new java.awt.Insets(2,2,2,2); gbc0.anchor = java.awt.GridBagConstraints.NORTHWEST; gbc0.fill = java.awt.GridBagConstraints.HORIZONTAL; gbc0.weightx = 1.0D; gbc0.gridwidth = 2; gbc1_0.gridx = 0; gbc1_0.gridy = 1; gbc1_0.ipadx = 0; gbc1_0.ipady = 0; gbc1_0.insets = new java.awt.Insets(2,2,2,2); gbc1_0.anchor = java.awt.GridBagConstraints.NORTHWEST; gbc1_0.fill = java.awt.GridBagConstraints.HORIZONTAL; gbc1_0.weightx = 1.0D; gbc1_1.gridx = 1; gbc1_1.gridy = 1; gbc1_1.ipadx = 0; gbc1_1.ipady = 0; gbc1_1.insets = new java.awt.Insets(2,2,2,2); gbc1_1.anchor = java.awt.GridBagConstraints.NORTHWEST; gbc1_1.fill = java.awt.GridBagConstraints.HORIZONTAL; gbc1_1.weightx = 1.0D; gbc2.gridx = 0; gbc2.gridy = 2; gbc2.ipadx = 0; gbc2.ipady = 0; gbc2.insets = new java.awt.Insets(2,2,2,2); gbc2.anchor = java.awt.GridBagConstraints.NORTHWEST; gbc2.fill = java.awt.GridBagConstraints.HORIZONTAL; gbc2.weightx = 1.0D; gbc2.weighty = 1.0D; gbc2.gridwidth = 2; gbcX.gridx = 0; gbcX.gridy = 3; gbcX.ipadx = 0; gbcX.ipady = 0; gbcX.insets = new java.awt.Insets(2,2,2,2); gbcX.anchor = java.awt.GridBagConstraints.NORTHWEST; gbcX.fill = java.awt.GridBagConstraints.HORIZONTAL; gbcX.weightx = 1.0D; gbcX.weighty = 1.0D; localeLabel = new JLabel(Constant.messages.getString("locale.options.label.language")); localeChangeLabel = new JLabel(Constant.messages.getString("locale.options.label.change")); panelMisc.add(localeLabel, gbc1_0); panelMisc.add(getLocaleSelect(), gbc1_1); panelMisc.add(localeChangeLabel, gbc2); panelMisc.add(new JLabel(), gbcX); } return panelMisc; } private JComboBox<ViewLocale> getLocaleSelect() { if (localeSelect == null) { localeSelect = new JComboBox<>(); for (ViewLocale locale : LocaleUtils.getAvailableViewLocales()) { localeSelect.addItem(locale); } localeSelect.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Change to use the selected language in the dialog ViewLocale selectedLocale = (ViewLocale) localeSelect.getSelectedItem(); if (selectedLocale != null) { Constant.setLocale(selectedLocale.getLocale()); localeLabel.setText(Constant.messages.getString("locale.options.label.language")); localeChangeLabel.setText(Constant.messages.getString("locale.options.label.change")); } }}); } return localeSelect; } @Override public void initParam(Object obj) { } @Override public void validateParam(Object obj) { // no validation needed } @Override public void saveParam (Object obj) throws Exception { OptionsParam options = (OptionsParam) obj; ViewLocale selectedLocale = (ViewLocale) localeSelect.getSelectedItem(); if (selectedLocale != null) { options.getViewParam().setLocale(selectedLocale.getLocale()); } } @Override public String getHelpIndex() { // TODO no help page? return "ui.dialogs.options.locale"; } }
9240938b434ca770beb5ddf9821828e8367cf25c
533
java
Java
modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithInnerClass.java
cakemail/swagger-core
f7e55e62976d991a2bcc9651b999527cb7c7c500
[ "Apache-2.0" ]
1
2015-11-23T19:52:48.000Z
2015-11-23T19:52:48.000Z
modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithInnerClass.java
cakemail/swagger-core
f7e55e62976d991a2bcc9651b999527cb7c7c500
[ "Apache-2.0" ]
null
null
null
modules/swagger-jaxrs/src/test/java/io/swagger/resources/ResourceWithInnerClass.java
cakemail/swagger-core
f7e55e62976d991a2bcc9651b999527cb7c7c500
[ "Apache-2.0" ]
3
2018-03-20T10:35:51.000Z
2021-02-04T18:31:21.000Z
24.227273
123
0.727955
1,001,575
package io.swagger.resources; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.models.Namespace.Description; import javax.ws.rs.GET; import javax.ws.rs.Path; import java.util.List; @Api("/basic") @Path("/") public class ResourceWithInnerClass { @GET @Path("/description") @ApiOperation(value = "Get list of instances of inner class", response = Description.class, responseContainer = "list") public List<Description> getDescription() { return null; } }
924093ce1610f5244577e742ac7f6920d9633f7c
6,154
java
Java
visionSamples/CameraApplication/app/src/main/java/com/example/cameraapplication/MainActivity.java
NancySoni/CameraApplication
b3b36b1c1852852c056b743c99f9790e0152ee8e
[ "Apache-2.0" ]
null
null
null
visionSamples/CameraApplication/app/src/main/java/com/example/cameraapplication/MainActivity.java
NancySoni/CameraApplication
b3b36b1c1852852c056b743c99f9790e0152ee8e
[ "Apache-2.0" ]
null
null
null
visionSamples/CameraApplication/app/src/main/java/com/example/cameraapplication/MainActivity.java
NancySoni/CameraApplication
b3b36b1c1852852c056b743c99f9790e0152ee8e
[ "Apache-2.0" ]
null
null
null
38.704403
133
0.61261
1,001,576
package com.example.cameraapplication; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.soundcloud.android.crop.Crop; import java.io.File; import java.io.IOException; public class MainActivity extends AppCompatActivity { Button click; ImageView imageView; GeneralUtils generalUtils; static final int RESULT_LOAD_IMAGE = 2; static final int REQUEST_IMAGE_CAPTURE = 1; Bitmap imageBitmap; String customer_img; Bitmap resized; Uri path; private Uri finalImageUrl; // @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); click=findViewById(R.id.take_photo); imageView=findViewById(R.id.captured_image); click.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { selectImage(); } }); } private void selectImage() { final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"}; AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Add Photo!"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (options[item].equals("Take Photo")) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } // Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg"); // intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); // startActivityForResult(intent, 1); } else if (options[item].equals("Choose from Gallery")) { // Crop.pickImage(BasicProfile.this); Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); Crop.pickImage(MainActivity.this); Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, RESULT_LOAD_IMAGE); // Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // startActivityForResult(intent, ); } else if (options[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); generalUtils.checkPermission(this); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { try { Bundle extras = data.getExtras(); imageBitmap = (Bitmap) extras.get("data"); Toast.makeText(MainActivity.this,"this is the change i made",Toast.LENGTH_LONG).show(); finalImageUrl = new GeneralUtils().getImageResizedUri(this, imageBitmap); imageView.setImageBitmap(imageBitmap); // System.out.println("AT CAMERA--->" + finalImageUrl); } catch (Exception e) { e.printStackTrace(); } resized = Bitmap.createScaledBitmap(imageBitmap, 600, 600, true); } else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) { beginCrop(data.getData()); finalImageUrl = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), finalImageUrl); // Log.d(TAG, String.valueOf(bitmap)); finalImageUrl=new GeneralUtils().getImageResizedUri(MainActivity.this, bitmap); imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } else if(requestCode == Crop.REQUEST_CROP) { handleCrop(resultCode, data); } } private void beginCrop(Uri source) { Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped")); Crop.of(source, destination).withAspect(600, 600).start(this); } private void handleCrop(int resultCode, Intent result) { try { if (resultCode == RESULT_OK) { imageBitmap = BitmapFactory .decodeStream(getContentResolver().openInputStream( Crop.getOutput(result))); // imageBitmap=MediaStore.Images.Media.getBitmap(getContentResolver(),path); imageView.setImageBitmap(imageBitmap); Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 600, 600, false); // Handle Your Bitmap here } else if (resultCode == Crop.RESULT_ERROR) { Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
924094af41b60a83aebde2c1f078d5092f81577e
217
java
Java
src/main/java/com/konoplyanikovd/interview/design/pattern/factorymethod/Fish.java
konoplyanikovd/JCSprout
7b3b8ca646732272c52ef95c5bd4a3cbdbb5a9e4
[ "MIT" ]
null
null
null
src/main/java/com/konoplyanikovd/interview/design/pattern/factorymethod/Fish.java
konoplyanikovd/JCSprout
7b3b8ca646732272c52ef95c5bd4a3cbdbb5a9e4
[ "MIT" ]
null
null
null
src/main/java/com/konoplyanikovd/interview/design/pattern/factorymethod/Fish.java
konoplyanikovd/JCSprout
7b3b8ca646732272c52ef95c5bd4a3cbdbb5a9e4
[ "MIT" ]
null
null
null
19.727273
66
0.686636
1,001,577
package com.konoplyanikovd.interview.design.pattern.factorymethod; public class Fish extends Animal { @Override protected void desc() { System.out.println("fish name is=" + this.getName()); } }
924094b2eb7c4da3823e16c599eba9de2da06182
151
java
Java
src/main/java/enums/Description.java
norimoji/mojimusic
0b9c7a07de9d5ff2dc6343fb7162cdc5d75b404e
[ "Apache-2.0" ]
null
null
null
src/main/java/enums/Description.java
norimoji/mojimusic
0b9c7a07de9d5ff2dc6343fb7162cdc5d75b404e
[ "Apache-2.0" ]
null
null
null
src/main/java/enums/Description.java
norimoji/mojimusic
0b9c7a07de9d5ff2dc6343fb7162cdc5d75b404e
[ "Apache-2.0" ]
null
null
null
12.583333
36
0.682119
1,001,578
package enums; /** * Created by Huy on 21/01/2017. */ @FunctionalInterface public interface Description<X, T> { T getDescription(X target); }
924094b42e674f2ff5e8873010b2aaba3f09e5aa
81,618
java
Java
javatests/com/google/gerrit/acceptance/git/AbstractPushForReview.java
luismbo/gerrit
7d35ff3fbeddc22fd2e0b42ff3f971598bba0c25
[ "Apache-2.0" ]
479
2015-07-21T01:05:49.000Z
2022-02-10T07:02:21.000Z
javatests/com/google/gerrit/acceptance/git/AbstractPushForReview.java
tazmanian60/gerrit
7d35ff3fbeddc22fd2e0b42ff3f971598bba0c25
[ "Apache-2.0" ]
1
2016-02-25T16:50:20.000Z
2016-02-25T16:50:20.000Z
javatests/com/google/gerrit/acceptance/git/AbstractPushForReview.java
tazmanian60/gerrit
7d35ff3fbeddc22fd2e0b42ff3f971598bba0c25
[ "Apache-2.0" ]
171
2015-04-04T07:07:04.000Z
2022-03-18T20:43:22.000Z
38.530439
100
0.681479
1,001,579
// Copyright (C) 2013 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.google.gerrit.acceptance.git; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.TruthJUnit.assume; import static com.google.gerrit.acceptance.GitUtil.assertPushOk; import static com.google.gerrit.acceptance.GitUtil.assertPushRejected; import static com.google.gerrit.acceptance.GitUtil.pushHead; import static com.google.gerrit.acceptance.PushOneCommit.FILE_NAME; import static com.google.gerrit.common.FooterConstants.CHANGE_ID; import static com.google.gerrit.extensions.client.ListChangesOption.ALL_REVISIONS; import static com.google.gerrit.extensions.client.ListChangesOption.CURRENT_REVISION; import static com.google.gerrit.extensions.client.ListChangesOption.DETAILED_ACCOUNTS; import static com.google.gerrit.extensions.client.ListChangesOption.DETAILED_LABELS; import static com.google.gerrit.extensions.client.ListChangesOption.MESSAGES; import static com.google.gerrit.extensions.common.testing.EditInfoSubject.assertThat; import static com.google.gerrit.server.git.receive.ReceiveConstants.PUSH_OPTION_SKIP_VALIDATION; import static com.google.gerrit.server.group.SystemGroupBackend.ANONYMOUS_USERS; import static com.google.gerrit.server.project.testing.Util.category; import static com.google.gerrit.server.project.testing.Util.value; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Streams; import com.google.gerrit.acceptance.AbstractDaemonTest; import com.google.gerrit.acceptance.GerritConfig; import com.google.gerrit.acceptance.GitUtil; import com.google.gerrit.acceptance.PushOneCommit; import com.google.gerrit.acceptance.Sandboxed; import com.google.gerrit.acceptance.TestAccount; import com.google.gerrit.acceptance.TestProjectInput; import com.google.gerrit.common.data.LabelType; import com.google.gerrit.common.data.Permission; import com.google.gerrit.extensions.api.changes.DraftInput; import com.google.gerrit.extensions.api.changes.NotifyHandling; import com.google.gerrit.extensions.api.changes.ReviewInput; import com.google.gerrit.extensions.api.projects.BranchInput; import com.google.gerrit.extensions.client.ChangeStatus; import com.google.gerrit.extensions.client.GeneralPreferencesInfo; import com.google.gerrit.extensions.client.InheritableBoolean; import com.google.gerrit.extensions.client.ListChangesOption; import com.google.gerrit.extensions.client.ProjectWatchInfo; import com.google.gerrit.extensions.client.ReviewerState; import com.google.gerrit.extensions.client.Side; import com.google.gerrit.extensions.common.ChangeInfo; import com.google.gerrit.extensions.common.ChangeMessageInfo; import com.google.gerrit.extensions.common.CommentInfo; import com.google.gerrit.extensions.common.EditInfo; import com.google.gerrit.extensions.common.LabelInfo; import com.google.gerrit.extensions.common.RevisionInfo; import com.google.gerrit.extensions.common.testing.EditInfoSubject; import com.google.gerrit.reviewdb.client.AccountGroup; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.ChangeMessage; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.client.RefNames; import com.google.gerrit.server.ChangeMessagesUtil; import com.google.gerrit.server.git.ProjectConfig; import com.google.gerrit.server.git.receive.ReceiveConstants; import com.google.gerrit.server.group.SystemGroupBackend; import com.google.gerrit.server.mail.Address; import com.google.gerrit.server.project.testing.Util; import com.google.gerrit.server.query.change.ChangeData; import com.google.gerrit.testing.FakeEmailSender.Message; import com.google.gerrit.testing.TestTimeUtil; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.RefUpdate.Result; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public abstract class AbstractPushForReview extends AbstractDaemonTest { protected enum Protocol { // TODO(dborowitz): TEST. SSH, HTTP } private LabelType patchSetLock; @BeforeClass public static void setTimeForTesting() { TestTimeUtil.resetWithClockStep(1, SECONDS); } @AfterClass public static void restoreTime() { TestTimeUtil.useSystemTime(); } @Before public void setUp() throws Exception { ProjectConfig cfg = projectCache.checkedGet(project).getConfig(); patchSetLock = Util.patchSetLock(); cfg.getLabelSections().put(patchSetLock.getName(), patchSetLock); AccountGroup.UUID anonymousUsers = systemGroupBackend.getGroup(ANONYMOUS_USERS).getUUID(); Util.allow( cfg, Permission.forLabel(patchSetLock.getName()), 0, 1, anonymousUsers, "refs/heads/*"); saveProjectConfig(cfg); grant(project, "refs/heads/*", Permission.LABEL + "Patch-Set-Lock"); } @After public void tearDown() throws Exception { setApiUser(admin); GeneralPreferencesInfo prefs = gApi.accounts().id(admin.id.get()).getPreferences(); prefs.publishCommentsOnPush = false; gApi.accounts().id(admin.id.get()).setPreferences(prefs); } protected void selectProtocol(Protocol p) throws Exception { String url; switch (p) { case SSH: url = adminSshSession.getUrl(); break; case HTTP: url = admin.getHttpUrl(server); break; default: throw new IllegalArgumentException("unexpected protocol: " + p); } testRepo = GitUtil.cloneProject(project, url + "/" + project.get()); } @Test public void pushForMaster() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); r.assertChange(Change.Status.NEW, null); } @Test @TestProjectInput(createEmptyCommit = false) public void pushInitialCommitForMasterBranch() throws Exception { RevCommit c = testRepo.commit().message("Initial commit").insertChangeId().create(); String id = GitUtil.getChangeId(testRepo, c).get(); testRepo.reset(c); String r = "refs/for/master"; PushResult pr = pushHead(testRepo, r, false); assertPushOk(pr, r); ChangeInfo change = gApi.changes().id(id).info(); assertThat(change.branch).isEqualTo("master"); assertThat(change.status).isEqualTo(ChangeStatus.NEW); try (Repository repo = repoManager.openRepository(project)) { assertThat(repo.resolve("master")).isNull(); } gApi.changes().id(change.id).current().review(ReviewInput.approve()); gApi.changes().id(change.id).current().submit(); try (Repository repo = repoManager.openRepository(project)) { assertThat(repo.resolve("master")).isEqualTo(c); } } @Test public void pushInitialCommitForRefsMetaConfigBranch() throws Exception { // delete refs/meta/config try (Repository repo = repoManager.openRepository(project); RevWalk rw = new RevWalk(repo)) { RefUpdate u = repo.updateRef(RefNames.REFS_CONFIG); u.setForceUpdate(true); u.setExpectedOldObjectId(repo.resolve(RefNames.REFS_CONFIG)); assertThat(u.delete(rw)).isEqualTo(Result.FORCED); } RevCommit c = testRepo .commit() .message("Initial commit") .author(admin.getIdent()) .committer(admin.getIdent()) .insertChangeId() .create(); String id = GitUtil.getChangeId(testRepo, c).get(); testRepo.reset(c); String r = "refs/for/" + RefNames.REFS_CONFIG; PushResult pr = pushHead(testRepo, r, false); assertPushOk(pr, r); ChangeInfo change = gApi.changes().id(id).info(); assertThat(change.branch).isEqualTo(RefNames.REFS_CONFIG); assertThat(change.status).isEqualTo(ChangeStatus.NEW); try (Repository repo = repoManager.openRepository(project)) { assertThat(repo.resolve(RefNames.REFS_CONFIG)).isNull(); } gApi.changes().id(change.id).current().review(ReviewInput.approve()); gApi.changes().id(change.id).current().submit(); try (Repository repo = repoManager.openRepository(project)) { assertThat(repo.resolve(RefNames.REFS_CONFIG)).isEqualTo(c); } } @Test public void pushInitialCommitForNormalNonExistingBranchFails() throws Exception { RevCommit c = testRepo .commit() .message("Initial commit") .author(admin.getIdent()) .committer(admin.getIdent()) .insertChangeId() .create(); testRepo.reset(c); String r = "refs/for/foo"; PushResult pr = pushHead(testRepo, r, false); assertPushRejected(pr, r, "branch foo not found"); try (Repository repo = repoManager.openRepository(project)) { assertThat(repo.resolve("foo")).isNull(); } } @Test public void output() throws Exception { String url = canonicalWebUrl.get() + "#/c/" + project.get() + "/+/"; ObjectId initialHead = testRepo.getRepository().resolve("HEAD"); PushOneCommit.Result r1 = pushTo("refs/for/master"); Change.Id id1 = r1.getChange().getId(); r1.assertOkStatus(); r1.assertChange(Change.Status.NEW, null); r1.assertMessage( "New changes:\n " + url + id1 + " " + r1.getCommit().getShortMessage() + "\n"); testRepo.reset(initialHead); String newMsg = r1.getCommit().getShortMessage() + " v2"; testRepo .branch("HEAD") .commit() .message(newMsg) .insertChangeId(r1.getChangeId().substring(1)) .create(); PushOneCommit.Result r2 = pushFactory .create(db, admin.getIdent(), testRepo, "another commit", "b.txt", "bbb") .to("refs/for/master"); Change.Id id2 = r2.getChange().getId(); r2.assertOkStatus(); r2.assertChange(Change.Status.NEW, null); r2.assertMessage( "New changes:\n" + " " + url + id2 + " another commit\n" + "\n" + "\n" + "Updated changes:\n" + " " + url + id1 + " " + newMsg + "\n"); } @Test public void autoclose() throws Exception { // Create a change PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); // Force push it, closing it String master = "refs/heads/master"; assertPushOk(pushHead(testRepo, master, false), master); // Attempt to push amended commit to same change String url = canonicalWebUrl.get() + "#/c/" + project.get() + "/+/" + r.getChange().getId(); r = amendChange(r.getChangeId(), "refs/for/master"); r.assertErrorStatus("change " + url + " closed"); } @Test public void pushForMasterWithTopic() throws Exception { // specify topic in ref String topic = "my/topic"; PushOneCommit.Result r = pushTo("refs/for/master/" + topic); r.assertOkStatus(); r.assertChange(Change.Status.NEW, topic); // specify topic as option r = pushTo("refs/for/master%topic=" + topic); r.assertOkStatus(); r.assertChange(Change.Status.NEW, topic); } @Test public void pushForMasterWithTopicOption() throws Exception { String topicOption = "topic=myTopic"; List<String> pushOptions = new ArrayList<>(); pushOptions.add(topicOption); PushOneCommit push = pushFactory.create(db, admin.getIdent(), testRepo); push.setPushOptions(pushOptions); PushOneCommit.Result r = push.to("refs/for/master"); r.assertOkStatus(); r.assertChange(Change.Status.NEW, "myTopic"); r.assertPushOptions(pushOptions); } @Test public void pushForMasterWithTopicInRefExceedLimitFails() throws Exception { String topic = Stream.generate(() -> "t").limit(2049).collect(Collectors.joining()); PushOneCommit.Result r = pushTo("refs/for/master/" + topic); r.assertErrorStatus("topic length exceeds the limit (2048)"); } @Test public void pushForMasterWithTopicAsOptionExceedLimitFails() throws Exception { String topic = Stream.generate(() -> "t").limit(2049).collect(Collectors.joining()); PushOneCommit.Result r = pushTo("refs/for/master%topic=" + topic); r.assertErrorStatus("topic length exceeds the limit (2048)"); } @Test public void pushForMasterWithNotify() throws Exception { // create a user that watches the project TestAccount user3 = accountCreator.create("user3", "[email protected]", "User3"); List<ProjectWatchInfo> projectsToWatch = new ArrayList<>(); ProjectWatchInfo pwi = new ProjectWatchInfo(); pwi.project = project.get(); pwi.filter = "*"; pwi.notifyNewChanges = true; projectsToWatch.add(pwi); setApiUser(user3); gApi.accounts().self().setWatchedProjects(projectsToWatch); TestAccount user2 = accountCreator.user2(); String pushSpec = "refs/for/master%reviewer=" + user.email + ",cc=" + user2.email; sender.clear(); PushOneCommit.Result r = pushTo(pushSpec + ",notify=" + NotifyHandling.NONE); r.assertOkStatus(); assertThat(sender.getMessages()).isEmpty(); sender.clear(); r = pushTo(pushSpec + ",notify=" + NotifyHandling.OWNER); r.assertOkStatus(); // no email notification about own changes assertThat(sender.getMessages()).isEmpty(); sender.clear(); r = pushTo(pushSpec + ",notify=" + NotifyHandling.OWNER_REVIEWERS); r.assertOkStatus(); assertThat(sender.getMessages()).hasSize(1); Message m = sender.getMessages().get(0); assertThat(m.rcpt()).containsExactly(user.emailAddress); sender.clear(); r = pushTo(pushSpec + ",notify=" + NotifyHandling.ALL); r.assertOkStatus(); assertThat(sender.getMessages()).hasSize(1); m = sender.getMessages().get(0); assertThat(m.rcpt()).containsExactly(user.emailAddress, user2.emailAddress, user3.emailAddress); sender.clear(); r = pushTo(pushSpec + ",notify=" + NotifyHandling.NONE + ",notify-to=" + user3.email); r.assertOkStatus(); assertNotifyTo(user3); sender.clear(); r = pushTo(pushSpec + ",notify=" + NotifyHandling.NONE + ",notify-cc=" + user3.email); r.assertOkStatus(); assertNotifyCc(user3); sender.clear(); r = pushTo(pushSpec + ",notify=" + NotifyHandling.NONE + ",notify-bcc=" + user3.email); r.assertOkStatus(); assertNotifyBcc(user3); // request that sender gets notified as TO, CC and BCC, email should be sent // even if the sender is the only recipient sender.clear(); r = pushTo(pushSpec + ",notify=" + NotifyHandling.NONE + ",notify-to=" + admin.email); assertNotifyTo(admin); sender.clear(); r = pushTo(pushSpec + ",notify=" + NotifyHandling.NONE + ",notify-cc=" + admin.email); r.assertOkStatus(); assertNotifyCc(admin); sender.clear(); r = pushTo(pushSpec + ",notify=" + NotifyHandling.NONE + ",notify-bcc=" + admin.email); r.assertOkStatus(); assertNotifyBcc(admin); } @Test public void pushForMasterWithCc() throws Exception { // cc one user String topic = "my/topic"; PushOneCommit.Result r = pushTo("refs/for/master/" + topic + "%cc=" + user.email); r.assertOkStatus(); r.assertChange(Change.Status.NEW, topic, ImmutableList.of(), ImmutableList.of(user)); // cc several users r = pushTo( "refs/for/master/" + topic + "%cc=" + admin.email + ",cc=" + user.email + ",cc=" + accountCreator.user2().email); r.assertOkStatus(); // Check that admin isn't CC'd as they own the change r.assertChange( Change.Status.NEW, topic, ImmutableList.of(), ImmutableList.of(user, accountCreator.user2())); // cc non-existing user String nonExistingEmail = "[email protected]"; r = pushTo( "refs/for/master/" + topic + "%cc=" + admin.email + ",cc=" + nonExistingEmail + ",cc=" + user.email); r.assertErrorStatus("user \"" + nonExistingEmail + "\" not found"); } @Test public void pushForMasterWithReviewer() throws Exception { // add one reviewer String topic = "my/topic"; PushOneCommit.Result r = pushTo("refs/for/master/" + topic + "%r=" + user.email); r.assertOkStatus(); r.assertChange(Change.Status.NEW, topic, user); // add several reviewers TestAccount user2 = accountCreator.create("another-user", "[email protected]", "Another User"); r = pushTo( "refs/for/master/" + topic + "%r=" + admin.email + ",r=" + user.email + ",r=" + user2.email); r.assertOkStatus(); // admin is the owner of the change and should not appear as reviewer r.assertChange(Change.Status.NEW, topic, user, user2); // add non-existing user as reviewer String nonExistingEmail = "[email protected]"; r = pushTo( "refs/for/master/" + topic + "%r=" + admin.email + ",r=" + nonExistingEmail + ",r=" + user.email); r.assertErrorStatus("user \"" + nonExistingEmail + "\" not found"); } @Test public void pushPrivateChange() throws Exception { // Push a private change. PushOneCommit.Result r = pushTo("refs/for/master%private"); r.assertOkStatus(); r.assertMessage(" [PRIVATE]"); assertThat(r.getChange().change().isPrivate()).isTrue(); // Pushing a new patch set without --private doesn't remove the privacy flag from the change. r = amendChange(r.getChangeId(), "refs/for/master"); r.assertOkStatus(); r.assertMessage(" [PRIVATE]"); assertThat(r.getChange().change().isPrivate()).isTrue(); // Remove the privacy flag from the change. r = amendChange(r.getChangeId(), "refs/for/master%remove-private"); r.assertOkStatus(); r.assertNotMessage(" [PRIVATE]"); assertThat(r.getChange().change().isPrivate()).isFalse(); // Normal push: privacy flag is not added back. r = amendChange(r.getChangeId(), "refs/for/master"); r.assertOkStatus(); r.assertNotMessage(" [PRIVATE]"); assertThat(r.getChange().change().isPrivate()).isFalse(); // Make the change private again. r = pushTo("refs/for/master%private"); r.assertOkStatus(); r.assertMessage(" [PRIVATE]"); assertThat(r.getChange().change().isPrivate()).isTrue(); // Can't use --private and --remove-private together. r = pushTo("refs/for/master%private,remove-private"); r.assertErrorStatus(); } @Test public void pushWorkInProgressChange() throws Exception { // Push a work-in-progress change. PushOneCommit.Result r = pushTo("refs/for/master%wip"); r.assertOkStatus(); r.assertMessage(" [WIP]"); assertThat(r.getChange().change().isWorkInProgress()).isTrue(); assertUploadTag(r.getChange(), ChangeMessagesUtil.TAG_UPLOADED_WIP_PATCH_SET); // Pushing a new patch set without --wip doesn't remove the wip flag from the change. r = amendChange(r.getChangeId(), "refs/for/master"); r.assertOkStatus(); r.assertMessage(" [WIP]"); assertThat(r.getChange().change().isWorkInProgress()).isTrue(); assertUploadTag(r.getChange(), ChangeMessagesUtil.TAG_UPLOADED_WIP_PATCH_SET); // Remove the wip flag from the change. r = amendChange(r.getChangeId(), "refs/for/master%ready"); r.assertOkStatus(); r.assertNotMessage(" [WIP]"); assertThat(r.getChange().change().isWorkInProgress()).isFalse(); assertUploadTag(r.getChange(), ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET); // Normal push: wip flag is not added back. r = amendChange(r.getChangeId(), "refs/for/master"); r.assertOkStatus(); r.assertNotMessage(" [WIP]"); assertThat(r.getChange().change().isWorkInProgress()).isFalse(); assertUploadTag(r.getChange(), ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET); // Make the change work-in-progress again. r = amendChange(r.getChangeId(), "refs/for/master%wip"); r.assertOkStatus(); r.assertMessage(" [WIP]"); assertThat(r.getChange().change().isWorkInProgress()).isTrue(); assertUploadTag(r.getChange(), ChangeMessagesUtil.TAG_UPLOADED_WIP_PATCH_SET); // Can't use --wip and --ready together. r = amendChange(r.getChangeId(), "refs/for/master%wip,ready"); r.assertErrorStatus(); } private void assertUploadTag(ChangeData cd, String expectedTag) throws Exception { List<ChangeMessage> msgs = cd.messages(); assertThat(msgs).isNotEmpty(); assertThat(Iterables.getLast(msgs).getTag()).isEqualTo(expectedTag); } @Test public void pushWorkInProgressChangeWhenNotOwner() throws Exception { TestRepository<?> userRepo = cloneProject(project, user); PushOneCommit.Result r = pushFactory.create(db, user.getIdent(), userRepo).to("refs/for/master%wip"); r.assertOkStatus(); assertThat(r.getChange().change().getOwner()).isEqualTo(user.id); assertThat(r.getChange().change().isWorkInProgress()).isTrue(); // Other user trying to move from WIP to ready should fail. GitUtil.fetch(testRepo, r.getPatchSet().getRefName() + ":ps"); testRepo.reset("ps"); r = amendChange(r.getChangeId(), "refs/for/master%ready", admin, testRepo); r.assertErrorStatus(ReceiveConstants.ONLY_OWNER_CAN_MODIFY_WIP); // Other user trying to move from WIP to WIP should succeed. r = amendChange(r.getChangeId(), "refs/for/master%wip", admin, testRepo); r.assertOkStatus(); assertThat(r.getChange().change().isWorkInProgress()).isTrue(); // Push as change owner to move change from WIP to ready. r = pushFactory.create(db, user.getIdent(), userRepo).to("refs/for/master%ready"); r.assertOkStatus(); assertThat(r.getChange().change().isWorkInProgress()).isFalse(); // Other user trying to move from ready to WIP should fail. GitUtil.fetch(testRepo, r.getPatchSet().getRefName() + ":ps"); testRepo.reset("ps"); r = amendChange(r.getChangeId(), "refs/for/master%wip", admin, testRepo); r.assertErrorStatus(ReceiveConstants.ONLY_OWNER_CAN_MODIFY_WIP); // Other user trying to move from ready to ready should succeed. r = amendChange(r.getChangeId(), "refs/for/master%ready", admin, testRepo); r.assertOkStatus(); } @Test public void pushForMasterAsEdit() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); Optional<EditInfo> edit = getEdit(r.getChangeId()); assertThat(edit).isAbsent(); assertThat(query("has:edit")).isEmpty(); // specify edit as option r = amendChange(r.getChangeId(), "refs/for/master%edit"); r.assertOkStatus(); edit = getEdit(r.getChangeId()); assertThat(edit).isPresent(); EditInfo editInfo = edit.get(); r.assertMessage( "Updated Changes:\n " + canonicalWebUrl.get() + "#/c/" + project.get() + "/+/" + r.getChange().getId() + " " + editInfo.commit.subject + " [EDIT]\n"); // verify that the re-indexing was triggered for the change assertThat(query("has:edit")).hasSize(1); } @Test public void pushForMasterWithMessage() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master/%m=my_test_message"); r.assertOkStatus(); r.assertChange(Change.Status.NEW, null); ChangeInfo ci = get(r.getChangeId(), MESSAGES, ALL_REVISIONS); Collection<ChangeMessageInfo> changeMessages = ci.messages; assertThat(changeMessages).hasSize(1); for (ChangeMessageInfo cm : changeMessages) { assertThat(cm.message).isEqualTo("Uploaded patch set 1.\nmy test message"); } Collection<RevisionInfo> revisions = ci.revisions.values(); assertThat(revisions).hasSize(1); for (RevisionInfo ri : revisions) { assertThat(ri.description).isEqualTo("my test message"); } } @Test public void pushForMasterWithMessageTwiceWithDifferentMessages() throws Exception { enableCreateNewChangeForAllNotInTarget(); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "a.txt", "content"); // %2C is comma; the value below tests that percent decoding happens after splitting. // All three ways of representing space ("%20", "+", and "_" are also exercised. PushOneCommit.Result r = push.to("refs/for/master/%m=my_test%20+_message%2Cm="); r.assertOkStatus(); push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); r = push.to("refs/for/master/%m=new_test_message"); r.assertOkStatus(); ChangeInfo ci = get(r.getChangeId(), ALL_REVISIONS); Collection<RevisionInfo> revisions = ci.revisions.values(); assertThat(revisions).hasSize(2); for (RevisionInfo ri : revisions) { if (ri.isCurrent) { assertThat(ri.description).isEqualTo("new test message"); } else { assertThat(ri.description).isEqualTo("my test message,m="); } } } @Test public void pushForMasterWithPercentEncodedMessage() throws Exception { // Exercise percent-encoding of UTF-8, underscores, and patterns reserved by git-rev-parse. PushOneCommit.Result r = pushTo( "refs/for/master/%m=" + "Punctu%2E%2e%2Eation%7E%2D%40%7Bu%7D%20%7C%20%28%E2%95%AF%C2%B0%E2%96%A1%C2%B0" + "%EF%BC%89%E2%95%AF%EF%B8%B5%20%E2%94%BB%E2%94%81%E2%94%BB%20%5E%5F%5E"); r.assertOkStatus(); r.assertChange(Change.Status.NEW, null); ChangeInfo ci = get(r.getChangeId(), MESSAGES, ALL_REVISIONS); Collection<ChangeMessageInfo> changeMessages = ci.messages; assertThat(changeMessages).hasSize(1); for (ChangeMessageInfo cm : changeMessages) { assertThat(cm.message) .isEqualTo("Uploaded patch set 1.\nPunctu...ation~-@{u} | (╯°□°)╯︵ ┻━┻ ^_^"); } Collection<RevisionInfo> revisions = ci.revisions.values(); assertThat(revisions).hasSize(1); for (RevisionInfo ri : revisions) { assertThat(ri.description).isEqualTo("Punctu...ation~-@{u} | (╯°□°)╯︵ ┻━┻ ^_^"); } } @Test public void pushForMasterWithInvalidPercentEncodedMessage() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master/%m=not_percent_decodable_%%oops%20"); r.assertOkStatus(); r.assertChange(Change.Status.NEW, null); ChangeInfo ci = get(r.getChangeId(), MESSAGES, ALL_REVISIONS); Collection<ChangeMessageInfo> changeMessages = ci.messages; assertThat(changeMessages).hasSize(1); for (ChangeMessageInfo cm : changeMessages) { assertThat(cm.message).isEqualTo("Uploaded patch set 1.\nnot percent decodable %%oops%20"); } Collection<RevisionInfo> revisions = ci.revisions.values(); assertThat(revisions).hasSize(1); for (RevisionInfo ri : revisions) { assertThat(ri.description).isEqualTo("not percent decodable %%oops%20"); } } @Test public void pushForMasterWithApprovals() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master/%l=Code-Review"); r.assertOkStatus(); ChangeInfo ci = get(r.getChangeId(), DETAILED_LABELS, MESSAGES, DETAILED_ACCOUNTS); LabelInfo cr = ci.labels.get("Code-Review"); assertThat(cr.all).hasSize(1); assertThat(cr.all.get(0).name).isEqualTo("Administrator"); assertThat(cr.all.get(0).value).isEqualTo(1); assertThat(Iterables.getLast(ci.messages).message) .isEqualTo("Uploaded patch set 1: Code-Review+1."); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); r = push.to("refs/for/master/%l=Code-Review+2"); ci = get(r.getChangeId(), DETAILED_LABELS, MESSAGES, DETAILED_ACCOUNTS); cr = ci.labels.get("Code-Review"); assertThat(Iterables.getLast(ci.messages).message) .isEqualTo("Uploaded patch set 2: Code-Review+2."); // Check that the user who pushed the change was added as a reviewer since they added a vote assertThatUserIsOnlyReviewer(ci, admin); assertThat(cr.all).hasSize(1); assertThat(cr.all.get(0).name).isEqualTo("Administrator"); assertThat(cr.all.get(0).value).isEqualTo(2); push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "c.txt", "moreContent", r.getChangeId()); r = push.to("refs/for/master/%l=Code-Review+2"); ci = get(r.getChangeId(), MESSAGES); assertThat(Iterables.getLast(ci.messages).message).isEqualTo("Uploaded patch set 3."); } @Test public void pushNewPatchSetForMasterWithApprovals() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); r = push.to("refs/for/master/%l=Code-Review+2"); ChangeInfo ci = get(r.getChangeId(), DETAILED_LABELS, MESSAGES, DETAILED_ACCOUNTS); LabelInfo cr = ci.labels.get("Code-Review"); assertThat(Iterables.getLast(ci.messages).message) .isEqualTo("Uploaded patch set 2: Code-Review+2."); // Check that the user who pushed the new patch set was added as a reviewer since they added // a vote assertThatUserIsOnlyReviewer(ci, admin); assertThat(cr.all).hasSize(1); assertThat(cr.all.get(0).name).isEqualTo("Administrator"); assertThat(cr.all.get(0).value).isEqualTo(2); } /** * There was a bug that allowed a user with Forge Committer Identity access right to upload a * commit and put *votes on behalf of another user* on it. This test checks that this is not * possible, but that the votes that are specified on push are applied only on behalf of the * uploader. * * <p>This particular bug only occurred when there was more than one label defined. However to * test that the votes that are specified on push are applied on behalf of the uploader a single * label is sufficient. */ @Test public void pushForMasterWithApprovalsForgeCommitterButNoForgeVote() throws Exception { // Create a commit with "User" as author and committer RevCommit c = commitBuilder() .author(user.getIdent()) .committer(user.getIdent()) .add(PushOneCommit.FILE_NAME, PushOneCommit.FILE_CONTENT) .message(PushOneCommit.SUBJECT) .create(); // Push this commit as "Administrator" (requires Forge Committer Identity) pushHead(testRepo, "refs/for/master/%l=Code-Review+1", false); // Expected Code-Review votes: // 1. 0 from User (committer): // When the committer is forged, the committer is automatically added as // reviewer, hence we expect a dummy 0 vote for the committer. // 2. +1 from Administrator (uploader): // On push Code-Review+1 was specified, hence we expect a +1 vote from // the uploader. ChangeInfo ci = get(GitUtil.getChangeId(testRepo, c).get(), DETAILED_LABELS, MESSAGES, DETAILED_ACCOUNTS); LabelInfo cr = ci.labels.get("Code-Review"); assertThat(cr.all).hasSize(2); int indexAdmin = admin.fullName.equals(cr.all.get(0).name) ? 0 : 1; int indexUser = indexAdmin == 0 ? 1 : 0; assertThat(cr.all.get(indexAdmin).name).isEqualTo(admin.fullName); assertThat(cr.all.get(indexAdmin).value.intValue()).isEqualTo(1); assertThat(cr.all.get(indexUser).name).isEqualTo(user.fullName); assertThat(cr.all.get(indexUser).value.intValue()).isEqualTo(0); assertThat(Iterables.getLast(ci.messages).message) .isEqualTo("Uploaded patch set 1: Code-Review+1."); // Check that the user who pushed the change was added as a reviewer since they added a vote assertThatUserIsOnlyReviewer(ci, admin); } @Test public void pushWithMultipleApprovals() throws Exception { LabelType Q = category("Custom-Label", value(1, "Positive"), value(0, "No score"), value(-1, "Negative")); ProjectConfig config = projectCache.checkedGet(project).getConfig(); AccountGroup.UUID anon = systemGroupBackend.getGroup(ANONYMOUS_USERS).getUUID(); String heads = "refs/heads/*"; Util.allow(config, Permission.forLabel("Custom-Label"), -1, 1, anon, heads); config.getLabelSections().put(Q.getName(), Q); saveProjectConfig(project, config); RevCommit c = commitBuilder() .author(admin.getIdent()) .committer(admin.getIdent()) .add(PushOneCommit.FILE_NAME, PushOneCommit.FILE_CONTENT) .message(PushOneCommit.SUBJECT) .create(); pushHead(testRepo, "refs/for/master/%l=Code-Review+1,l=Custom-Label-1", false); ChangeInfo ci = get(GitUtil.getChangeId(testRepo, c).get(), DETAILED_LABELS, DETAILED_ACCOUNTS); LabelInfo cr = ci.labels.get("Code-Review"); assertThat(cr.all).hasSize(1); cr = ci.labels.get("Custom-Label"); assertThat(cr.all).hasSize(1); // Check that the user who pushed the change was added as a reviewer since they added a vote assertThatUserIsOnlyReviewer(ci, admin); } @Test public void pushNewPatchsetToRefsChanges() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); r = push.to("refs/changes/" + r.getChange().change().getId().get()); r.assertOkStatus(); } @Test public void pushNewPatchsetToPatchSetLockedChange() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); revision(r).review(new ReviewInput().label("Patch-Set-Lock", 1)); r = push.to("refs/for/master"); r.assertErrorStatus("cannot add patch set to " + r.getChange().change().getChangeId() + "."); } @Test public void pushForMasterWithApprovals_MissingLabel() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master/%l=Verify"); r.assertErrorStatus("label \"Verify\" is not a configured label"); } @Test public void pushForMasterWithApprovals_ValueOutOfRange() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master/%l=Code-Review-3"); r.assertErrorStatus("label \"Code-Review\": -3 is not a valid value"); } @Test public void pushForNonExistingBranch() throws Exception { String branchName = "non-existing"; PushOneCommit.Result r = pushTo("refs/for/" + branchName); r.assertErrorStatus("branch " + branchName + " not found"); } @Test public void pushForMasterWithHashtags() throws Exception { // Hashtags only work when reading from NoteDB is enabled assume().that(notesMigration.readChanges()).isTrue(); // specify a single hashtag as option String hashtag1 = "tag1"; Set<String> expected = ImmutableSet.of(hashtag1); PushOneCommit.Result r = pushTo("refs/for/master%hashtag=#" + hashtag1); r.assertOkStatus(); r.assertChange(Change.Status.NEW, null); Set<String> hashtags = gApi.changes().id(r.getChangeId()).getHashtags(); assertThat(hashtags).containsExactlyElementsIn(expected); // specify a single hashtag as option in new patch set String hashtag2 = "tag2"; PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); r = push.to("refs/for/master/%hashtag=" + hashtag2); r.assertOkStatus(); expected = ImmutableSet.of(hashtag1, hashtag2); hashtags = gApi.changes().id(r.getChangeId()).getHashtags(); assertThat(hashtags).containsExactlyElementsIn(expected); } @Test public void pushForMasterWithMultipleHashtags() throws Exception { // Hashtags only work when reading from NoteDB is enabled assume().that(notesMigration.readChanges()).isTrue(); // specify multiple hashtags as options String hashtag1 = "tag1"; String hashtag2 = "tag2"; Set<String> expected = ImmutableSet.of(hashtag1, hashtag2); PushOneCommit.Result r = pushTo("refs/for/master%hashtag=#" + hashtag1 + ",hashtag=##" + hashtag2); r.assertOkStatus(); r.assertChange(Change.Status.NEW, null); Set<String> hashtags = gApi.changes().id(r.getChangeId()).getHashtags(); assertThat(hashtags).containsExactlyElementsIn(expected); // specify multiple hashtags as options in new patch set String hashtag3 = "tag3"; String hashtag4 = "tag4"; PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); r = push.to("refs/for/master%hashtag=" + hashtag3 + ",hashtag=" + hashtag4); r.assertOkStatus(); expected = ImmutableSet.of(hashtag1, hashtag2, hashtag3, hashtag4); hashtags = gApi.changes().id(r.getChangeId()).getHashtags(); assertThat(hashtags).containsExactlyElementsIn(expected); } @Test public void pushForMasterWithHashtagsNoteDbDisabled() throws Exception { // Push with hashtags should fail when reading from NoteDb is disabled. assume().that(notesMigration.readChanges()).isFalse(); PushOneCommit.Result r = pushTo("refs/for/master%hashtag=tag1"); r.assertErrorStatus("cannot add hashtags; noteDb is disabled"); } @Test public void pushCommitUsingSignedOffBy() throws Exception { PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent"); PushOneCommit.Result r = push.to("refs/for/master"); r.assertOkStatus(); setUseSignedOffBy(InheritableBoolean.TRUE); blockForgeCommitter(project, "refs/heads/master"); push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT + String.format("\n\nSigned-off-by: %s <%s>", admin.fullName, admin.email), "b.txt", "anotherContent"); r = push.to("refs/for/master"); r.assertOkStatus(); push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent"); r = push.to("refs/for/master"); r.assertErrorStatus("not Signed-off-by author/committer/uploader in commit message footer"); } @Test public void createNewChangeForAllNotInTarget() throws Exception { enableCreateNewChangeForAllNotInTarget(); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "a.txt", "content"); PushOneCommit.Result r = push.to("refs/for/master"); r.assertOkStatus(); push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent"); r = push.to("refs/for/master"); r.assertOkStatus(); gApi.projects().name(project.get()).branch("otherBranch").create(new BranchInput()); PushOneCommit.Result r2 = push.to("refs/for/otherBranch"); r2.assertOkStatus(); assertTwoChangesWithSameRevision(r); } @Test public void pushChangeBasedOnChangeOfOtherUserWithCreateNewChangeForAllNotInTarget() throws Exception { enableCreateNewChangeForAllNotInTarget(); // create a change as admin PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "a.txt", "content"); PushOneCommit.Result r = push.to("refs/for/master"); r.assertOkStatus(); RevCommit commitChange1 = r.getCommit(); // create a second change as user (depends on the change from admin) TestRepository<?> userRepo = cloneProject(project, user); GitUtil.fetch(userRepo, r.getPatchSet().getRefName() + ":change"); userRepo.reset("change"); push = pushFactory.create( db, user.getIdent(), userRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent"); r = push.to("refs/for/master"); r.assertOkStatus(); // assert that no new change was created for the commit of the predecessor change assertThat(query(commitChange1.name())).hasSize(1); } @Test public void pushSameCommitTwiceUsingMagicBranchBaseOption() throws Exception { grant(project, "refs/heads/master", Permission.PUSH); PushOneCommit.Result rBase = pushTo("refs/heads/master"); rBase.assertOkStatus(); gApi.projects().name(project.get()).branch("foo").create(new BranchInput()); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent"); PushOneCommit.Result r = push.to("refs/for/master"); r.assertOkStatus(); PushResult pr = GitUtil.pushHead(testRepo, "refs/for/foo%base=" + rBase.getCommit().name(), false, false); // BatchUpdate implementations differ in how they hook into progress monitors. We mostly just // care that there is a new change. assertThat(pr.getMessages()).containsMatch("changes: new: 1,( refs: 1)? done"); assertTwoChangesWithSameRevision(r); } @Test public void pushSameCommitTwice() throws Exception { ProjectConfig config = projectCache.checkedGet(project).getConfig(); config.getProject().setCreateNewChangeForAllNotInTarget(InheritableBoolean.TRUE); saveProjectConfig(project, config); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "a.txt", "content"); PushOneCommit.Result r = push.to("refs/for/master"); r.assertOkStatus(); push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent"); r = push.to("refs/for/master"); r.assertOkStatus(); assertPushRejected( pushHead(testRepo, "refs/for/master", false), "refs/for/master", "commit(s) already exists (as current patchset)"); } @Test public void pushSameCommitTwiceWhenIndexFailed() throws Exception { ProjectConfig config = projectCache.checkedGet(project).getConfig(); config.getProject().setCreateNewChangeForAllNotInTarget(InheritableBoolean.TRUE); saveProjectConfig(project, config); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "a.txt", "content"); PushOneCommit.Result r = push.to("refs/for/master"); r.assertOkStatus(); push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent"); r = push.to("refs/for/master"); r.assertOkStatus(); indexer.delete(r.getChange().getId()); assertPushRejected( pushHead(testRepo, "refs/for/master", false), "refs/for/master", "commit(s) already exists (as current patchset)"); } private void assertTwoChangesWithSameRevision(PushOneCommit.Result result) throws Exception { List<ChangeInfo> changes = query(result.getCommit().name()); assertThat(changes).hasSize(2); ChangeInfo c1 = get(changes.get(0).id, CURRENT_REVISION); ChangeInfo c2 = get(changes.get(1).id, CURRENT_REVISION); assertThat(c1.project).isEqualTo(c2.project); assertThat(c1.branch).isNotEqualTo(c2.branch); assertThat(c1.changeId).isEqualTo(c2.changeId); assertThat(c1.currentRevision).isEqualTo(c2.currentRevision); } @Test public void pushAFewChanges() throws Exception { testPushAFewChanges(); } @Test public void pushAFewChangesWithCreateNewChangeForAllNotInTarget() throws Exception { enableCreateNewChangeForAllNotInTarget(); testPushAFewChanges(); } private void testPushAFewChanges() throws Exception { int n = 10; String r = "refs/for/master"; ObjectId initialHead = testRepo.getRepository().resolve("HEAD"); List<RevCommit> commits = createChanges(n, r); // Check that a change was created for each. for (RevCommit c : commits) { assertThat(byCommit(c).change().getSubject()) .named("change for " + c.name()) .isEqualTo(c.getShortMessage()); } List<RevCommit> commits2 = amendChanges(initialHead, commits, r); // Check that there are correct patch sets. for (int i = 0; i < n; i++) { RevCommit c = commits.get(i); RevCommit c2 = commits2.get(i); String name = "change for " + c2.name(); ChangeData cd = byCommit(c); assertThat(cd.change().getSubject()).named(name).isEqualTo(c2.getShortMessage()); assertThat(getPatchSetRevisions(cd)) .named(name) .containsExactlyEntriesIn(ImmutableMap.of(1, c.name(), 2, c2.name())); } // Pushing again results in "no new changes". assertPushRejected(pushHead(testRepo, r, false), r, "no new changes"); } @Test public void pushWithoutChangeId() throws Exception { testPushWithoutChangeId(); } @Test public void pushWithoutChangeIdWithCreateNewChangeForAllNotInTarget() throws Exception { enableCreateNewChangeForAllNotInTarget(); testPushWithoutChangeId(); } private void testPushWithoutChangeId() throws Exception { RevCommit c = createCommit(testRepo, "Message without Change-Id"); assertThat(GitUtil.getChangeId(testRepo, c)).isEmpty(); pushForReviewRejected(testRepo, "missing Change-Id in commit message footer"); ProjectConfig config = projectCache.checkedGet(project).getConfig(); config.getProject().setRequireChangeID(InheritableBoolean.FALSE); saveProjectConfig(project, config); pushForReviewOk(testRepo); } @Test public void pushWithMultipleChangeIds() throws Exception { testPushWithMultipleChangeIds(); } @Test public void pushWithMultipleChangeIdsWithCreateNewChangeForAllNotInTarget() throws Exception { enableCreateNewChangeForAllNotInTarget(); testPushWithMultipleChangeIds(); } private void testPushWithMultipleChangeIds() throws Exception { createCommit( testRepo, "Message with multiple Change-Id\n" + "\n" + "Change-Id: I10f98c2ef76e52e23aa23be5afeb71e40b350e86\n" + "Change-Id: Ie9a132e107def33bdd513b7854b50de911edba0a\n"); pushForReviewRejected(testRepo, "multiple Change-Id lines in commit message footer"); ProjectConfig config = projectCache.checkedGet(project).getConfig(); config.getProject().setRequireChangeID(InheritableBoolean.FALSE); saveProjectConfig(project, config); pushForReviewRejected(testRepo, "multiple Change-Id lines in commit message footer"); } @Test public void pushWithInvalidChangeId() throws Exception { testpushWithInvalidChangeId(); } @Test public void pushWithInvalidChangeIdWithCreateNewChangeForAllNotInTarget() throws Exception { enableCreateNewChangeForAllNotInTarget(); testpushWithInvalidChangeId(); } private void testpushWithInvalidChangeId() throws Exception { createCommit(testRepo, "Message with invalid Change-Id\n\nChange-Id: X\n"); pushForReviewRejected(testRepo, "invalid Change-Id line format in commit message footer"); ProjectConfig config = projectCache.checkedGet(project).getConfig(); config.getProject().setRequireChangeID(InheritableBoolean.FALSE); saveProjectConfig(project, config); pushForReviewRejected(testRepo, "invalid Change-Id line format in commit message footer"); } @Test public void pushWithInvalidChangeIdFromEgit() throws Exception { testPushWithInvalidChangeIdFromEgit(); } @Test public void pushWithInvalidChangeIdFromEgitWithCreateNewChangeForAllNotInTarget() throws Exception { enableCreateNewChangeForAllNotInTarget(); testPushWithInvalidChangeIdFromEgit(); } private void testPushWithInvalidChangeIdFromEgit() throws Exception { createCommit( testRepo, "Message with invalid Change-Id\n" + "\n" + "Change-Id: I0000000000000000000000000000000000000000\n"); pushForReviewRejected(testRepo, "invalid Change-Id line format in commit message footer"); ProjectConfig config = projectCache.checkedGet(project).getConfig(); config.getProject().setRequireChangeID(InheritableBoolean.FALSE); saveProjectConfig(project, config); pushForReviewRejected(testRepo, "invalid Change-Id line format in commit message footer"); } @Test public void pushCommitWithSameChangeIdAsPredecessorChange() throws Exception { PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "a.txt", "content"); PushOneCommit.Result r = push.to("refs/for/master"); r.assertOkStatus(); RevCommit commitChange1 = r.getCommit(); createCommit(testRepo, commitChange1.getFullMessage()); pushForReviewRejected( testRepo, "same Change-Id in multiple changes.\n" + "Squash the commits with the same Change-Id or ensure Change-Ids are unique for each" + " commit"); ProjectConfig config = projectCache.checkedGet(project).getConfig(); config.getProject().setRequireChangeID(InheritableBoolean.FALSE); saveProjectConfig(project, config); pushForReviewRejected( testRepo, "same Change-Id in multiple changes.\n" + "Squash the commits with the same Change-Id or ensure Change-Ids are unique for each" + " commit"); } @Test public void pushTwoCommitWithSameChangeId() throws Exception { RevCommit commitChange1 = createCommitWithChangeId(testRepo, "some change"); createCommit(testRepo, commitChange1.getFullMessage()); pushForReviewRejected( testRepo, "same Change-Id in multiple changes.\n" + "Squash the commits with the same Change-Id or ensure Change-Ids are unique for each" + " commit"); ProjectConfig config = projectCache.checkedGet(project).getConfig(); config.getProject().setRequireChangeID(InheritableBoolean.FALSE); saveProjectConfig(project, config); pushForReviewRejected( testRepo, "same Change-Id in multiple changes.\n" + "Squash the commits with the same Change-Id or ensure Change-Ids are unique for each" + " commit"); } private static RevCommit createCommit(TestRepository<?> testRepo, String message) throws Exception { return testRepo.branch("HEAD").commit().message(message).add("a.txt", "content").create(); } private static RevCommit createCommitWithChangeId(TestRepository<?> testRepo, String message) throws Exception { RevCommit c = testRepo .branch("HEAD") .commit() .message(message) .insertChangeId() .add("a.txt", "content") .create(); return testRepo.getRevWalk().parseCommit(c); } @Test public void cantAutoCloseChangeAlreadyMergedToBranch() throws Exception { PushOneCommit.Result r1 = createChange(); Change.Id id1 = r1.getChange().getId(); PushOneCommit.Result r2 = createChange(); Change.Id id2 = r2.getChange().getId(); // Merge change 1 behind Gerrit's back. try (Repository repo = repoManager.openRepository(project)) { TestRepository<?> tr = new TestRepository<>(repo); tr.branch("refs/heads/master").update(r1.getCommit()); } assertThat(gApi.changes().id(id1.get()).info().status).isEqualTo(ChangeStatus.NEW); assertThat(gApi.changes().id(id2.get()).info().status).isEqualTo(ChangeStatus.NEW); r2 = amendChange(r2.getChangeId()); r2.assertOkStatus(); // Change 1 is still new despite being merged into the branch, because // ReceiveCommits only considers commits between the branch tip (which is // now the merged change 1) and the push tip (new patch set of change 2). assertThat(gApi.changes().id(id1.get()).info().status).isEqualTo(ChangeStatus.NEW); assertThat(gApi.changes().id(id2.get()).info().status).isEqualTo(ChangeStatus.NEW); } @Test public void accidentallyPushNewPatchSetDirectlyToBranchAndRecoverByPushingToRefsChanges() throws Exception { Change.Id id = accidentallyPushNewPatchSetDirectlyToBranch(); ChangeData cd = byChangeId(id); String ps1Rev = Iterables.getOnlyElement(cd.patchSets()).getRevision().get(); String r = "refs/changes/" + id; assertPushOk(pushHead(testRepo, r, false), r); // Added a new patch set and auto-closed the change. cd = byChangeId(id); assertThat(cd.change().getStatus()).isEqualTo(Change.Status.MERGED); assertThat(getPatchSetRevisions(cd)) .containsExactlyEntriesIn( ImmutableMap.of(1, ps1Rev, 2, testRepo.getRepository().resolve("HEAD").name())); } @Test public void accidentallyPushNewPatchSetDirectlyToBranchAndCantRecoverByPushingToRefsFor() throws Exception { Change.Id id = accidentallyPushNewPatchSetDirectlyToBranch(); ChangeData cd = byChangeId(id); String ps1Rev = Iterables.getOnlyElement(cd.patchSets()).getRevision().get(); String r = "refs/for/master"; assertPushRejected(pushHead(testRepo, r, false), r, "no new changes"); // Change not updated. cd = byChangeId(id); assertThat(cd.change().getStatus()).isEqualTo(Change.Status.NEW); assertThat(getPatchSetRevisions(cd)).containsExactlyEntriesIn(ImmutableMap.of(1, ps1Rev)); } @Test public void forcePushAbandonedChange() throws Exception { grant(project, "refs/*", Permission.PUSH, true); PushOneCommit push1 = pushFactory.create(db, admin.getIdent(), testRepo, "change1", "a.txt", "content"); PushOneCommit.Result r = push1.to("refs/for/master"); r.assertOkStatus(); //abandon the change String changeId = r.getChangeId(); assertThat(info(changeId).status).isEqualTo(ChangeStatus.NEW); gApi.changes().id(changeId).abandon(); ChangeInfo info = get(changeId); assertThat(info.status).isEqualTo(ChangeStatus.ABANDONED); push1.setForce(true); PushOneCommit.Result r1 = push1.to("refs/heads/master"); r1.assertOkStatus(); ChangeInfo result = Iterables.getOnlyElement(gApi.changes().query(r.getChangeId()).get()); assertThat(result.status).isEqualTo(ChangeStatus.MERGED); } private Change.Id accidentallyPushNewPatchSetDirectlyToBranch() throws Exception { PushOneCommit.Result r = createChange(); RevCommit ps1Commit = r.getCommit(); Change c = r.getChange().change(); RevCommit ps2Commit; try (Repository repo = repoManager.openRepository(project)) { // Create a new patch set of the change directly in Gerrit's repository, // without pushing it. In reality it's more likely that the client would // create and push this behind Gerrit's back (e.g. an admin accidentally // using direct ssh access to the repo), but that's harder to do in tests. TestRepository<?> tr = new TestRepository<>(repo); ps2Commit = tr.branch("refs/heads/master") .commit() .message(ps1Commit.getShortMessage() + " v2") .insertChangeId(r.getChangeId().substring(1)) .create(); } testRepo.git().fetch().setRefSpecs(new RefSpec("refs/heads/master")).call(); testRepo.reset(ps2Commit); ChangeData cd = byCommit(ps1Commit); assertThat(cd.change().getStatus()).isEqualTo(Change.Status.NEW); assertThat(getPatchSetRevisions(cd)) .containsExactlyEntriesIn(ImmutableMap.of(1, ps1Commit.name())); return c.getId(); } @Test public void pushWithEmailInFooter() throws Exception { pushWithReviewerInFooter(user.emailAddress.toString(), user); } @Test public void pushWithNameInFooter() throws Exception { pushWithReviewerInFooter(user.fullName, user); } @Test public void pushWithEmailInFooterNotFound() throws Exception { pushWithReviewerInFooter(new Address("No Body", "[email protected]").toString(), null); } @Test public void pushWithNameInFooterNotFound() throws Exception { pushWithReviewerInFooter("Notauser", null); } @Test public void pushNewPatchsetOverridingStickyLabel() throws Exception { ProjectConfig cfg = projectCache.checkedGet(project).getConfig(); LabelType codeReview = Util.codeReview(); codeReview.setCopyMaxScore(true); cfg.getLabelSections().put(codeReview.getName(), codeReview); saveProjectConfig(cfg); PushOneCommit.Result r = pushTo("refs/for/master%l=Code-Review+2"); r.assertOkStatus(); PushOneCommit push = pushFactory.create( db, admin.getIdent(), testRepo, PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); r = push.to("refs/for/master%l=Code-Review+1"); r.assertOkStatus(); } @Test public void createChangeForMergedCommit() throws Exception { String master = "refs/heads/master"; grant(project, master, Permission.PUSH, true); // Update master with a direct push. RevCommit c1 = testRepo.commit().message("Non-change 1").create(); RevCommit c2 = testRepo.parseBody( testRepo.commit().parent(c1).message("Non-change 2").insertChangeId().create()); String changeId = Iterables.getOnlyElement(c2.getFooterLines(CHANGE_ID)); testRepo.reset(c2); assertPushOk(pushHead(testRepo, master, false, true), master); String q = "commit:" + c1.name() + " OR commit:" + c2.name() + " OR change:" + changeId; assertThat(gApi.changes().query(q).get()).isEmpty(); // Push c2 as a merged change. String r = "refs/for/master%merged"; assertPushOk(pushHead(testRepo, r, false), r); EnumSet<ListChangesOption> opts = EnumSet.of(ListChangesOption.CURRENT_REVISION); ChangeInfo info = gApi.changes().id(changeId).get(opts); assertThat(info.currentRevision).isEqualTo(c2.name()); assertThat(info.status).isEqualTo(ChangeStatus.MERGED); // Only c2 was created as a change. String q1 = "commit: " + c1.name(); assertThat(gApi.changes().query(q1).get()).isEmpty(); // Push c1 as a merged change. testRepo.reset(c1); assertPushOk(pushHead(testRepo, r, false), r); List<ChangeInfo> infos = gApi.changes().query(q1).withOptions(opts).get(); assertThat(infos).hasSize(1); info = infos.get(0); assertThat(info.currentRevision).isEqualTo(c1.name()); assertThat(info.status).isEqualTo(ChangeStatus.MERGED); } @Test public void mergedOptionFailsWhenCommitIsNotMerged() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master%merged"); r.assertErrorStatus("not merged into branch"); } @Test public void mergedOptionFailsWhenCommitIsMergedOnOtherBranch() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); gApi.changes().id(r.getChangeId()).current().submit(); try (Repository repo = repoManager.openRepository(project)) { TestRepository<?> tr = new TestRepository<>(repo); tr.branch("refs/heads/branch").commit().message("Initial commit on branch").create(); } pushTo("refs/for/master%merged").assertErrorStatus("not merged into branch"); } @Test public void mergedOptionFailsWhenChangeExists() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); gApi.changes().id(r.getChangeId()).current().submit(); testRepo.reset(r.getCommit()); String ref = "refs/for/master%merged"; PushResult pr = pushHead(testRepo, ref, false); RemoteRefUpdate rru = pr.getRemoteUpdate(ref); assertThat(rru.getStatus()).isEqualTo(RemoteRefUpdate.Status.REJECTED_OTHER_REASON); assertThat(rru.getMessage()).contains("no new changes"); } @Test public void mergedOptionWithNewCommitWithSameChangeIdFails() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); gApi.changes().id(r.getChangeId()).current().submit(); RevCommit c2 = testRepo .amend(r.getCommit()) .message("New subject") .insertChangeId(r.getChangeId().substring(1)) .create(); testRepo.reset(c2); String ref = "refs/for/master%merged"; PushResult pr = pushHead(testRepo, ref, false); RemoteRefUpdate rru = pr.getRemoteUpdate(ref); assertThat(rru.getStatus()).isEqualTo(RemoteRefUpdate.Status.REJECTED_OTHER_REASON); assertThat(rru.getMessage()).contains("not merged into branch"); } @Test public void mergedOptionWithExistingChangeInsertsPatchSet() throws Exception { String master = "refs/heads/master"; grant(project, master, Permission.PUSH, true); PushOneCommit.Result r = pushTo("refs/for/master"); r.assertOkStatus(); ObjectId c1 = r.getCommit().copy(); // Create a PS2 commit directly on master in the server's repo. This // simulates the client amending locally and pushing directly to the branch, // expecting the change to be auto-closed, but the change metadata update // fails. ObjectId c2; try (Repository repo = repoManager.openRepository(project)) { TestRepository<?> tr = new TestRepository<>(repo); RevCommit commit2 = tr.amend(c1).message("New subject").insertChangeId(r.getChangeId().substring(1)).create(); c2 = commit2.copy(); tr.update(master, c2); } testRepo.git().fetch().setRefSpecs(new RefSpec("refs/heads/master")).call(); testRepo.reset(c2); String ref = "refs/for/master%merged"; assertPushOk(pushHead(testRepo, ref, false), ref); ChangeInfo info = gApi.changes().id(r.getChangeId()).get(ALL_REVISIONS); assertThat(info.currentRevision).isEqualTo(c2.name()); assertThat(info.revisions.keySet()).containsExactly(c1.name(), c2.name()); // TODO(dborowitz): Fix ReceiveCommits to also auto-close the change. assertThat(info.status).isEqualTo(ChangeStatus.NEW); } @Test public void publishCommentsOnPushPublishesDraftsOnAllRevisions() throws Exception { PushOneCommit.Result r = createChange(); String rev1 = r.getCommit().name(); CommentInfo c1 = addDraft(r.getChangeId(), rev1, newDraft(FILE_NAME, 1, "comment1")); CommentInfo c2 = addDraft(r.getChangeId(), rev1, newDraft(FILE_NAME, 1, "comment2")); r = amendChange(r.getChangeId()); String rev2 = r.getCommit().name(); CommentInfo c3 = addDraft(r.getChangeId(), rev2, newDraft(FILE_NAME, 1, "comment3")); assertThat(getPublishedComments(r.getChangeId())).isEmpty(); gApi.changes().id(r.getChangeId()).addReviewer(user.email); sender.clear(); amendChange(r.getChangeId(), "refs/for/master%publish-comments"); Collection<CommentInfo> comments = getPublishedComments(r.getChangeId()); assertThat(comments.stream().map(c -> c.id)).containsExactly(c1.id, c2.id, c3.id); assertThat(comments.stream().map(c -> c.message)) .containsExactly("comment1", "comment2", "comment3"); assertThat(getLastMessage(r.getChangeId())).isEqualTo("Uploaded patch set 3.\n\n(3 comments)"); List<String> messages = sender .getMessages() .stream() .map(m -> m.body()) .sorted(Comparator.comparingInt(m -> m.contains("reexamine") ? 0 : 1)) .collect(toList()); assertThat(messages).hasSize(2); assertThat(messages.get(0)).contains("Gerrit-MessageType: newpatchset"); assertThat(messages.get(0)).contains("I'd like you to reexamine a change"); assertThat(messages.get(0)).doesNotContain("Uploaded patch set 3"); assertThat(messages.get(1)).contains("Gerrit-MessageType: comment"); assertThat(messages.get(1)) .containsMatch( Pattern.compile( // A little weird that the comment email contains this text, but it's actually // what's in the ChangeMessage. Really we should fuse the emails into one, but until // then, this test documents the current behavior. "Uploaded patch set 3\\.\n" + "\n" + "\\(3 comments\\)\\n.*" + "PS1, Line 1:.*" + "comment1\\n.*" + "PS1, Line 1:.*" + "comment2\\n.*" + "PS2, Line 1:.*" + "comment3\\n", Pattern.DOTALL)); } @Test public void publishCommentsOnPushWithMessage() throws Exception { PushOneCommit.Result r = createChange(); String rev = r.getCommit().name(); addDraft(r.getChangeId(), rev, newDraft(FILE_NAME, 1, "comment1")); r = amendChange(r.getChangeId(), "refs/for/master%publish-comments,m=The_message"); Collection<CommentInfo> comments = getPublishedComments(r.getChangeId()); assertThat(comments.stream().map(c -> c.message)).containsExactly("comment1"); assertThat(getLastMessage(r.getChangeId())) .isEqualTo("Uploaded patch set 2.\n\n(1 comment)\n\nThe message"); } @Test public void publishCommentsOnPushPublishesDraftsOnMultipleChanges() throws Exception { ObjectId initialHead = testRepo.getRepository().resolve("HEAD"); List<RevCommit> commits = createChanges(2, "refs/for/master"); String id1 = byCommit(commits.get(0)).change().getKey().get(); String id2 = byCommit(commits.get(1)).change().getKey().get(); CommentInfo c1 = addDraft(id1, commits.get(0).name(), newDraft(FILE_NAME, 1, "comment1")); CommentInfo c2 = addDraft(id2, commits.get(1).name(), newDraft(FILE_NAME, 1, "comment2")); assertThat(getPublishedComments(id1)).isEmpty(); assertThat(getPublishedComments(id2)).isEmpty(); amendChanges(initialHead, commits, "refs/for/master%publish-comments"); Collection<CommentInfo> cs1 = getPublishedComments(id1); assertThat(cs1.stream().map(c -> c.message)).containsExactly("comment1"); assertThat(cs1.stream().map(c -> c.id)).containsExactly(c1.id); assertThat(getLastMessage(id1)) .isEqualTo("Uploaded patch set 2: Commit message was updated.\n\n(1 comment)"); Collection<CommentInfo> cs2 = getPublishedComments(id2); assertThat(cs2.stream().map(c -> c.message)).containsExactly("comment2"); assertThat(cs2.stream().map(c -> c.id)).containsExactly(c2.id); assertThat(getLastMessage(id2)) .isEqualTo("Uploaded patch set 2: Commit message was updated.\n\n(1 comment)"); } @Test public void publishCommentsOnPushOnlyPublishesDraftsOnUpdatedChanges() throws Exception { PushOneCommit.Result r1 = createChange(); PushOneCommit.Result r2 = createChange(); String id1 = r1.getChangeId(); String id2 = r2.getChangeId(); addDraft(id1, r1.getCommit().name(), newDraft(FILE_NAME, 1, "comment1")); CommentInfo c2 = addDraft(id2, r2.getCommit().name(), newDraft(FILE_NAME, 1, "comment2")); assertThat(getPublishedComments(id1)).isEmpty(); assertThat(getPublishedComments(id2)).isEmpty(); r2 = amendChange(id2, "refs/for/master%publish-comments"); assertThat(getPublishedComments(id1)).isEmpty(); assertThat(gApi.changes().id(id1).drafts()).hasSize(1); Collection<CommentInfo> cs2 = getPublishedComments(id2); assertThat(cs2.stream().map(c -> c.message)).containsExactly("comment2"); assertThat(cs2.stream().map(c -> c.id)).containsExactly(c2.id); assertThat(getLastMessage(id1)).doesNotMatch("[Cc]omment"); assertThat(getLastMessage(id2)).isEqualTo("Uploaded patch set 2.\n\n(1 comment)"); } @Test public void publishCommentsOnPushWithPreference() throws Exception { PushOneCommit.Result r = createChange(); addDraft(r.getChangeId(), r.getCommit().name(), newDraft(FILE_NAME, 1, "comment1")); r = amendChange(r.getChangeId()); assertThat(getPublishedComments(r.getChangeId())).isEmpty(); GeneralPreferencesInfo prefs = gApi.accounts().id(admin.id.get()).getPreferences(); prefs.publishCommentsOnPush = true; gApi.accounts().id(admin.id.get()).setPreferences(prefs); r = amendChange(r.getChangeId()); assertThat(getPublishedComments(r.getChangeId()).stream().map(c -> c.message)) .containsExactly("comment1"); } @Test public void publishCommentsOnPushOverridingPreference() throws Exception { PushOneCommit.Result r = createChange(); addDraft(r.getChangeId(), r.getCommit().name(), newDraft(FILE_NAME, 1, "comment1")); GeneralPreferencesInfo prefs = gApi.accounts().id(admin.id.get()).getPreferences(); prefs.publishCommentsOnPush = true; gApi.accounts().id(admin.id.get()).setPreferences(prefs); r = amendChange(r.getChangeId(), "refs/for/master%no-publish-comments"); assertThat(getPublishedComments(r.getChangeId())).isEmpty(); } @Test public void pushDraftGetsPrivateChange() throws Exception { String changeId1 = createChange("refs/drafts/master").getChangeId(); String changeId2 = createChange("refs/for/master%draft").getChangeId(); ChangeInfo info1 = gApi.changes().id(changeId1).get(); ChangeInfo info2 = gApi.changes().id(changeId2).get(); assertThat(info1.status).isEqualTo(ChangeStatus.NEW); assertThat(info2.status).isEqualTo(ChangeStatus.NEW); assertThat(info1.isPrivate).isEqualTo(true); assertThat(info2.isPrivate).isEqualTo(true); assertThat(info1.revisions).hasSize(1); assertThat(info2.revisions).hasSize(1); } @Sandboxed @Test public void pushWithDraftOptionToExistingNewChangeGetsChangeEdit() throws Exception { String changeId = createChange().getChangeId(); EditInfoSubject.assertThat(getEdit(changeId)).isAbsent(); ChangeInfo changeInfo = gApi.changes().id(changeId).get(); ChangeStatus originalChangeStatus = changeInfo.status; PushOneCommit.Result result = amendChange(changeId, "refs/drafts/master"); result.assertOkStatus(); changeInfo = gApi.changes().id(changeId).get(); assertThat(changeInfo.status).isEqualTo(originalChangeStatus); assertThat(changeInfo.isPrivate).isNull(); assertThat(changeInfo.revisions).hasSize(1); EditInfoSubject.assertThat(getEdit(changeId)).isPresent(); } @GerritConfig(name = "receive.maxBatchCommits", value = "2") @Test public void maxBatchCommits() throws Exception { List<RevCommit> commits = new ArrayList<>(); commits.addAll(initChanges(2)); String master = "refs/heads/master"; assertPushOk(pushHead(testRepo, master), master); commits.addAll(initChanges(3)); assertPushRejected(pushHead(testRepo, master), master, "too many commits"); grantSkipValidation(project, master, SystemGroupBackend.REGISTERED_USERS); PushResult r = pushHead(testRepo, master, false, false, ImmutableList.of(PUSH_OPTION_SKIP_VALIDATION)); assertPushOk(r, master); // No open changes; branch was advanced. String q = commits.stream().map(ObjectId::name).collect(joining(" OR commit:", "commit:", "")); assertThat(gApi.changes().query(q).get()).isEmpty(); assertThat(gApi.projects().name(project.get()).branch(master).get().revision) .isEqualTo(Iterables.getLast(commits).name()); } @Test public void pushToPublishMagicBranchIsAllowed() throws Exception { // Push to "refs/publish/*" will be a synonym of "refs/for/*". createChange("refs/publish/master"); PushOneCommit.Result result = pushTo("refs/publish/master"); result.assertOkStatus(); assertThat(result.getMessage()) .endsWith("Pushing to refs/publish/* is deprecated, use refs/for/* instead.\n"); } private DraftInput newDraft(String path, int line, String message) { DraftInput d = new DraftInput(); d.path = path; d.side = Side.REVISION; d.line = line; d.message = message; d.unresolved = true; return d; } private CommentInfo addDraft(String changeId, String revId, DraftInput in) throws Exception { return gApi.changes().id(changeId).revision(revId).createDraft(in).get(); } private Collection<CommentInfo> getPublishedComments(String changeId) throws Exception { return gApi.changes() .id(changeId) .comments() .values() .stream() .flatMap(cs -> cs.stream()) .collect(toList()); } private String getLastMessage(String changeId) throws Exception { return Streams.findLast( gApi.changes().id(changeId).get(MESSAGES).messages.stream().map(m -> m.message)) .get(); } private void assertThatUserIsOnlyReviewer(ChangeInfo ci, TestAccount reviewer) { assertThat(ci.reviewers).isNotNull(); assertThat(ci.reviewers.keySet()).containsExactly(ReviewerState.REVIEWER); assertThat(ci.reviewers.get(ReviewerState.REVIEWER).iterator().next().email) .isEqualTo(reviewer.email); } private void pushWithReviewerInFooter(String nameEmail, TestAccount expectedReviewer) throws Exception { int n = 5; String r = "refs/for/master"; ObjectId initialHead = testRepo.getRepository().resolve("HEAD"); List<RevCommit> commits = createChanges(n, r, ImmutableList.of("Acked-By: " + nameEmail)); for (int i = 0; i < n; i++) { RevCommit c = commits.get(i); ChangeData cd = byCommit(c); String name = "reviewers for " + (i + 1); if (expectedReviewer != null) { assertThat(cd.reviewers().all()).named(name).containsExactly(expectedReviewer.getId()); gApi.changes().id(cd.getId().get()).reviewer(expectedReviewer.getId().toString()).remove(); } assertThat(byCommit(c).reviewers().all()).named(name).isEmpty(); } List<RevCommit> commits2 = amendChanges(initialHead, commits, r); for (int i = 0; i < n; i++) { RevCommit c = commits2.get(i); ChangeData cd = byCommit(c); String name = "reviewers for " + (i + 1); if (expectedReviewer != null) { assertThat(cd.reviewers().all()).named(name).containsExactly(expectedReviewer.getId()); } else { assertThat(byCommit(c).reviewers().all()).named(name).isEmpty(); } } } private List<RevCommit> createChanges(int n, String refsFor) throws Exception { return createChanges(n, refsFor, ImmutableList.of()); } private List<RevCommit> createChanges(int n, String refsFor, List<String> footerLines) throws Exception { List<RevCommit> commits = initChanges(n, footerLines); assertPushOk(pushHead(testRepo, refsFor, false), refsFor); return commits; } private List<RevCommit> initChanges(int n) throws Exception { return initChanges(n, ImmutableList.of()); } private List<RevCommit> initChanges(int n, List<String> footerLines) throws Exception { List<RevCommit> commits = new ArrayList<>(n); for (int i = 1; i <= n; i++) { String msg = "Change " + i; if (!footerLines.isEmpty()) { StringBuilder sb = new StringBuilder(msg).append("\n\n"); for (String line : footerLines) { sb.append(line).append('\n'); } msg = sb.toString(); } TestRepository<?>.CommitBuilder cb = testRepo.branch("HEAD").commit().message(msg).insertChangeId(); if (!commits.isEmpty()) { cb.parent(commits.get(commits.size() - 1)); } RevCommit c = cb.create(); testRepo.getRevWalk().parseBody(c); commits.add(c); } return commits; } private List<RevCommit> amendChanges( ObjectId initialHead, List<RevCommit> origCommits, String refsFor) throws Exception { testRepo.reset(initialHead); List<RevCommit> newCommits = new ArrayList<>(origCommits.size()); for (RevCommit c : origCommits) { String msg = c.getShortMessage() + "v2"; if (!c.getShortMessage().equals(c.getFullMessage())) { msg = msg + c.getFullMessage().substring(c.getShortMessage().length()); } TestRepository<?>.CommitBuilder cb = testRepo.branch("HEAD").commit().message(msg); if (!newCommits.isEmpty()) { cb.parent(origCommits.get(newCommits.size() - 1)); } RevCommit c2 = cb.create(); testRepo.getRevWalk().parseBody(c2); newCommits.add(c2); } assertPushOk(pushHead(testRepo, refsFor, false), refsFor); return newCommits; } private static Map<Integer, String> getPatchSetRevisions(ChangeData cd) throws Exception { Map<Integer, String> revisions = new HashMap<>(); for (PatchSet ps : cd.patchSets()) { revisions.put(ps.getPatchSetId(), ps.getRevision().get()); } return revisions; } private ChangeData byCommit(ObjectId id) throws Exception { List<ChangeData> cds = queryProvider.get().byCommit(id); assertThat(cds).named("change for " + id.name()).hasSize(1); return cds.get(0); } private ChangeData byChangeId(Change.Id id) throws Exception { List<ChangeData> cds = queryProvider.get().byLegacyChangeId(id); assertThat(cds).named("change " + id).hasSize(1); return cds.get(0); } private static void pushForReviewOk(TestRepository<?> testRepo) throws GitAPIException { pushForReview(testRepo, RemoteRefUpdate.Status.OK, null); } private static void pushForReviewRejected(TestRepository<?> testRepo, String expectedMessage) throws GitAPIException { pushForReview(testRepo, RemoteRefUpdate.Status.REJECTED_OTHER_REASON, expectedMessage); } private static void pushForReview( TestRepository<?> testRepo, RemoteRefUpdate.Status expectedStatus, String expectedMessage) throws GitAPIException { String ref = "refs/for/master"; PushResult r = pushHead(testRepo, ref); RemoteRefUpdate refUpdate = r.getRemoteUpdate(ref); assertThat(refUpdate.getStatus()).isEqualTo(expectedStatus); if (expectedMessage != null) { assertThat(refUpdate.getMessage()).contains(expectedMessage); } } private void enableCreateNewChangeForAllNotInTarget() throws Exception { ProjectConfig config = projectCache.checkedGet(project).getConfig(); config.getProject().setCreateNewChangeForAllNotInTarget(InheritableBoolean.TRUE); saveProjectConfig(project, config); } private void grantSkipValidation(Project.NameKey project, String ref, AccountGroup.UUID groupUuid) throws Exception { // See SKIP_VALIDATION implementation in default permission backend. ProjectConfig config = projectCache.checkedGet(project).getConfig(); Util.allow(config, Permission.FORGE_AUTHOR, groupUuid, ref); Util.allow(config, Permission.FORGE_COMMITTER, groupUuid, ref); Util.allow(config, Permission.FORGE_SERVER, groupUuid, ref); Util.allow(config, Permission.PUSH_MERGE, groupUuid, "refs/for/" + ref); saveProjectConfig(project, config); } }
924095b277832d781d169cf310c76fe010fc1af6
578
java
Java
play-hack3/app/models/Twit.java
Red-Hat-Vayeye/hack3
43c1bec9da09cd42e1c2545ed2f5739cc649c4d0
[ "MIT" ]
null
null
null
play-hack3/app/models/Twit.java
Red-Hat-Vayeye/hack3
43c1bec9da09cd42e1c2545ed2f5739cc649c4d0
[ "MIT" ]
null
null
null
play-hack3/app/models/Twit.java
Red-Hat-Vayeye/hack3
43c1bec9da09cd42e1c2545ed2f5739cc649c4d0
[ "MIT" ]
null
null
null
18.0625
78
0.688581
1,001,580
package models; import java.util.*; import java.util.stream.*; import javax.persistence.*; import io.ebean.*; import play.data.format.*; import play.data.validation.*; import play.db.ebean.Transactional; @Entity public class Twit extends Model { @Id @Constraints.Min(10) public Integer id; @Constraints.Required public String text; @Constraints.Required public String keywords; public static void delete(Integer id) { find.ref(id).delete(); } public static final Finder<Integer, Twit> find = new Finder<>(Twit.class); }
924095dcc5b1a18a931ec14142099758279e050c
2,397
java
Java
Exercise_09/Exercise_09_01/Exercise_09_01.java
saurab2019/Intro-to-Java-Programming
390f278fc5be5c9cc279e548dd9d3a93a350867e
[ "MIT" ]
1,100
2015-09-16T07:11:39.000Z
2022-03-31T22:43:17.000Z
Exercise_09/Exercise_09_01/Exercise_09_01.java
saurab2019/Intro-to-Java-Programming
390f278fc5be5c9cc279e548dd9d3a93a350867e
[ "MIT" ]
33
2017-01-22T17:03:58.000Z
2022-03-19T17:54:53.000Z
Exercise_09/Exercise_09_01/Exercise_09_01.java
saurab2019/Intro-to-Java-Programming
390f278fc5be5c9cc279e548dd9d3a93a350867e
[ "MIT" ]
1,023
2015-10-31T13:42:25.000Z
2022-03-31T18:55:11.000Z
57.071429
82
0.577806
1,001,581
/********************************************************************************* * (The Rectangle class) Following the example of the Circle class in Section 9.2,* * design a class named Rectangle to represent a rectangle. The class contains: * * * * ■ Two double data fields named width and height that specify the width and * * height of the rectangle. The default values are 1 for both width and height. * * ■ A no-arg constructor that creates a default rectangle. * * ■ A constructor that creates a rectangle with the specified width and height. * * ■ A method named getArea() that returns the area of this rectangle. * * ■ A method named getPerimeter() that returns the perimeter. * * * * Draw the UML diagram for the class and then implement the class. Write a test * * program that creates two Rectangle objects—one with width 4 and height 40 * * and the other with width 3.5 and height 35.9. Display the width, height, area, * * and perimeter of each rectangle in this order. * *********************************************************************************/ public class Exercise_09_01 { /** Main method */ public static void main(String[] args) { // Create a Rectangle with width 4 and height 40 Rectangle rectangle1 = new Rectangle(4, 40); // Create a Rectangle with width 3.5 and height 35.9 Rectangle rectangle2 = new Rectangle(3.5, 35.9); // Display the width, height, area, and perimeter of rectangle1 System.out.println("\n Rectangle 1"); System.out.println("-------------"); System.out.println("Width: " + rectangle1.width); System.out.println("Height: " + rectangle1.height); System.out.println("Area: " + rectangle1.getArea()); System.out.println("Perimeter: " + rectangle1.getPerimeter()); // Display the width, height, area, and perimeter of rectangle2 System.out.println("\n Rectangle 2"); System.out.println("-------------"); System.out.println("Width: " + rectangle2.width); System.out.println("Height: " + rectangle2.height); System.out.println("Area: " + rectangle2.getArea()); System.out.println("Perimeter: " + rectangle2.getPerimeter()); } }
9240963bae40d4f2107882aa02ab5d2b8cce6c24
6,191
java
Java
core/src/test/java/com/origin/insurancehub/usecases/CalculateInsuranceTestInteractorTest.java
Thiago-AS/insurance-hub
26e4cb9346e43a2f9f42b43cd19e08b6ea08b4ac
[ "MIT" ]
null
null
null
core/src/test/java/com/origin/insurancehub/usecases/CalculateInsuranceTestInteractorTest.java
Thiago-AS/insurance-hub
26e4cb9346e43a2f9f42b43cd19e08b6ea08b4ac
[ "MIT" ]
null
null
null
core/src/test/java/com/origin/insurancehub/usecases/CalculateInsuranceTestInteractorTest.java
Thiago-AS/insurance-hub
26e4cb9346e43a2f9f42b43cd19e08b6ea08b4ac
[ "MIT" ]
null
null
null
42.115646
104
0.636569
1,001,582
package com.origin.insurancehub.usecases; import com.origin.insurancehub.entities.house.House; import com.origin.insurancehub.entities.house.OwnershipStatus; import com.origin.insurancehub.entities.insurance.Insurance; import com.origin.insurancehub.entities.insurance.InsurancePlan; import com.origin.insurancehub.entities.insurance.ListIsuranceItem; import com.origin.insurancehub.entities.user.MaritalStatus; import com.origin.insurancehub.entities.user.User; import com.origin.insurancehub.entities.vehicle.Vehicle; import com.origin.insurancehub.usecases.calculateinsurance.CalculateInsuranceInteractor; import com.origin.insurancehub.usecases.calculateinsurance.CalculateInsurancePresenter; import com.origin.insurancehub.usecases.calculateinsurance.CalculateInsuranceRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) class CalculateInsuranceTestInteractorTest { @Mock private CalculateInsurancePresenter presenter; private CalculateInsuranceInteractor interactor; @BeforeEach void setUp() { this.interactor = new CalculateInsuranceInteractor(this.presenter); } @Test void shouldReturnAllIneligibleInsurances() { final CalculateInsuranceRequest request = CalculateInsuranceRequest.builder() .vehicles(List.of()) .houses(List.of()) .income(0L) .riskQuestions(List.of(0, 1, 0)) .dependents(0L) .maritalStatus(MaritalStatus.SINGLE) .age(65L) .build(); final Insurance insurance = Insurance.builder() .user(buildUserFromRequest(request)) .life(InsurancePlan.INELIGIBLE) .home(List.of()) .auto(List.of()) .disability(InsurancePlan.INELIGIBLE) .umbrella(InsurancePlan.INELIGIBLE) .build(); this.interactor.execute(request); verify(this.presenter).success(insurance); } @Test void shouldReturnCalculatedInsurances() { final CalculateInsuranceRequest request = CalculateInsuranceRequest.builder() .vehicles(List.of(Vehicle.builder().id(1L).year(2018L).build())) .houses(List.of(House.builder().id(2L).ownershipStatus(OwnershipStatus.OWNED).build())) .income(0L) .riskQuestions(List.of(0, 1, 0)) .dependents(2L) .maritalStatus(MaritalStatus.MARRIED) .age(35L) .build(); final Insurance insurance = Insurance.builder() .user(buildUserFromRequest(request)) .life(InsurancePlan.REGULAR) .home(List.of(ListIsuranceItem.builder().id(2L).plan(InsurancePlan.ECONOMIC).build())) .auto(List.of(ListIsuranceItem.builder().id(1L).plan(InsurancePlan.REGULAR).build())) .disability(InsurancePlan.INELIGIBLE) .umbrella(InsurancePlan.ECONOMIC) .build(); this.interactor.execute(request); verify(this.presenter).success(insurance); } @Test void shouldCountSecondRiskQuestionInDisabilityInsurance() { final CalculateInsuranceRequest request = CalculateInsuranceRequest.builder() .vehicles(List.of(Vehicle.builder().id(1L).year(2018L).build())) .houses(List.of(House.builder().id(2L).ownershipStatus(OwnershipStatus.OWNED).build())) .income(100_000L) .riskQuestions(List.of(0, 1, 0)) .dependents(2L) .maritalStatus(MaritalStatus.SINGLE) .age(35L) .build(); final Insurance insurance = Insurance.builder() .user(buildUserFromRequest(request)) .life(InsurancePlan.REGULAR) .home(List.of(ListIsuranceItem.builder().id(2L).plan(InsurancePlan.ECONOMIC).build())) .auto(List.of(ListIsuranceItem.builder().id(1L).plan(InsurancePlan.REGULAR).build())) .disability(InsurancePlan.RESPONSIBLE) .umbrella(InsurancePlan.ECONOMIC) .build(); this.interactor.execute(request); verify(this.presenter).success(insurance); } @Test void shouldReturnAllInsurancesIneligible() { final CalculateInsuranceRequest request = CalculateInsuranceRequest.builder() .vehicles(List.of(Vehicle.builder().id(1L).year(2018L).build())) .houses(List.of(House.builder().id(2L).ownershipStatus(OwnershipStatus.OWNED).build())) .income(20_000L) .riskQuestions(List.of(0, 0, 0)) .dependents(2L) .maritalStatus(MaritalStatus.SINGLE) .age(35L) .build(); final Insurance insurance = Insurance.builder() .user(buildUserFromRequest(request)) .life(InsurancePlan.INELIGIBLE) .home(List.of(ListIsuranceItem.builder().id(2L).plan(InsurancePlan.INELIGIBLE).build())) .auto(List.of(ListIsuranceItem.builder().id(1L).plan(InsurancePlan.INELIGIBLE).build())) .disability(InsurancePlan.INELIGIBLE) .umbrella(InsurancePlan.INELIGIBLE) .build(); this.interactor.execute(request); verify(this.presenter).success(insurance); } private User buildUserFromRequest(final CalculateInsuranceRequest request) { return User.builder() .age(request.getAge()) .dependents(request.getDependents()) .houses(request.getHouses()) .income(request.getIncome()) .maritalStatus(request.getMaritalStatus()) .riskQuestions(request.getRiskQuestions()) .vehicles(request.getVehicles()) .build(); } }
92409697bb034b1ad051ea149876c4b4a25db337
1,850
java
Java
grus-framework/grus-core/src/main/java/com/ciicgat/sdk/lang/tool/ReadResourceUtils.java
guanaitong/grus
e3817ec49efb6ef5aeb5e0a64f68b1eb77de66a0
[ "Apache-2.0" ]
3
2021-12-06T04:00:12.000Z
2021-12-30T09:25:36.000Z
grus-framework/grus-core/src/main/java/com/ciicgat/sdk/lang/tool/ReadResourceUtils.java
guanaitong/grus
e3817ec49efb6ef5aeb5e0a64f68b1eb77de66a0
[ "Apache-2.0" ]
null
null
null
grus-framework/grus-core/src/main/java/com/ciicgat/sdk/lang/tool/ReadResourceUtils.java
guanaitong/grus
e3817ec49efb6ef5aeb5e0a64f68b1eb77de66a0
[ "Apache-2.0" ]
1
2021-12-06T04:01:14.000Z
2021-12-06T04:01:14.000Z
28.90625
106
0.628649
1,001,583
/* * Copyright 2007-2021, CIIC Guanaitong, Co., Ltd. * All rights reserved. */ package com.ciicgat.sdk.lang.tool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * 读取配置文件工具类 * * @author jonathan * @version $Id: ReadResourceUtils.java, v 0.1 2011-11-25 下午01:10:50 trunks Exp $ */ public final class ReadResourceUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ReadResourceUtils.class); private static ConcurrentMap<String, Properties> propertiesMap = new ConcurrentHashMap<>(); private ReadResourceUtils() { } /** * 获取属性文件。<br /> * * @param filename 文件的路径,方法内部会修改路径以"/"开始。 * @return */ public static Properties getPropertyFile(String filename) { Properties prop = propertiesMap.get(filename); if (prop != null) { return prop; } return propertiesMap.computeIfAbsent(filename, filename1 -> { if (!filename1.startsWith("/")) { filename1 = "/" + filename1; } InputStream in = ReadResourceUtils.class.getResourceAsStream(filename1); BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); Properties prop1 = new Properties(); try { prop1.load(reader); } catch (Exception e) { LOGGER.error("读取配置文件[" + filename1 + "]出错:", e); } finally { CloseUtils.close(reader); CloseUtils.close(in); } return prop1; }); } }
9240969dbe6e6ef663bc74f6229fc932df40b25f
2,616
java
Java
src/main/java/org/zeroturnaround/jenkins/updateModes/Hotpatch.java
zeroturnaround/jenkins-liverebel-plugin
1745880edcfd72325d6c29752bc0dd8a3d883cb7
[ "Apache-2.0" ]
null
null
null
src/main/java/org/zeroturnaround/jenkins/updateModes/Hotpatch.java
zeroturnaround/jenkins-liverebel-plugin
1745880edcfd72325d6c29752bc0dd8a3d883cb7
[ "Apache-2.0" ]
null
null
null
src/main/java/org/zeroturnaround/jenkins/updateModes/Hotpatch.java
zeroturnaround/jenkins-liverebel-plugin
1745880edcfd72325d6c29752bc0dd8a3d883cb7
[ "Apache-2.0" ]
null
null
null
36.333333
257
0.750382
1,001,584
package org.zeroturnaround.jenkins.updateModes; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.kohsuke.stapler.DataBoundConstructor; import org.zeroturnaround.liverebel.plugins.PluginUtil; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Hudson; public class Hotpatch extends UpdateMode{ public final boolean updateWithWarnings; public final int requestPause; public final UpdateMode fallback; public Hotpatch() { this.fallback = null; updateWithWarnings = false; requestPause = PluginUtil.DEFAULT_REQUEST_PAUSE; } @DataBoundConstructor public Hotpatch(boolean updateWithWarnings, int requestPause, UpdateMode fallback) { this.updateWithWarnings = updateWithWarnings; this.requestPause = requestPause; this.fallback = fallback; } @Override public String toString() { return "Hotpatch"; } @Extension public static class DescriptorImpl extends Descriptor<UpdateMode> { public Descriptor<org.zeroturnaround.jenkins.updateModes.UpdateMode> getDefaultFallbackUpdate() { DescriptorExtensionList<org.zeroturnaround.jenkins.updateModes.UpdateMode, Descriptor<org.zeroturnaround.jenkins.updateModes.UpdateMode>> allDescriptors = Hudson.getInstance().getDescriptorList(org.zeroturnaround.jenkins.updateModes.UpdateMode.class); Iterator<Descriptor<org.zeroturnaround.jenkins.updateModes.UpdateMode>> it = allDescriptors.iterator(); while (it.hasNext()) { Descriptor<org.zeroturnaround.jenkins.updateModes.UpdateMode> next = it.next(); if (next.clazz == RollingRestarts.class) { return next; } } return null; } public List<Descriptor<UpdateMode>> getFallbackUpdateModes() { DescriptorExtensionList<org.zeroturnaround.jenkins.updateModes.UpdateMode, Descriptor<org.zeroturnaround.jenkins.updateModes.UpdateMode>> allDescriptors = Hudson.getInstance().getDescriptorList(org.zeroturnaround.jenkins.updateModes.UpdateMode.class); List<Descriptor<UpdateMode>> fallbackUpdateModes = new ArrayList<Descriptor<UpdateMode>>(); Iterator<Descriptor<UpdateMode>> it = allDescriptors.iterator(); while (it.hasNext()) { Descriptor<org.zeroturnaround.jenkins.updateModes.UpdateMode> next = it.next(); if (next.clazz != Hotpatch.class) { fallbackUpdateModes.add(next); } } return fallbackUpdateModes; } @Override public String getDisplayName() { return "Hotpatch (only for Java applications)"; } } }
924096c935c15d89c8f1515c4f4c917681c04302
2,370
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/MeasuringTapeAuto10.java
SimonFromNeedham/T-10-actual-19-20
38213fcd2717d7d7113bf4b15431d42d3f87f61d
[ "MIT" ]
1
2019-12-11T02:41:12.000Z
2019-12-11T02:41:12.000Z
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/MeasuringTapeAuto10.java
SimonFromNeedham/T-10-actual-19-20
38213fcd2717d7d7113bf4b15431d42d3f87f61d
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/MeasuringTapeAuto10.java
SimonFromNeedham/T-10-actual-19-20
38213fcd2717d7d7113bf4b15431d42d3f87f61d
[ "MIT" ]
1
2019-10-03T19:08:01.000Z
2019-10-03T19:08:01.000Z
28.902439
115
0.534177
1,001,585
package org.firstinspires.ftc.teamcode; import android.graphics.Color; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit; @Autonomous(name = "Measuring Tape Autonomous 10b") public class MeasuringTapeAuto10 extends Library{ enum State{ PARKING, END } State currentState; ElapsedTime clock = new ElapsedTime(); boolean moving = false; private final double SCALE_FACTOR = 255; private float[] hsvValues = { 0F, 0F, 0F }; @Override public void init(){ hardwareInit(); currentState = State.PARKING; } public void loop(){ /* Loop constantly checks state, and then executes a command based on this. */ if( currentState == State.PARKING ){ Parking(); } if( currentState == State.END ){ Stop(); } Telemetry(); } public void Parking(){ if( !moving ){ clock.reset(); moving = true; }else if( clock.seconds() <= 10 ){ tapeMeasure.setPower(1); }else{ tapeMeasure.setPower(0); currentState = State.END; } // if(!moving){ // clock.reset(); // moving = true; // }else if(hsvValues[0] <= 60 || clock.seconds()>=6){ // moving = false; // drive(0,0,0); // currentState = State.END; // }else if(clock.seconds()>=5){ // drive(0, 0, -.3f); // }else{ // drive(0,0,.4f); // } // // if( distanceLeft.getDistance(DistanceUnit.CM)>8 || distanceRight.getDistance(DistanceUnit.CM)>8){ // drive(.3f,0,0); // } } public void Stop(){ moving = false; drive(0, 0, 0); } private void Telemetry(){ telemetry.addData("Millis since State Start: ", clock.seconds()); telemetry.addData("State: ", currentState); telemetry.addData("Distamce Left: ", distanceLeft.getDistance(DistanceUnit.CM)); telemetry.addData("Distamce Right: ", distanceRight.getDistance(DistanceUnit.CM)); } }
924096c9a42d3415c8d1844e0e91f507879a4f0a
6,309
java
Java
ide/db.mysql/src/org/netbeans/modules/db/mysql/ui/PropertiesDialog.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,056
2019-04-25T20:00:35.000Z
2022-03-30T04:46:14.000Z
ide/db.mysql/src/org/netbeans/modules/db/mysql/ui/PropertiesDialog.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,846
2019-04-25T20:50:05.000Z
2022-03-31T23:40:41.000Z
ide/db.mysql/src/org/netbeans/modules/db/mysql/ui/PropertiesDialog.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
550
2019-04-25T20:04:33.000Z
2022-03-25T17:43:01.000Z
34.664835
92
0.651767
1,001,586
/* * 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.netbeans.modules.db.mysql.ui; import java.awt.Dialog; import java.util.logging.Logger; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.netbeans.modules.db.mysql.DatabaseServer; import org.netbeans.modules.db.mysql.impl.ServerNodeProvider; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; /** * * @author David */ public class PropertiesDialog { private static final Logger LOGGER = Logger.getLogger(PropertiesDialog.class.getName()); private static final String HELP_CTX = PropertiesDialog.class.getName(); public enum Tab { BASIC, ADMIN }; private final JTabbedPane tabbedPane; private final BasePropertiesPanel basePanel; private final AdminPropertiesPanel adminPanel; private final DatabaseServer server; public PropertiesDialog(DatabaseServer server) { this.server = server; basePanel = new BasePropertiesPanel(server); adminPanel = new AdminPropertiesPanel(server); tabbedPane = createTabbedPane(basePanel, adminPanel); } /** * Display the properties dialog * * @return true if the user confirmed changes, false if they canceled */ public boolean displayDialog() { return displayDialog(Tab.BASIC); } /** * Display the properties dialog, choosing which tab you want to have * initial focus * * @param focusTab * @return true if the user confirmed changes, false if they canceled */ public boolean displayDialog(Tab focusTab) { DialogDescriptor descriptor = createDialogDescriptor(); if ( focusTab == Tab.ADMIN ) { tabbedPane.setSelectedIndex(1); } boolean ok = displayDialog(descriptor); if ( ok ) { updateServer(); } return ok; } private static JTabbedPane createTabbedPane(JPanel basePanel, JPanel adminPanel) { JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.addTab( getMessage("PropertiesDialog.BasePanelTitle"), /* icon */ null, basePanel, getMessage("PropertiesDialog.BasePanelHint")); tabbedPane.addTab( getMessage("PropertiesDialog.AdminPanelTitle"), /* icon */ null, adminPanel, getMessage("PropertiesDialog.AdminPanelHint")); tabbedPane.getAccessibleContext().setAccessibleName( getMessage("PropertiesDialog.ACS_Name")); tabbedPane.getAccessibleContext().setAccessibleDescription( getMessage("PropertiesDialog.ACS_Desc")); return tabbedPane; } private DialogDescriptor createDialogDescriptor() { DialogDescriptor descriptor = new DialogDescriptor( tabbedPane, getMessage("PropertiesDialog.Title")); descriptor.setHelpCtx(new HelpCtx(HELP_CTX)); basePanel.setDialogDescriptor(descriptor); adminPanel.setDialogDescriptor(descriptor); return descriptor; } private boolean displayDialog(DialogDescriptor descriptor) { Dialog dialog = DialogDisplayer.getDefault().createDialog(descriptor); dialog.setVisible(true); dialog.dispose(); return DialogDescriptor.OK_OPTION.equals(descriptor.getValue()); } private void updateServer() { if (! basePanel.getHost().equals(server.getHost())) { server.setHost(basePanel.getHost()); } if (! basePanel.getPort().equals(server.getPort())) { server.setPort(basePanel.getPort()); } if (! basePanel.getUser().equals(server.getUser())) { server.setUser(basePanel.getUser()); } if (! basePanel.getPassword().equals(server.getPassword())) { server.setPassword(basePanel.getPassword()); } if (basePanel.getSavePassword() != server.isSavePassword()) { server.setSavePassword(basePanel.getSavePassword()); } if (! adminPanel.getAdminPath().equals(server.getAdminPath())) { server.setAdminPath(adminPanel.getAdminPath()); } if (! adminPanel.getAdminArgs().equals(server.getAdminArgs())) { server.setAdminArgs(adminPanel.getAdminArgs()); } if (! adminPanel.getStartPath().equals(server.getStartPath())) { server.setStartPath(adminPanel.getStartPath()); } if (! adminPanel.getStartArgs().equals(server.getStartArgs())) { server.setStartArgs(adminPanel.getStartArgs()); } if (! adminPanel.getStopPath().equals(server.getStopPath())) { server.setStopPath(adminPanel.getStopPath()); } if (! adminPanel.getStopArgs().equals(server.getStopArgs())) { server.setStopArgs(adminPanel.getStopArgs()); } ServerNodeProvider provider = ServerNodeProvider.getDefault(); if ( ! provider.isRegistered() ) { // setRegistered will connect the server provider.setRegistered(true); } } private static String getMessage(String id) { return NbBundle.getMessage(PropertiesDialog.class, id); } public void setErrorMessage(String msg) { basePanel.setErrorMessage(msg); } }
924096e7c26c728966b63a3c2e00bce710e4410a
1,159
java
Java
app/models/TimeTracking.java
brunoluizdesiqueira/TimeTracking
93a377200988447acbfd48071cee435293505149
[ "Apache-2.0" ]
null
null
null
app/models/TimeTracking.java
brunoluizdesiqueira/TimeTracking
93a377200988447acbfd48071cee435293505149
[ "Apache-2.0" ]
null
null
null
app/models/TimeTracking.java
brunoluizdesiqueira/TimeTracking
93a377200988447acbfd48071cee435293505149
[ "Apache-2.0" ]
null
null
null
25.195652
121
0.746333
1,001,587
package models; import com.avaje.ebean.Model; import models.enumeradores.TipoTransicao; import javax.persistence.*; import java.time.Duration; import java.util.ArrayList; import java.util.List; /** * @author Bruno * Classe TimeTracking responsável por controlar as diversas alterações da linha do tempo * */ @Entity @Table(name = "timeTracking") public class TimeTracking extends Model{ @Id @GeneratedValue private long id; @OneToMany(mappedBy = "timeTracking") private List<TimeLine> timeLine; @OneToOne(mappedBy = "timeTracking") private Tarefa tarefa; public TimeTracking() { this.timeLine = new ArrayList<TimeLine>(); } public Duration getTempoTotal() { return Duration.between(this.timeLine.get(0).getInstante(), this.timeLine.get(this.timeLine.size() -1).getInstante()); } public long getId() { return id; } public List<TimeLine> getTimeLine() { return timeLine; } public void setTimeLine(List<TimeLine> timeLine) { this.timeLine = timeLine; } public void registrar(TipoTransicao transicao, String descricao, Usuario usuarioParecer){ timeLine.add(new TimeLine(transicao, descricao, usuarioParecer)); } }
924097fd6e8ea5896fb560a4f5406ee0545fa4b6
31,100
java
Java
restx-factory/src/test/java/restx/factory/FactoryTest.java
walien/restx
ef3f3d56de1f04839d5a1921ff23fade77747067
[ "Apache-2.0" ]
253
2015-01-06T21:34:39.000Z
2021-11-22T08:48:27.000Z
restx-factory/src/test/java/restx/factory/FactoryTest.java
walien/restx
ef3f3d56de1f04839d5a1921ff23fade77747067
[ "Apache-2.0" ]
182
2015-01-02T10:26:07.000Z
2021-09-30T08:06:22.000Z
restx-factory/src/test/java/restx/factory/FactoryTest.java
walien/restx
ef3f3d56de1f04839d5a1921ff23fade77747067
[ "Apache-2.0" ]
52
2015-01-10T19:33:17.000Z
2021-02-08T17:58:50.000Z
45.735294
139
0.598682
1,001,588
package restx.factory; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import org.junit.After; import org.junit.Test; import java.util.Set; import static org.assertj.core.api.Assertions.*; import static restx.factory.Factory.LocalMachines.threadLocal; /** * User: xavierhanin * Date: 1/31/13 * Time: 7:11 PM */ public class FactoryTest { @Test public void should_compare_named_component() throws Exception { assertThat(Factory.NAMED_COMPONENT_COMPARATOR.compare( NamedComponent.of(String.class, "test1", 0, "A"), NamedComponent.of(String.class, "test2", 0, "A") )).isLessThan(0); assertThat(Factory.NAMED_COMPONENT_COMPARATOR.compare( NamedComponent.of(String.class, "test", 0, "A"), NamedComponent.of(String.class, "test2", 0, "A") )).isLessThan(0); assertThat(Factory.NAMED_COMPONENT_COMPARATOR.compare( NamedComponent.of(String.class, "test2", -10, "A"), NamedComponent.of(String.class, "test1", 0, "A") )).isLessThan(0); } @Test public void should_build_new_component_from_single_machine() throws Exception { Factory factory = Factory.builder().addMachine(testMachine()).build(); Optional<NamedComponent<String>> component = factory.queryByName(Name.of(String.class, "test")).findOne(); assertThat(component.isPresent()).isTrue(); assertThat(component.get().getName()).isEqualTo(Name.of(String.class, "test")); assertThat(component.get().getComponent()).isEqualTo("value1"); assertThat(factory.queryByName(Name.of(String.class, "test")).findOne().get()).isEqualTo(component.get()); } @Test public void should_concat_new_single_machine() throws Exception { Factory factory = Factory.builder().addMachine(testMachine()).build(); factory = factory.concat(new SingletonFactoryMachine<>(0, NamedComponent.of(String.class, "c2", "v2"))); assertThat(factory.getComponent(Name.of(String.class, "test"))).isEqualTo("value1"); assertThat(factory.getComponent(Name.of(String.class, "c2"))).isEqualTo("v2"); } @Test public void should_build_with_warehouse() throws Exception { Factory factory = Factory.builder().addMachine(testMachine()).addMachine(testMachine("test3")).build(); factory.getComponent(Name.of(String.class, "test")); // this will build the component and put it into the warehouse factory = Factory.builder() .addMachine(testMachine("test2")) .addWarehouseProvider(factory.getWarehouse()) .build(); assertThat(factory.getComponent(Name.of(String.class, "test"))).isEqualTo("value1"); assertThat(factory.getComponent(Name.of(String.class, "test2"))).isEqualTo("value1"); assertThat(factory.queryByName(Name.of(String.class, "test3")).optional().findOne().isPresent()).isFalse(); } @Test public void should_start_auto_startable() throws Exception { LifecycleComponent lifecycleComponent = new LifecycleComponent(); Factory factory = Factory.builder().addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of( AutoStartable.class, "t", lifecycleComponent))).build(); factory.start(); assertThat(lifecycleComponent.started).isTrue(); } @Test public void should_start_auto_startable_in_order() throws Exception { final LifecycleComponent lifecycleComponent1 = new LifecycleComponent(); final boolean[] l2Started = new boolean[1]; final boolean[] wasL1Started = new boolean[1]; Factory factory = Factory.builder() .addMachine(new SingletonFactoryMachine<>(10, NamedComponent.of( AutoStartable.class, "t0", new AutoStartable() { @Override public void start() { wasL1Started[0] = lifecycleComponent1.started; l2Started[0] = true; } } ))) .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of( AutoStartable.class, "t1", lifecycleComponent1))) .build(); factory.start(); assertThat(lifecycleComponent1.started).isTrue(); assertThat(l2Started[0]).isTrue(); assertThat(wasL1Started[0]).isTrue(); } @Test public void should_prepare_auto_preparable() throws Exception { LifecycleComponent lifecycleComponent = new LifecycleComponent(); Factory factory = Factory.builder().addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of( AutoPreparable.class, "t", lifecycleComponent))).build(); factory.prepare(); assertThat(lifecycleComponent.prepared).isTrue(); } @Test public void should_not_close_closeable_from_other_warehouse() throws Exception { LifecycleComponent lifecycleComponent = new LifecycleComponent(); Factory factory = Factory.builder().addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of( AutoStartable.class, "t", lifecycleComponent))).build(); factory.start(); assertThat(lifecycleComponent.started).isTrue(); Factory otherFactory = Factory.builder() .addMachine(testMachine()) .addWarehouseProvider(factory.getWarehouse()) .build(); assertThat(otherFactory.getComponents(AutoStartable.class)).containsOnly(lifecycleComponent); otherFactory.close(); assertThat(lifecycleComponent.closed).isFalse(); factory.close(); assertThat(lifecycleComponent.closed).isTrue(); } @Test public void should_build_new_component_with_deps() throws Exception { Factory factory = Factory.builder() .addMachine(testMachine()) .addMachine(new SingleNameFactoryMachine<>( 0, new StdMachineEngine<String>(Name.of(String.class, "test2"), BoundlessComponentBox.FACTORY) { private Factory.Query<String> stringQuery = Factory.Query.byName(Name.of(String.class, "test")); @Override public BillOfMaterials getBillOfMaterial() { return BillOfMaterials.of(stringQuery); } @Override protected String doNewComponent(SatisfiedBOM satisfiedBOM) { return satisfiedBOM.getOne(stringQuery).get().getComponent() + " value2"; } })) .build(); Optional<NamedComponent<String>> component = factory.queryByName(Name.of(String.class, "test2")).findOne(); assertThat(component.isPresent()).isTrue(); assertThat(component.get().getName()).isEqualTo(Name.of(String.class, "test2")); assertThat(component.get().getComponent()).isEqualTo("value1 value2"); assertThat(factory.getComponent(Name.of(String.class, "test2"))).isEqualTo("value1 value2"); assertThat(factory.queryByName(Name.of(String.class, "test2")).findOne().get()).isEqualTo(component.get()); } @Test public void should_fail_with_missing_deps() throws Exception { SingleNameFactoryMachine<String> machine = machineWithMissingDependency(); Factory factory = Factory.builder().addMachine(machine).build(); try { factory.queryByName(Name.of(String.class, "test")).findOne(); fail("should raise exception when asking for a component with missing dependency"); } catch (IllegalStateException e) { assertThat(e) .hasMessageStartingWith( "\n" + " QueryByName{name=Name{name='test', clazz=java.lang.String[]}}\n" + " | \\__=> Name{name='test', clazz=java.lang.String[]}\n" + " |\n" + " +-> QueryByName{name=Name{name='missing', clazz=java.lang.String[]}}\n" + " |\n" + " +--: Name{name='missing', clazz=java.lang.String[]} can't be satisfied") ; } } @Test public void should_fail_with_circular_dependencies() throws Exception { Factory factory = Factory.builder() .addMachine(failingSingleDepMachine("test5", "test4")) .addMachine(failingSingleDepMachine("test4", "test3")) .addMachine(failingSingleDepMachine("test3", "test2")) .addMachine(failingSingleDepMachine("test2", "test1")) .addMachine(failingSingleDepMachine("test1", "test4")) .build(); try { factory.queryByName(Name.of(String.class, "test5")).findOne(); fail("should raise exception when asking for a component with circular dependency"); } catch (IllegalStateException e) { assertThat(e) .hasMessage( "Circular dependency detected : \n" + "-> Name{name='test4', clazz=java.lang.String[]}\n" + " -> Name{name='test3', clazz=java.lang.String[]}\n" + " -> Name{name='test2', clazz=java.lang.String[]}\n" + " -> Name{name='test1', clazz=java.lang.String[]}\n" + " -> Name{name='test4', clazz=java.lang.String[]}\n" + "\n" + "Please, fix this as current RestX DI can't handle cycles.") ; } } @Test public void should_fail_with_similar_components() throws Exception { SingleNameFactoryMachine<String> machine = machineWithMissingDependency(); Factory factory = Factory.builder().addMachine(machine).addMachine(testMachine("ASIMILARCOMPONENT")).build(); try { factory.queryByName(Name.of(String.class, "test")).findOne(); fail("should raise exception when asking for a component with missing dependency"); } catch (IllegalStateException e) { assertThat(e) .hasMessageContaining("ASIMILARCOMPONENT") ; } } @Test public void should_find_one_when_multiple_available_fail() throws Exception { Factory factory = Factory.builder().addMachine(testMachine("test")).addMachine(testMachine("test2")).build(); try { factory.queryByClass(String.class).findOne(); fail("should raise exception when asking for one component with multiple available"); } catch (IllegalStateException e) { assertThat(e) .hasMessage("more than one component is available for query QueryByClass{componentClass=java.lang.String[]}.\n" + " Please select which one you want with a more specific query,\n" + " or by deactivating one of the available components.\n" + " Available components:\n" + " - NamedComponent{name=Name{name='test', clazz=java.lang.String[]}, priority=0, component=value1}\n" + " [Activation key: 'restx.activation::java.lang.String::test']\n" + " - NamedComponent{name=Name{name='test2', clazz=java.lang.String[]}, priority=0, component=value1}\n" + " [Activation key: 'restx.activation::java.lang.String::test2']\n") ; } } @Test public void should_warn_about_missing_annotated_machine() throws Exception { Factory factory = Factory.builder().addFromServiceLoader().build(); assertThat(factory.dump()).contains(TestMissingAnnotatedMachine.class.getName()); } @Test public void should_dump_list_overrider() throws Exception { SingleNameFactoryMachine<String> machine1 = testMachine(); SingleNameFactoryMachine<String> machine2 = overridingMachine(); Factory factory = Factory.builder() .addMachine(machine1) .addMachine(machine2) .build(); assertThat(factory.dump()).contains("OVERRIDING:\n " + machine1); } @Test public void should_customize_component() throws Exception { Factory factory = Factory.builder() .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of( String.class, "test", "hello"))) .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(ComponentCustomizerEngine.class, "cutomizerTest", new ComponentCustomizerEngine() { @Override public <T> boolean canCustomize(Name<T> name) { return name.getClazz() == String.class; } @Override public <T> ComponentCustomizer<T> getCustomizer(Name<T> name) { return new ComponentCustomizer<T>() { @Override public int priority() { return 0; } @Override @SuppressWarnings("unchecked") public NamedComponent<T> customize(NamedComponent<T> namedComponent) { return new NamedComponent<>( namedComponent.getName(), (T) (namedComponent.getComponent() + " world")); } }; } }))) .build(); Optional<NamedComponent<String>> component = factory.queryByName(Name.of(String.class, "test")).findOne(); assertThat(component.isPresent()).isTrue(); assertThat(component.get().getName()).isEqualTo(Name.of(String.class, "test")); assertThat(component.get().getComponent()).isEqualTo("hello world"); assertThat(factory.queryByName(Name.of(String.class, "test")).findOne().get()).isEqualTo(component.get()); } @Test public void should_customize_component_with_simple_customizer() throws Exception { Factory factory = Factory.builder() .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of( String.class, "test", "hello"))) .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(ComponentCustomizerEngine.class, "cutomizerTest", new SingleComponentClassCustomizerEngine<String>(0, String.class) { @Override public NamedComponent<String> customize(NamedComponent<String> namedComponent) { return new NamedComponent<>( namedComponent.getName(), namedComponent.getComponent() + " world"); } }))) .build(); Optional<NamedComponent<String>> component = factory.queryByName(Name.of(String.class, "test")).findOne(); assertThat(component.isPresent()).isTrue(); assertThat(component.get().getComponent()).isEqualTo("hello world"); } @Test public void should_customize_component_with_customizer_with_deps() throws Exception { Factory factory = Factory.builder() .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of( String.class, "dep", "world"))) .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of( String.class, "test", "hello"))) .addMachine(new SingleNameFactoryMachine<>(0, new StdMachineEngine<ComponentCustomizerEngine>( Name.of(ComponentCustomizerEngine.class, "cutomizerTest"), BoundlessComponentBox.FACTORY) { private Factory.Query<String> query = Factory.Query.byName(Name.of(String.class, "dep")); @Override public BillOfMaterials getBillOfMaterial() { return BillOfMaterials.of(query); } @Override protected ComponentCustomizerEngine doNewComponent(final SatisfiedBOM satisfiedBOM) { return new SingleComponentClassCustomizerEngine<String>(0, String.class) { @Override public NamedComponent<String> customize(NamedComponent<String> namedComponent) { return new NamedComponent<>( namedComponent.getName(), namedComponent.getComponent() + " " + satisfiedBOM.getOne(query).get().getComponent()); } }; } })) .build(); Optional<NamedComponent<String>> component = factory.queryByName(Name.of(String.class, "test")).findOne(); assertThat(component.isPresent()).isTrue(); assertThat(component.get().getComponent()).isEqualTo("hello world"); } @Test public void should_handle_machine_factory_to_build_conditional_component() throws Exception { SingleNameFactoryMachine<FactoryMachine> alternativeMachine = alternativeMachine(); Factory factory = Factory.builder() .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(String.class, "mode", "dev"))) .addMachine(alternativeMachine) .build(); Optional<NamedComponent<String>> component = factory.queryByName(Name.of(String.class, "test")).optional().findOne(); assertThat(component.isPresent()).isTrue(); assertThat(component.get().getComponent()).isEqualTo("hello"); factory = Factory.builder() .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(String.class, "mode", "prod"))) .addMachine(alternativeMachine) .build(); component = factory.queryByName(Name.of(String.class, "test")).optional().findOne(); assertThat(component.isPresent()).isFalse(); } @Test public void should_handle_machine_factory_to_build_alternative() throws Exception { SingleNameFactoryMachine<FactoryMachine> alternativeMachine = alternativeMachine(); Factory factory = Factory.builder() .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(String.class, "mode", "dev"))) .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(String.class, "test", "default"))) .addMachine(alternativeMachine) .build(); Optional<NamedComponent<String>> component = factory.queryByName(Name.of(String.class, "test")).optional().findOne(); assertThat(component.isPresent()).isTrue(); assertThat(component.get().getComponent()).isEqualTo("hello"); factory = Factory.builder() .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(String.class, "mode", "prod"))) .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(String.class, "test", "default"))) .addMachine(alternativeMachine) .build(); component = factory.queryByName(Name.of(String.class, "test")).optional().findOne(); assertThat(component.isPresent()).isTrue(); assertThat(component.get().getComponent()).isEqualTo("default"); } @Test public void should_handle_machine_factory_with_dependencies_on_other_machine_factory() throws Exception { SingleNameFactoryMachine<FactoryMachine> alternativeMachine = alternativeMachine(); SingleNameFactoryMachine<FactoryMachine> dependentMachine = new SingleNameFactoryMachine<>(0, new StdMachineEngine<FactoryMachine>( Name.of(FactoryMachine.class, "machineFactoryTest2"), BoundlessComponentBox.FACTORY) { private Factory.Query<String> query = Factory.Query.byName(Name.of(String.class, "test")); @Override public BillOfMaterials getBillOfMaterial() { return BillOfMaterials.of(query); } @Override protected FactoryMachine doNewComponent(final SatisfiedBOM satisfiedBOM) { return new SingletonFactoryMachine<>(0, NamedComponent.of( String.class, "test2", satisfiedBOM.getOne(query).get().getComponent() + " world")); } }); Factory factory = Factory.builder() .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(String.class, "mode", "dev"))) .addMachine(alternativeMachine) .addMachine(dependentMachine) .build(); Optional<NamedComponent<String>> component = factory.queryByName(Name.of(String.class, "test2")).optional().findOne(); assertThat(component.isPresent()).isTrue(); assertThat(component.get().getComponent()).isEqualTo("hello world"); } private SingleNameFactoryMachine<FactoryMachine> alternativeMachine() { return new AlternativesFactoryMachine<>(0, Name.of(String.class, "mode"), ImmutableMap.of("dev", new SingletonFactoryMachine<>(-100, NamedComponent.of( String.class, "test", "hello"))), BoundlessComponentBox.FACTORY); } @Test @SuppressWarnings("unchecked") public void should_build_component_lists_from_multiple_machines() throws Exception { Factory factory = Factory.builder() .addMachine(new SingleNameFactoryMachine<>( 0, new NoDepsMachineEngine<String>(Name.of(String.class, "test 1"), BoundlessComponentBox.FACTORY) { @Override protected String doNewComponent(SatisfiedBOM satisfiedBOM) { return "value 1"; } })) .addMachine(new SingleNameFactoryMachine<>( 0, new NoDepsMachineEngine<String>(Name.of(String.class, "test 2"), BoundlessComponentBox.FACTORY) { @Override protected String doNewComponent(SatisfiedBOM satisfiedBOM) { return "value 2"; } })) .build(); Set<NamedComponent<String>> components = factory.queryByClass(String.class).find(); assertThat(components).containsExactly( NamedComponent.of(String.class, "test 1", "value 1"), NamedComponent.of(String.class, "test 2", "value 2")); } @Test @SuppressWarnings("unchecked") public void should_respect_component_priorities() throws Exception { Factory factory = Factory.builder() .addMachine(new SingleNameFactoryMachine<>( 0, new NoDepsMachineEngine<String>(Name.of(String.class, "test 1"), 1, BoundlessComponentBox.FACTORY) { @Override protected String doNewComponent(SatisfiedBOM satisfiedBOM) { return "value 1"; } })) .addMachine(new SingleNameFactoryMachine<>( 0, new NoDepsMachineEngine<String>(Name.of(String.class, "test 2"), 0, BoundlessComponentBox.FACTORY) { @Override protected String doNewComponent(SatisfiedBOM satisfiedBOM) { return "value 2"; } })) .build(); Set<NamedComponent<String>> components = factory.queryByClass(String.class).find(); assertThat(components).containsExactly( NamedComponent.of(String.class, "test 2", "value 2"), NamedComponent.of(String.class, "test 1", "value 1")); } @Test public void should_factory_be_queryable() throws Exception { Factory factory = Factory.builder().build(); assertThat(factory.queryByClass(Factory.class).findAsComponents()).containsExactly(factory); assertThat(factory.getComponent(Factory.class)).isEqualTo(factory); } @Test public void should_allow_to_close_with_factory_queried() throws Exception { // check that we don't get a stack overflow error due to box closing the factory Factory factory = Factory.builder().build(); assertThat(factory.queryByClass(Factory.class).findAsComponents()).containsExactly(factory); factory.close(); } @Test public void should_register_and_unregister() throws Exception { Factory factory = Factory.builder().build(); assertThat(Factory.getFactory(factory.getId())).isEqualTo(Optional.absent()); Factory.register(factory.getId(), factory); assertThat(Factory.getFactory(factory.getId())).isEqualTo(Optional.of(factory)); Factory.unregister(factory.getId(), factory); assertThat(Factory.getFactory(factory.getId())).isEqualTo(Optional.absent()); } @Test public void should_get_default_instance() throws Exception { Factory factory = Factory.getInstance(); assertThat(factory).isNotNull().isSameAs(Factory.getInstance()); } @Test public void should_use_local_machines() throws Exception { threadLocal().set("test", "myvalue"); Factory factory = Factory.newInstance(); assertThat(factory.getComponent(Name.of(String.class, "test"))).isEqualTo("myvalue"); threadLocal().clear(); factory = Factory.newInstance(); assertThat(factory.queryByName(Name.of(String.class, "test")).optional().findOne().isPresent()).isFalse(); } @Test public void should_deactivate_component() throws Exception { threadLocal().set("name1", new A("a1")); threadLocal().set("name2", new A("a2")); Factory factory = Factory.newInstance(); assertThat(factory.getComponents(A.class)).extracting("a").containsExactly("a1", "a2"); assertThat(factory.queryByName(Name.of(A.class, "name2")).findOne().isPresent()).isTrue(); threadLocal().set(Factory.activationKey(A.class, "name2"), "false"); factory = Factory.newInstance(); assertThat(factory.getComponents(A.class)).extracting("a").containsExactly("a1"); assertThat(factory.queryByName(Name.of(A.class, "name2")).findOne().isPresent()).isFalse(); } @Test public void should_deactivate_component2() throws Exception { threadLocal().set("name1", new A("a1")); threadLocal().set("name2", new A("a2")); Factory factory = Factory.newInstance(); assertThat(factory.queryByName(Name.of(Object.class, "name2")).findOne().isPresent()).isTrue(); threadLocal().set(Factory.activationKey(A.class, "name2"), "false"); factory = Factory.newInstance(); assertThat(factory.queryByName(Name.of(Object.class, "name2")).findOne().isPresent()).isFalse(); } @Test public void should_allow_to_deactivate_components_from_provided_warehouse() throws Exception { Factory factory = Factory.builder().addMachine( new SingletonFactoryMachine<>(0, NamedComponent.of(A.class, "a", new A("v1")))).build(); Set<A> components = factory.getComponents(A.class); assertThat(components).hasSize(1).extracting("a").containsExactly("v1"); Factory newFactory = Factory.builder().addWarehouseProvider(factory.getWarehouse()) .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(String.class, Factory.activationKey(A.class, "a"), "false"))) .addMachine(new SingletonFactoryMachine<>(0, NamedComponent.of(A.class, "b", new A("v2")))).build(); components = newFactory.getComponents(A.class); assertThat(components).hasSize(1).extracting("a").containsExactly("v2"); } @After public void teardown() { threadLocal().clear(); } private SingleNameFactoryMachine<String> testMachine() { return testMachine("test"); } private SingleNameFactoryMachine<String> testMachine(String name) { return new SingleNameFactoryMachine<>( 0, new NoDepsMachineEngine<String>(Name.of(String.class, name), BoundlessComponentBox.FACTORY) { @Override protected String doNewComponent(SatisfiedBOM satisfiedBOM) { return "value1"; } }); } private SingleNameFactoryMachine<String> machineWithMissingDependency() { return failingSingleDepMachine("test", "missing"); } private SingleNameFactoryMachine<String> failingSingleDepMachine(final String name, final String depName) { return new SingleNameFactoryMachine<>( 0, new StdMachineEngine<String>(Name.of(String.class, name), BoundlessComponentBox.FACTORY) { @Override public BillOfMaterials getBillOfMaterial() { return BillOfMaterials.of(Factory.Query.byName(Name.of(String.class, depName))); } @Override protected String doNewComponent(SatisfiedBOM satisfiedBOM) { throw new RuntimeException("shouldn't be called"); } }); } private SingleNameFactoryMachine<String> overridingMachine() { return new SingleNameFactoryMachine<>( -10, new NoDepsMachineEngine<String>(Name.of(String.class, "test"), BoundlessComponentBox.FACTORY) { @Override protected String doNewComponent(SatisfiedBOM satisfiedBOM) { return "value1"; } }); } private static class LifecycleComponent implements AutoStartable, AutoCloseable, AutoPreparable { private boolean closed; private boolean started; private boolean prepared; @Override public void close() throws Exception { closed = true; } @Override public void start() { started = true; } @Override public void prepare() { prepared = true; } } private static class A { String a; private A(String a) { this.a = a; } public String getA() { return a; } } }
9240986a313bdaadae17a8af04d8fa649e6b5f94
3,743
java
Java
src/main/java/com/redhat/demo/optaplanner/solver/domain/OptaMechanic.java
MusaTalluzi/2019-demo4-optaplanner
143d83901019e01543ff4effdabdcdddd60f30d6
[ "Apache-2.0" ]
11
2019-05-15T07:55:55.000Z
2021-12-04T19:10:23.000Z
src/main/java/com/redhat/demo/optaplanner/solver/domain/OptaMechanic.java
karstengresch/2019-demo4-optaplanner
45cb0ca2cf572ba52755a075729beb8fad715c97
[ "Apache-2.0" ]
1
2019-05-28T15:29:37.000Z
2019-05-28T15:29:37.000Z
src/main/java/com/redhat/demo/optaplanner/solver/domain/OptaMechanic.java
karstengresch/2019-demo4-optaplanner
45cb0ca2cf572ba52755a075729beb8fad715c97
[ "Apache-2.0" ]
8
2019-05-15T07:55:58.000Z
2021-08-10T01:28:07.000Z
31.720339
145
0.682073
1,001,589
/* * Copyright 2019 Red Hat, Inc. and/or 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.redhat.demo.optaplanner.solver.domain; import org.optaplanner.core.api.domain.lookup.PlanningId; public class OptaMechanic extends OptaVisitOrMechanic { @PlanningId private Integer mechanicIndex; private OptaConfiguration optaConfiguration; private boolean dummy; private double speed; private long fixDurationMillis; private long thumbUpDurationMillis; // The machine component that the mechanic is currently working on, on-route to or has just finished working on private OptaMachine focusMachine; // When the OptaMechanic will finish with working on focusMachine private Long focusDepartureTimeMillis; @SuppressWarnings("unused") private OptaMechanic() { } public static OptaMechanic createDummy(OptaConfiguration optaConfiguration) { OptaMechanic mechanic = new OptaMechanic(Integer.MIN_VALUE, optaConfiguration, Double.NaN, 0L, 0L, null, null); mechanic.dummy = true; return mechanic; } public OptaMechanic(int mechanicIndex, OptaConfiguration optaConfiguration, double speed, long fixDurationMillis, long thumbUpDurationMillis, OptaMachine focusMachine, Long focusDepartureTimeMillis) { this.mechanicIndex = mechanicIndex; this.optaConfiguration = optaConfiguration; dummy = false; this.speed = speed; this.fixDurationMillis = fixDurationMillis; this.thumbUpDurationMillis = thumbUpDurationMillis; this.focusMachine = focusMachine; this.focusDepartureTimeMillis = focusDepartureTimeMillis; } @Override public OptaMachine getMachine() { return focusMachine; } @Override public Long getFixOffsetMillis() { if (focusDepartureTimeMillis == null) { return null; } long focusDepartureOffsetMillis = focusDepartureTimeMillis - optaConfiguration.getLastDispatchOfAnyMechanicTimeMillis(); return focusDepartureOffsetMillis - thumbUpDurationMillis; } @Override public String toString() { return "OptaMechanic-" + mechanicIndex; } // ************************************************************************ // Getter and setters boilerplate // ************************************************************************ public Integer getMechanicIndex() { return mechanicIndex; } public boolean isDummy() { return dummy; } public double getSpeed() { return speed; } public long getFixDurationMillis() { return fixDurationMillis; } public long getThumbUpDurationMillis() { return thumbUpDurationMillis; } public OptaMachine getFocusMachine() { return focusMachine; } public void setFocusMachine(OptaMachine focusMachine) { this.focusMachine = focusMachine; } public long getFocusDepartureTimeMillis() { return focusDepartureTimeMillis; } public void setFocusDepartureTimeMillis(long focusDepartureTimeMillis) { this.focusDepartureTimeMillis = focusDepartureTimeMillis; } }
92409beb820176c0a17c3f96f2daa9390da5ab51
217
java
Java
src/TestURI.java
atulsm/Test_Projects
d6ad15e34011658a926a4613450f0f22e6f11b2a
[ "Apache-2.0" ]
1
2016-02-03T17:15:59.000Z
2016-02-03T17:15:59.000Z
src/TestURI.java
atulsm/Test_Projects
d6ad15e34011658a926a4613450f0f22e6f11b2a
[ "Apache-2.0" ]
null
null
null
src/TestURI.java
atulsm/Test_Projects
d6ad15e34011658a926a4613450f0f22e6f11b2a
[ "Apache-2.0" ]
1
2019-08-22T08:29:06.000Z
2019-08-22T08:29:06.000Z
24.111111
92
0.737327
1,001,590
import java.net.URI; public class TestURI { public static void main(String[] args) { URI resource = URI.create("/visual-analytics/proxy/kibana-int/dashboard/Alert Dashboard"); System.out.println(resource); } }
92409bfacba9ff53fcd2e3588eb0af8c79736798
2,015
java
Java
spring-cloud-azure-servicebus-topic-stream-binder/src/test/java/com/microsoft/azure/servicebus/stream/binder/ServiceBusTopicTestChannelProvisioner.java
lekkalraja/spring-cloud-azure
e95f5d090d51599b2f352906f0529890f6c7ba22
[ "MIT" ]
1
2021-06-13T03:30:25.000Z
2021-06-13T03:30:25.000Z
spring-cloud-azure-servicebus-topic-stream-binder/src/test/java/com/microsoft/azure/servicebus/stream/binder/ServiceBusTopicTestChannelProvisioner.java
lekkalraja/spring-cloud-azure
e95f5d090d51599b2f352906f0529890f6c7ba22
[ "MIT" ]
null
null
null
spring-cloud-azure-servicebus-topic-stream-binder/src/test/java/com/microsoft/azure/servicebus/stream/binder/ServiceBusTopicTestChannelProvisioner.java
lekkalraja/spring-cloud-azure
e95f5d090d51599b2f352906f0529890f6c7ba22
[ "MIT" ]
null
null
null
47.97619
117
0.834739
1,001,591
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for * license information. */ package com.microsoft.azure.servicebus.stream.binder; import com.microsoft.azure.servicebus.stream.binder.properties.ServiceBusConsumerProperties; import com.microsoft.azure.servicebus.stream.binder.properties.ServiceBusProducerProperties; import com.microsoft.azure.servicebus.stream.binder.provisioning.ServiceBusTopicChannelProvisioner; import com.microsoft.azure.servicebus.stream.binder.provisioning.ServiceBusTopicConsumerDestination; import com.microsoft.azure.servicebus.stream.binder.provisioning.ServiceBusTopicProducerDestination; import com.microsoft.azure.spring.cloud.context.core.api.ResourceManagerProvider; import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; import org.springframework.cloud.stream.binder.ExtendedProducerProperties; import org.springframework.cloud.stream.provisioning.ConsumerDestination; import org.springframework.cloud.stream.provisioning.ProducerDestination; import org.springframework.cloud.stream.provisioning.ProvisioningException; /** * @author Warren Zhu */ public class ServiceBusTopicTestChannelProvisioner extends ServiceBusTopicChannelProvisioner { public ServiceBusTopicTestChannelProvisioner(ResourceManagerProvider resourceManagerProvider, String namespace) { super(resourceManagerProvider, namespace); } @Override public ProducerDestination provisionProducerDestination(String name, ExtendedProducerProperties<ServiceBusProducerProperties> properties) throws ProvisioningException { return new ServiceBusTopicProducerDestination(name); } @Override public ConsumerDestination provisionConsumerDestination(String name, String group, ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) throws ProvisioningException { return new ServiceBusTopicConsumerDestination(name); } }
92409c36a99fd7f28cc0239ee76531db0e5093b5
1,098
java
Java
example/app/src/androidTest/java/com/stanfy/spoon/example/test/AnotherMainActivityTest.java
Igorshp/spoon-gradle-plugin
71b55cf2845ddca5a923f1e8deba0ac40ca30d62
[ "Apache-2.0" ]
321
2015-01-14T08:32:49.000Z
2021-06-21T15:26:33.000Z
example/app/src/androidTest/java/com/stanfy/spoon/example/test/AnotherMainActivityTest.java
Igorshp/spoon-gradle-plugin
71b55cf2845ddca5a923f1e8deba0ac40ca30d62
[ "Apache-2.0" ]
136
2015-01-06T09:27:28.000Z
2020-06-14T19:11:35.000Z
example/app/src/androidTest/java/com/stanfy/spoon/example/test/AnotherMainActivityTest.java
Igorshp/spoon-gradle-plugin
71b55cf2845ddca5a923f1e8deba0ac40ca30d62
[ "Apache-2.0" ]
96
2015-01-06T10:50:28.000Z
2020-08-25T08:35:09.000Z
28.153846
93
0.737705
1,001,592
package com.stanfy.spoon.example.test; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.SmallTest; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.LargeTest; import android.test.UiThreadTest; import android.widget.TextView; import com.squareup.spoon.Spoon; import com.stanfy.spoon.example.MainActivity; /** * Tests for MainActivity. */ public class AnotherMainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> { public AnotherMainActivityTest() { super(MainActivity.class); } @UiThreadTest public void testSetText() throws Throwable { final MainActivity act = getActivity(); final TextView text = (TextView) act.findViewById(android.R.id.text1); assertNotNull(text); Spoon.screenshot(act, "startup"); final int steps = 5; for (int i = 1; i <= steps; i++) { final String step = String.valueOf(i); act.setText(step); Spoon.screenshot(act, "step-" + i); assertEquals(text.getText().toString(), step); } } }
92409d16bac9bed3ead276fbf22af6c867240a24
73
java
Java
src/main/java/com/playmyskay/voxel/world/VoxelWorldFactory.java
playmyskay/playmyksay-libgdx-tools
b6dafff515f0e490c4e0c3a9b700d625a6c16b17
[ "Apache-2.0" ]
null
null
null
src/main/java/com/playmyskay/voxel/world/VoxelWorldFactory.java
playmyskay/playmyksay-libgdx-tools
b6dafff515f0e490c4e0c3a9b700d625a6c16b17
[ "Apache-2.0" ]
null
null
null
src/main/java/com/playmyskay/voxel/world/VoxelWorldFactory.java
playmyskay/playmyksay-libgdx-tools
b6dafff515f0e490c4e0c3a9b700d625a6c16b17
[ "Apache-2.0" ]
1
2021-05-12T13:21:30.000Z
2021-05-12T13:21:30.000Z
12.166667
35
0.794521
1,001,593
package com.playmyskay.voxel.world; public class VoxelWorldFactory { }
92409d535e6ff8bcc139ba5f1aab0db306574660
997
java
Java
src/test/java/org/ws/baidu/api/TestPlaceAPI.java
AlexandGao/WSHttpHelper
856934f1f503f819c0112a31f01cbf44a7a82a42
[ "Apache-2.0" ]
null
null
null
src/test/java/org/ws/baidu/api/TestPlaceAPI.java
AlexandGao/WSHttpHelper
856934f1f503f819c0112a31f01cbf44a7a82a42
[ "Apache-2.0" ]
null
null
null
src/test/java/org/ws/baidu/api/TestPlaceAPI.java
AlexandGao/WSHttpHelper
856934f1f503f819c0112a31f01cbf44a7a82a42
[ "Apache-2.0" ]
null
null
null
32.16129
94
0.63992
1,001,594
package org.ws.baidu.api; import junit.framework.TestCase; import org.ws.httphelper.WSHttpHelper; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 15-12-11. */ public class TestPlaceAPI extends TestCase { public void testRequest()throws Exception{ PlaceAPI api = new PlaceAPI(); api.addParameter("q","饭店"); api.addParameter("region","北京"); System.out.println(api.execute().getBody().toString()); System.out.println(api.getContext().getUrl()); } public void testDoGet()throws Exception{ Map<String,Object> param = new HashMap<String,Object>(); param.put("uid","5a8fb739999a70a54207c130"); param.put("ak","E4805d16520de693a3fe707cdc962045"); param.put("output","json"); param.put("scope","2"); Object obj=WSHttpHelper.doGetHtml("http://api.map.baidu.com/place/v2/detail", param); System.out.print(obj.toString()); } }
92409de943daf2af94856d64bebad944f05e280e
2,801
java
Java
app/models/entidades/Paciente.java
AlbertoTrindade/safe-prescription
47f29950d2d7c155c409c82fd43b80668fcbe159
[ "Apache-2.0" ]
null
null
null
app/models/entidades/Paciente.java
AlbertoTrindade/safe-prescription
47f29950d2d7c155c409c82fd43b80668fcbe159
[ "Apache-2.0" ]
null
null
null
app/models/entidades/Paciente.java
AlbertoTrindade/safe-prescription
47f29950d2d7c155c409c82fd43b80668fcbe159
[ "Apache-2.0" ]
null
null
null
20.595588
185
0.752231
1,001,595
package models.entidades; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import play.data.validation.Constraints.Required; import play.db.ebean.Model; @Entity public class Paciente extends Model{ @Id private long idPaciente; @Required private String nome; @OneToOne(cascade = CascadeType.ALL) private Endereco endereco; @Required private String cpf; @Required private String dataNasc; @Required private String telefoneFixo; @Required private String telefoneCelular; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "paciente_quadro_clinico") private List<QuadroClinico> quadrosClinicos; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "paciente_alergia") private List<Farmaco> alergias; public Paciente(String nome, Endereco endereco, String cpf, String dataNasc, String telefoneFixo, String telefoneCelular, List<QuadroClinico> quadrosClinicos, List<Farmaco> alergias) { this.nome = nome; this.endereco = endereco; this.cpf = cpf; this.dataNasc = dataNasc; this.telefoneFixo = telefoneFixo; this.telefoneCelular = telefoneCelular; this.quadrosClinicos = quadrosClinicos; this.alergias = alergias; } public static Model.Finder<Long, Paciente> find = new Finder<Long, Paciente>(Long.class, Paciente.class); public long getIdPaciente() { return idPaciente; } public void setIdPaciente(long idPaciente) { this.idPaciente = idPaciente; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Endereco getEndereco() { return endereco; } public void setEndereco(Endereco endereco) { this.endereco = endereco; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getDataNasc() { return dataNasc; } public void setDataNasc(String dataNasc) { this.dataNasc = dataNasc; } public String getTelefoneFixo() { return telefoneFixo; } public void setTelefoneFixo(String telefoneFixo) { this.telefoneFixo = telefoneFixo; } public String getTelefoneCelular() { return telefoneCelular; } public void setTelefoneCelular(String telefoneCelular) { this.telefoneCelular = telefoneCelular; } public List<QuadroClinico> getQuadrosClinicos() { return quadrosClinicos; } public void setQuadrosClinicos(List<QuadroClinico> quadrosClinicos) { this.quadrosClinicos = quadrosClinicos; } public List<Farmaco> getAlergias() { return alergias; } public void setAlergias(List<Farmaco> alergias) { this.alergias = alergias; } public String toString(){ return this.nome; } }
92409e4e7f7a8785d171f05002032ad06b90940e
4,949
java
Java
src/main/java/com/kleegroup/formation/boot/initializer/PersistenceManagerInitializer.java
KleeGroup/klee-formation
e216fa2c047f4dec94675afe39b1bde244b40c8d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/kleegroup/formation/boot/initializer/PersistenceManagerInitializer.java
KleeGroup/klee-formation
e216fa2c047f4dec94675afe39b1bde244b40c8d
[ "Apache-2.0" ]
9
2017-01-04T12:51:51.000Z
2017-03-17T10:37:53.000Z
src/main/java/com/kleegroup/formation/boot/initializer/PersistenceManagerInitializer.java
KleeGroup/klee-formation
e216fa2c047f4dec94675afe39b1bde244b40c8d
[ "Apache-2.0" ]
null
null
null
37.210526
174
0.769448
1,001,596
package com.kleegroup.formation.boot.initializer; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.inject.Inject; import com.kleegroup.formation.domain.administration.utilisateur.Utilisateur; import com.kleegroup.formation.domain.administration.utilisateur.Role; import com.kleegroup.formation.domain.formation.Niveau; import io.vertigo.app.Home; import io.vertigo.commons.cache.CacheManager; import io.vertigo.core.spaces.component.ComponentInitializer; import io.vertigo.dynamo.domain.metamodel.DataType; import io.vertigo.dynamo.domain.metamodel.DtDefinition; import io.vertigo.dynamo.domain.metamodel.DtField; import io.vertigo.dynamo.domain.model.DtListURIForMasterData; import io.vertigo.dynamo.domain.model.DtObject; import io.vertigo.dynamo.domain.util.DtObjectUtil; import io.vertigo.dynamo.store.StoreManager; /** * Initialisation du manager des masterdatas. * @author pchretien * @version $Id: PersistenceManagerInitializer.java,v 1.6 2014/08/04 16:57:50 npiedeloup Exp $ */ public final class PersistenceManagerInitializer implements ComponentInitializer { private static final int CACHE_DURATION_LONG = 3600; private static final int CACHE_DURATION_SHORT = 600; public static final String ALL_DATA_CODE = null; private static final String IS_ACTIVE = "IS_ACTIVE"; private static final String ACTIVE_DATA_CODE = "ACTIVE"; /** * Map static. */ private static final Map<Class<? extends DtObject>, Set<String>> MDL_MAP = new HashMap<>(); @Inject private StoreManager persistenceManager; /** {@inheritDoc} */ @Override public void init() { registerMasterData(persistenceManager, Niveau.class); registerMasterData(persistenceManager, Utilisateur.class); registerMasterData(persistenceManager, Role.class); //Liste de référence des communes-CP //registerMasterData(persistenceManager, Commune.class, CACHE_DURATION_LONG, true); // Enregistrement des listes de référence //registerMasterData(persistenceManager, TutoObjectType.class, CACHE_DURATION_LONG, false); //registerMasterData(persistenceManager, TutoObjectEtat.class, CACHE_DURATION_LONG, false); } private static <O extends DtObject> void registerMasterData(final StoreManager storeManager, final Class<O> dtObjectClass) { registerMasterData(storeManager, dtObjectClass, null, false); } private static <O extends DtObject> void registerMasterData(final StoreManager storeManager, final Class<O> dtObjectClass, final Integer duration, final boolean isBigList) { final DtDefinition dtDefinition = DtObjectUtil.findDtDefinition(dtObjectClass); memorizeMdl(dtObjectClass, dtDefinition.getName()); // Si la durée dans le cache n'est pas précisé, on se base sur le type de la clé primaire // pour déterminer la // durée final int cacheDuration; if (duration == null) { final DtField primaryKey = dtDefinition.getIdField().get(); if (primaryKey.getDomain().getDataType() == DataType.String) { cacheDuration = CACHE_DURATION_LONG; } else { cacheDuration = CACHE_DURATION_SHORT; } } else { cacheDuration = duration; } storeManager.getDataStoreConfig().registerCacheable(dtDefinition, cacheDuration, !isBigList, !isBigList); // on enregistre le filtre actif final DtListURIForMasterData uriActif = new DtListURIForMasterData(dtDefinition, ACTIVE_DATA_CODE); if (dtDefinition.contains(IS_ACTIVE)) { storeManager.getMasterDataConfig().register(uriActif, IS_ACTIVE, Boolean.TRUE); } else { storeManager.getMasterDataConfig().register(uriActif); } // On enregistre la liste globale final DtListURIForMasterData uri = new DtListURIForMasterData(dtDefinition, ALL_DATA_CODE); storeManager.getMasterDataConfig().register(uri); } private static void memorizeMdl(final Class<? extends DtObject> dtObjectClass, final String cacheName) { Set<String> set = MDL_MAP.get(dtObjectClass); if (set == null) { set = new HashSet<>(); MDL_MAP.put(dtObjectClass, set); } set.add(cacheName); } /** * Vide le cache sur les listes de références. */ public static void clearMdlCache() { final CacheManager manager = Home.getApp().getComponentSpace().resolve(CacheManager.class); for (final Set<String> set : MDL_MAP.values()) { clearDtoCache(manager, set); } } private static void clearDtoCache(final CacheManager manager, final Set<String> set) { if (set != null) { final String debutContext = "DataCache:"; for (final String mdl : set) { manager.clear(debutContext + mdl); } } } /** * Vide le cache de façon spécifique sur une liste de référence. * * @param dtObjectClass classe de lal iste de référence */ public static void clearMdlCache(final Class<? extends DtObject> dtObjectClass) { final CacheManager manager = Home.getApp().getComponentSpace().resolve(CacheManager.class); final Set<String> set = MDL_MAP.get(dtObjectClass); clearDtoCache(manager, set); } }
92409f5e2af633b4848221ef5efc19ed207a915b
4,591
java
Java
src/main/java/org/yx/conf/LocalhostUtil.java
wjiajun/sumk
60348542f298cb318e5c0508cc56e829c7eb3583
[ "Apache-2.0" ]
331
2016-09-12T01:29:20.000Z
2022-03-02T07:37:02.000Z
src/main/java/org/yx/conf/LocalhostUtil.java
wjiajun/sumk
60348542f298cb318e5c0508cc56e829c7eb3583
[ "Apache-2.0" ]
3
2018-12-03T15:15:22.000Z
2020-07-11T02:39:51.000Z
src/main/java/org/yx/conf/LocalhostUtil.java
wjiajun/sumk
60348542f298cb318e5c0508cc56e829c7eb3583
[ "Apache-2.0" ]
135
2016-09-12T06:22:26.000Z
2022-02-12T10:07:27.000Z
26.234286
91
0.671749
1,001,597
/** * Copyright (C) 2016 - 2030 youtongluan. * * 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.yx.conf; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.function.Predicate; import org.yx.common.matcher.BooleanMatcher; import org.yx.common.matcher.Matchers; import org.yx.log.RawLog; import org.yx.util.CollectionUtil; import org.yx.util.StringUtil; public final class LocalhostUtil { private static String localIp = null; private static String[] localIps = null; private static Predicate<String> matcher = defaultMatcher(); private static Predicate<String> defaultMatcher() { Predicate<String> m = Matchers.createWildcardMatcher("10.*,172.*,16.*,192.*,168.*", 1); Predicate<String> not1 = Matchers.createWildcardMatcher("*.1", 1).negate(); return m.and(not1); } private static boolean isValid(InetAddress ia) { if (ia instanceof Inet6Address && AppInfo.getBoolean("sumk.local.ipv6.disable", false)) { return false; } return !ia.isAnyLocalAddress() && !ia.isLoopbackAddress(); } private static String getHostAddress(InetAddress ia) { String address = ia.getHostAddress(); int index = address.indexOf('%'); if (index > 0 && AppInfo.getBoolean("sumk.ipv6.pure", true)) { address = address.substring(0, index); } return address; } public static synchronized boolean setLocalIp(String ip) { if (ip == null) { ip = ""; } try { ip = StringUtil.toLatin(ip).trim(); if (ip.contains(Matchers.WILDCARD) || ip.contains(",")) { matcher = Matchers.createWildcardMatcher(ip, 1); resetLocalIp(); return true; } matcher = defaultMatcher(); if (ip.length() > 0) { localIp = ip; } else { resetLocalIp(); } return true; } catch (Exception e) { RawLog.error("sumk.conf", e.getMessage(), e); return false; } } public static String getLocalIP() { if (localIp != null) {// localIp不会从非null变为null return localIp; } resetLocalIp(); return localIp; } private synchronized static void resetLocalIp() { try { String ip = getLocalIP0(); if (ip != null && ip.length() > 0) { localIp = ip; return; } } catch (Exception e) { RawLog.error("sumk.conf", e.getMessage(), e); } if (localIp == null) { localIp = "0.0.0.0"; } } private static String getLocalIP0() throws Exception { String[] ips = getLocalIps(); Predicate<String> matcher = LocalhostUtil.matcher; if (matcher == null) { matcher = BooleanMatcher.TRUE; } for (String ip : ips) { if (matcher.test(ip)) { return ip; } } if (ips.length > 0) { RawLog.warn("sumk.conf", "没有合适ip,使用第一个ip,列表为:" + Arrays.toString(ips)); return ips[0]; } RawLog.warn("sumk.conf", "找不到任何ip,使用0.0.0.0"); return "0.0.0.0"; } private static synchronized String[] getLocalIps() { if (localIps != null) { return localIps; } List<String> ipList = new ArrayList<String>(); try { Enumeration<?> e1 = (Enumeration<?>) NetworkInterface.getNetworkInterfaces(); while (e1.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) e1.nextElement(); if (!isUp(ni)) { continue; } Enumeration<?> e2 = ni.getInetAddresses(); while (e2.hasMoreElements()) { InetAddress ia = (InetAddress) e2.nextElement(); if (isValid(ia)) { ipList.add(getHostAddress(ia)); } } } } catch (SocketException e) { RawLog.error("sumk.conf", e.getMessage(), e); } if (ipList.isEmpty()) { return new String[0]; } localIps = ipList.toArray(new String[ipList.size()]); return localIps; } /** * 网卡是否有效 * * @param ni * @return * @throws SocketException */ private static boolean isUp(NetworkInterface ni) throws SocketException { return (!ni.isVirtual()) && ni.isUp() && (!ni.isLoopback()); } public static List<String> getLocalIPList() { return CollectionUtil.unmodifyList(getLocalIps()); } }
92409ffc11aad676d5d80bee59dffe53a10dce44
1,154
java
Java
src/test/java/com/ivalidate/model/CnpjValidateTest.java
jarnunes/IValidate
a55529eeb4621e3ad1100fcbecc101c8c969240e
[ "MIT" ]
1
2021-10-30T18:33:34.000Z
2021-10-30T18:33:34.000Z
src/test/java/com/ivalidate/model/CnpjValidateTest.java
jarnunes/IValidate
a55529eeb4621e3ad1100fcbecc101c8c969240e
[ "MIT" ]
null
null
null
src/test/java/com/ivalidate/model/CnpjValidateTest.java
jarnunes/IValidate
a55529eeb4621e3ad1100fcbecc101c8c969240e
[ "MIT" ]
null
null
null
20.607143
74
0.665511
1,001,598
package com.ivalidate.model; import com.ivalidate.model.cnpj.CnpjValidate; import org.junit.Test; import org.junit.Assert; public class CnpjValidateTest { @Test public void testCalcFirstDigit() { Assert.assertEquals(CnpjValidate.calcDigit(112223330001L, 1), 8); } @Test public void testCalcSecDigit() { Assert.assertEquals(CnpjValidate.calcDigit(1122233300018L, 2), 1); } @Test public void testValidateCnpj() { Assert.assertTrue(CnpjValidate.validate("11.222.333/0001-81")); } @Test public void testCleanvalidCnpj() { Assert.assertTrue(CnpjValidate.validate("11222333000181")); } @Test public void testInvalidCnpj() { Assert.assertFalse(CnpjValidate.validate("11.222.333/0001-88")); } @Test public void testIsSequence() { Assert.assertFalse(CnpjValidate.validate("11111111111111")); } @Test public void testCleanInvalidCnpj() { Assert.assertFalse(CnpjValidate.validate("11222333000188")); } @Test public void testNoneCnpj() { Assert.assertFalse(CnpjValidate.validate("")); } }
9240a030fd8d12db6815777e9b6366caeeb3a179
2,613
java
Java
ide/refactoring.api/src/org/netbeans/modules/refactoring/api/impl/SPIAccessor.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,056
2019-04-25T20:00:35.000Z
2022-03-30T04:46:14.000Z
ide/refactoring.api/src/org/netbeans/modules/refactoring/api/impl/SPIAccessor.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,846
2019-04-25T20:50:05.000Z
2022-03-31T23:40:41.000Z
ide/refactoring.api/src/org/netbeans/modules/refactoring/api/impl/SPIAccessor.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
550
2019-04-25T20:04:33.000Z
2022-03-25T17:43:01.000Z
43.55
107
0.781095
1,001,599
/* * 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.netbeans.modules.refactoring.api.impl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.netbeans.modules.refactoring.api.RefactoringSession; import org.netbeans.modules.refactoring.spi.ModificationResult; import org.netbeans.modules.refactoring.spi.RefactoringCommit; import org.netbeans.modules.refactoring.spi.RefactoringElementImplementation; import org.netbeans.modules.refactoring.spi.RefactoringElementsBag; import org.netbeans.modules.refactoring.spi.SimpleRefactoringElementImplementation; import org.netbeans.modules.refactoring.spi.Transaction; /** * * @author Martin Matula, Jan Becicka */ public abstract class SPIAccessor { public static SPIAccessor DEFAULT; static { Class c = RefactoringElementsBag.class; try { Class.forName(c.getName(), true, c.getClassLoader()); } catch (Exception ex) { ex.printStackTrace(); } } public abstract RefactoringElementsBag createBag(RefactoringSession session, List delegate); public abstract Collection getReadOnlyFiles(RefactoringElementsBag bag); public abstract ArrayList<Transaction> getCommits(RefactoringElementsBag bag); public abstract ArrayList<RefactoringElementImplementation> getFileChanges(RefactoringElementsBag bag); public abstract String getNewFileContent(SimpleRefactoringElementImplementation impl); public abstract boolean hasChangesInGuardedBlocks(RefactoringElementsBag bag); public abstract boolean hasChangesInReadOnlyFiles(RefactoringElementsBag bag); public abstract void check(Transaction commit, boolean undo); public abstract void sum(Transaction commit); public abstract Collection<? extends ModificationResult> getTransactions(RefactoringCommit c); }
9240a06fe098ffa8c78e8d53073b3a6b0c6dc5fe
15,630
java
Java
app/src/main/java/org/frc836/yearly/MatchActivity.java
username115/FRCScouting
77e197b3e0380d558b1a82b20ed360035451295d
[ "Apache-2.0" ]
7
2015-01-13T00:29:32.000Z
2018-03-25T08:11:38.000Z
app/src/main/java/org/frc836/yearly/MatchActivity.java
username115/FRCScouting
77e197b3e0380d558b1a82b20ed360035451295d
[ "Apache-2.0" ]
187
2015-01-03T15:39:10.000Z
2022-03-26T15:16:02.000Z
app/src/main/java/org/frc836/yearly/MatchActivity.java
username115/FRCScouting
77e197b3e0380d558b1a82b20ed360035451295d
[ "Apache-2.0" ]
11
2015-03-06T05:52:27.000Z
2019-04-17T21:27:27.000Z
32.094456
157
0.622137
1,001,600
/* * Copyright 2015 Daniel Logan * * 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.frc836.yearly; import android.app.AlertDialog; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.util.SparseArray; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContract; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityOptionsCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import androidx.viewpager.widget.ViewPager; import org.frc836.database.DBActivity; import org.frc836.database.MatchStatsStruct; import org.growingstems.scouting.MainMenuSelection; import org.growingstems.scouting.MatchFragment; import org.growingstems.scouting.Prefs; import org.growingstems.scouting.R; import java.util.List; public class MatchActivity extends DBActivity { public static final int NUM_SCREENS = 4; public static final int AUTO_SCREEN = 0; public static final int TELE_SCREEN = 1; public static final int CLIMB_SCREEN = 2; public static final int END_SCREEN = 3; private MatchViewAdapter mMatchViewAdapter; private ViewPager mViewPager; private String HELPMESSAGE; private MatchStatsStruct teamData; private EditText teamText; private EditText matchT; private TextView posT; private Button lastB; private Button nextB; private int mCurrentPage; private boolean readOnly = false; private String event = null; private boolean prac = false; private String position = null; private final Handler timer = new Handler(); private static final int DELAY = 16000; private final ActivityResultLauncher<Intent> resultForPrefs = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {}); private final Runnable mUpdateTimeTask = new Runnable() { public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(MatchActivity.this); builder.setMessage("Continue to Tele-Op?") .setCancelable(true) .setPositiveButton("Yes", (dialog, id) -> { if (mCurrentPage == AUTO_SCREEN) onNext(nextB); }) .setNegativeButton("No", (dialog, id) -> { timer.removeCallbacks(mUpdateTimeTask); if (!readOnly && mCurrentPage == AUTO_SCREEN) timer.postDelayed(mUpdateTimeTask, DELAY); dialog.cancel(); }); builder.show(); } }; private static final String defaultEvent = "CHS District Oxon Hill MD Event"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.match); HELPMESSAGE = "Record Match Data here.\n" + "Input number of cargo scored in both Autonomous and Tele-op periods.\n" + "Input hang location, and how long it took to reach final hang position.\n" + "A timer has been provided to assist with this.\n" + "During the match, observe where cargo was scored from, and mark the locations the robot tended to use."; getGUIRefs(); Intent intent = getIntent(); teamText.setText(intent.getStringExtra("team")); matchT.setText(intent.getStringExtra("match")); readOnly = intent.getBooleanExtra("readOnly", false); event = intent.getStringExtra("event"); prac = intent.getBooleanExtra("practice", false); position = intent.getStringExtra("position"); mMatchViewAdapter = new MatchViewAdapter(getSupportFragmentManager()); mCurrentPage = AUTO_SCREEN; mViewPager = findViewById(R.id.matchPager); mViewPager.setAdapter(mMatchViewAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { pageSelected(position); } }); if (!readOnly) posT.setOnClickListener(new positionClickListener()); loadData(); loadAuto(); } protected void onResume() { super.onResume(); teamData.event_id = event == null ? Prefs.getEvent(getApplicationContext(), defaultEvent) : event; teamData.practice_match = readOnly ? prac : Prefs.getPracticeMatch(getApplicationContext(), false); updatePosition(); if (mCurrentPage == AUTO_SCREEN && !readOnly) { timer.postDelayed(mUpdateTimeTask, DELAY); } } protected void onPause() { super.onPause(); timer.removeCallbacks(mUpdateTimeTask); } public List<String> getNotesOptions() { return db.getNotesOptions(); } public List<String> getTeamNotes() { return db.getNotesForTeam(teamData.team_id); } private void updatePosition() { String pos = position == null ? Prefs.getPosition(getApplicationContext(), "Red 1") : position; posT.setText(pos); if (pos.contains("Blue")) { posT.setTextColor(Color.BLUE); } else { posT.setTextColor(Color.RED); } } @Override public String getHelpMessage() { return HELPMESSAGE; } @NonNull @Override public ActivityResultLauncher<Intent> getResultForPrefs() { return resultForPrefs; } private class positionClickListener implements View.OnClickListener { public void onClick(View v) { MainMenuSelection.openSettings(MatchActivity.this); } } private void loadData() { Editable teamE = teamText.getText(); Editable matchE = matchT.getText(); boolean loadData = false; if (teamE != null && teamE.length() > 0 && matchE != null && matchE.length() > 0) { String team = teamE.toString(); String match = matchE.toString(); teamData = db.getMatchStats(event == null ? Prefs.getEvent(getApplicationContext(), defaultEvent) : event, Integer .parseInt(match), Integer.parseInt(team), readOnly ? prac : Prefs.getPracticeMatch(getApplicationContext(), false)); if (teamData == null) teamData = new MatchStatsStruct(Integer.parseInt(team), event == null ? Prefs.getEvent(getApplicationContext(), defaultEvent) : event, Integer.parseInt(match), readOnly ? prac : Prefs.getPracticeMatch(getApplicationContext(), false)); else loadData = true; } else teamData = new MatchStatsStruct(); if (loadData && !readOnly) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Data for this match exists.\nLoad old match?") .setCancelable(false) .setPositiveButton("Yes", (dialog, id) -> dialog.cancel()) .setNegativeButton("No", (dialog, id) -> { if (teamText.getText().toString().length() > 0 && matchT.getText().toString() .length() > 0) { teamData = new MatchStatsStruct( Integer.parseInt(teamText .getText().toString()), event == null ? Prefs.getEvent(getApplicationContext(), defaultEvent) : event, Integer.parseInt(matchT .getText().toString())); } else teamData = new MatchStatsStruct(); loadAuto(); loadTele(); loadEnd(); }); builder.show(); } mViewPager.setCurrentItem(0, true); loadAll(); lastB.setText(getString(R.string.match_change_button_cancel)); nextB.setText(getString(R.string.match_change_button_tele)); } public void pageSelected(int page) { switch (mCurrentPage) { case AUTO_SCREEN: saveAuto(); break; case TELE_SCREEN: saveTele(); break; case CLIMB_SCREEN: saveClimb(); break; case END_SCREEN: saveEnd(); break; } mCurrentPage = page; switch (page) { case AUTO_SCREEN: loadAuto(); lastB.setText(getString(R.string.match_change_button_cancel)); nextB.setText(getString(R.string.match_change_button_tele)); if (!readOnly) timer.postDelayed(mUpdateTimeTask, DELAY); break; case TELE_SCREEN: loadTele(); lastB.setText(getString(R.string.match_change_button_auto)); nextB.setText(getString(R.string.match_change_button_climb)); timer.removeCallbacks(mUpdateTimeTask); break; case CLIMB_SCREEN: loadClimb(); lastB.setText(getString(R.string.match_change_button_tele)); nextB.setText(getString(R.string.match_change_button_end)); timer.removeCallbacks(mUpdateTimeTask); break; case END_SCREEN: loadEnd(); lastB.setText(getString(R.string.match_change_button_climb)); nextB.setText(readOnly ? getString(R.string.match_change_button_cancel) : getString(R.string.match_change_button_submit)); timer.removeCallbacks(mUpdateTimeTask); break; default: loadAll(); lastB.setText(getString(R.string.match_change_button_cancel)); nextB.setText(getString(R.string.match_change_button_tele)); timer.removeCallbacks(mUpdateTimeTask); } } @Override public void onBackPressed() { onBack(null); } public void onBack(View v) { if (mCurrentPage == 0 || mCurrentPage >= NUM_SCREENS) { if (!readOnly) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage( "Cancel Match Entry?\nChanges will not be saved.") .setCancelable(false) .setPositiveButton("Yes", (dialog, id) -> MatchActivity.this.finish()) .setNegativeButton("No", (dialog, id) -> dialog.cancel()); builder.show(); } else finish(); } mViewPager.setCurrentItem(mCurrentPage - 1, true); } public void onNext(View v) { if (mCurrentPage < 0 || mCurrentPage >= (NUM_SCREENS - 1)) { saveAll(); submit(); } mViewPager.setCurrentItem(mCurrentPage + 1, true); } private static class MatchViewAdapter extends FragmentPagerAdapter { SparseArray<MatchFragment> fragments; MatchViewAdapter(FragmentManager fm) { super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); fragments = new SparseArray<>(NUM_SCREENS); } @NonNull @Override public Fragment getItem(int i) { return getMatchFragment(i); } MatchFragment getMatchFragment(int i) { MatchFragment fragment; if (fragments.get(i) != null) { return fragments.get(i); } switch (i) { case AUTO_SCREEN: fragment = AutoMatchFragment.newInstance(); fragments.put(i, fragment); return fragment; case TELE_SCREEN: fragment = TeleMatchFragment.newInstance(); fragments.put(i, fragment); return fragment; case CLIMB_SCREEN: fragment = ClimbFragment.newInstance(); fragments.put(i, fragment); return fragment; case END_SCREEN: default: fragment = EndMatchFragment.newInstance(); fragments.put(i, fragment); return fragment; } } @Override public int getCount() { return NUM_SCREENS; } } private void getGUIRefs() { teamText = findViewById(R.id.teamNum); matchT = findViewById(R.id.matchNum); posT = findViewById(R.id.pos); lastB = findViewById(R.id.backB); nextB = findViewById(R.id.nextB); } private void loadClimb() { mMatchViewAdapter.getMatchFragment(CLIMB_SCREEN).loadData(teamData); } private void saveClimb() { saveTeamInfo(); mMatchViewAdapter.getMatchFragment(CLIMB_SCREEN).saveData(teamData); } private void loadAuto() { mMatchViewAdapter.getMatchFragment(AUTO_SCREEN).loadData(teamData); } private void saveAuto() { saveTeamInfo(); mMatchViewAdapter.getMatchFragment(AUTO_SCREEN).saveData(teamData); } private void loadTele() { mMatchViewAdapter.getMatchFragment(TELE_SCREEN).loadData(teamData); } private void saveTele() { saveTeamInfo(); mMatchViewAdapter.getMatchFragment(TELE_SCREEN).saveData(teamData); } private void loadEnd() { mMatchViewAdapter.getMatchFragment(END_SCREEN).loadData(teamData); } private void saveEnd() { saveTeamInfo(); mMatchViewAdapter.getMatchFragment(END_SCREEN).saveData(teamData); } private void loadAll() { loadTele(); loadAuto(); loadTele(); loadEnd(); } private void saveAll() { saveTele(); saveAuto(); saveTele(); saveEnd(); } private void saveTeamInfo() { Editable team = teamText.getText(); if (team != null && team.length() > 0) teamData.team_id = Integer.parseInt(team.toString()); Editable match = matchT.getText(); if (match != null && match.length() > 0) { teamData.match_id = Integer.parseInt(match.toString()); } teamData.position_id = posT.getText().toString(); } private void submit() { if (!readOnly) { saveEnd(); if (teamData.match_id > 0 && teamData.team_id > 0) { db.submitMatch(teamData); nextB.setEnabled(false); if (matchT.getText().length() > 0) setResult(Integer.parseInt(matchT.getText().toString()) + 1); } else if (teamData.match_id <= 0) { Toast.makeText(this, "Please enter a match number", Toast.LENGTH_SHORT).show(); return; } else { Toast.makeText(this, "Please enter a team number", Toast.LENGTH_SHORT).show(); return; } } finish(); } public String getPosition() { return position == null ? Prefs.getPosition(getApplicationContext(), "Red 1") : position; } }
9240a0bd98f233f6358b906005627ec4cf82e1a0
4,034
java
Java
jadx-core/src/main/java/jadx/core/dex/visitors/AttachCommentsVisitor.java
warifp/jadx
63f7ce20a412bac4abb665207ec1682761186f74
[ "Apache-2.0" ]
3
2021-05-17T00:48:15.000Z
2021-11-29T00:07:03.000Z
jadx-core/src/main/java/jadx/core/dex/visitors/AttachCommentsVisitor.java
warifp/jadx
63f7ce20a412bac4abb665207ec1682761186f74
[ "Apache-2.0" ]
2
2021-09-29T22:38:05.000Z
2021-11-23T23:23:04.000Z
jadx-core/src/main/java/jadx/core/dex/visitors/AttachCommentsVisitor.java
warifp/jadx
63f7ce20a412bac4abb665207ec1682761186f74
[ "Apache-2.0" ]
1
2021-08-04T09:10:30.000Z
2021-08-04T09:10:30.000Z
28.814286
102
0.72236
1,001,601
package jadx.core.dex.visitors; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.data.CodeRefType; import jadx.api.data.ICodeComment; import jadx.api.data.ICodeData; import jadx.api.data.IJavaCodeRef; import jadx.api.data.IJavaNodeRef; import jadx.core.dex.attributes.AType; import jadx.core.dex.attributes.IAttributeNode; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.exceptions.JadxException; import jadx.core.utils.exceptions.JadxRuntimeException; @JadxVisitor( name = "AttachComments", desc = "Attach user code comments", runBefore = { ProcessInstructionsVisitor.class } ) public class AttachCommentsVisitor extends AbstractVisitor { private static final Logger LOG = LoggerFactory.getLogger(AttachCommentsVisitor.class); private Map<String, List<ICodeComment>> clsCommentsMap; @Override public void init(RootNode root) throws JadxException { updateCommentsData(root.getArgs().getCodeData()); root.registerCodeDataUpdateListener(this::updateCommentsData); } @Override public boolean visit(ClassNode cls) { List<ICodeComment> clsComments = getCommentsData(cls); if (!clsComments.isEmpty()) { applyComments(cls, clsComments); } cls.getInnerClasses().forEach(this::visit); return false; } private static void applyComments(ClassNode cls, List<ICodeComment> clsComments) { for (ICodeComment comment : clsComments) { IJavaNodeRef nodeRef = comment.getNodeRef(); switch (nodeRef.getType()) { case CLASS: addComment(cls, comment.getComment()); break; case FIELD: FieldNode fieldNode = cls.searchFieldByShortId(nodeRef.getShortId()); if (fieldNode == null) { LOG.warn("Field reference not found: {}", nodeRef); } else { addComment(fieldNode, comment.getComment()); } break; case METHOD: MethodNode methodNode = cls.searchMethodByShortId(nodeRef.getShortId()); if (methodNode == null) { LOG.warn("Method reference not found: {}", nodeRef); } else { IJavaCodeRef codeRef = comment.getCodeRef(); if (codeRef == null) { addComment(methodNode, comment.getComment()); } else { processCustomAttach(methodNode, codeRef, comment); } } break; } } } private static InsnNode getInsnByOffset(MethodNode mth, int offset) { try { return mth.getInstructions()[offset]; } catch (Exception e) { LOG.warn("Insn reference not found in: {} with offset: {}", mth, offset); return null; } } private static void processCustomAttach(MethodNode mth, IJavaCodeRef codeRef, ICodeComment comment) { CodeRefType attachType = codeRef.getAttachType(); switch (attachType) { case INSN: { InsnNode insn = getInsnByOffset(mth, codeRef.getIndex()); addComment(insn, comment.getComment()); break; } default: throw new JadxRuntimeException("Unexpected attach type: " + attachType); } } private static void addComment(@Nullable IAttributeNode node, String comment) { if (node == null) { return; } node.remove(AType.CODE_COMMENTS); node.addAttr(AType.CODE_COMMENTS, comment); } private List<ICodeComment> getCommentsData(ClassNode cls) { if (clsCommentsMap == null) { return Collections.emptyList(); } List<ICodeComment> clsComments = clsCommentsMap.get(cls.getClassInfo().getRawName()); if (clsComments == null) { return Collections.emptyList(); } return clsComments; } private void updateCommentsData(@Nullable ICodeData data) { if (data == null) { this.clsCommentsMap = Collections.emptyMap(); } else { this.clsCommentsMap = data.getComments().stream() .collect(Collectors.groupingBy(c -> c.getNodeRef().getDeclaringClass())); } } }
9240a105e8e2e2a12a82f5362d173180cdb308ec
1,971
java
Java
src/main/java/com/jianma/yxyp/util/PasswordHelper.java
jianmakeji/yxyp
3d56d787ffe9926f83832954f5e718e640f59341
[ "MIT" ]
1
2019-02-14T01:18:57.000Z
2019-02-14T01:18:57.000Z
src/main/java/com/jianma/yxyp/util/PasswordHelper.java
jianmakeji/yxyp
3d56d787ffe9926f83832954f5e718e640f59341
[ "MIT" ]
5
2020-05-15T21:06:24.000Z
2021-12-09T20:40:01.000Z
src/main/java/com/jianma/yxyp/util/PasswordHelper.java
jianmakeji/yxyp
3d56d787ffe9926f83832954f5e718e640f59341
[ "MIT" ]
null
null
null
28.985294
96
0.644343
1,001,602
package com.jianma.yxyp.util; import java.math.BigInteger; import java.security.MessageDigest; import java.util.UUID; import org.apache.shiro.crypto.RandomNumberGenerator; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.util.ByteSource; import com.jianma.yxyp.model.User; public class PasswordHelper { private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator(); private static String algorithmName = "md5"; private static final int hashIterations = 2; public static void encryptPassword(User user) { user.setSlot(randomNumberGenerator.nextBytes().toHex()); String newPassword = new SimpleHash( algorithmName, user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex(); user.setPassword(newPassword); } public static void encryptAppPassword(User user) { user.setSlot(randomNumberGenerator.nextBytes().toHex()); String newPassword = new SimpleHash( algorithmName, user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex(); user.setPassword(newPassword); } /** * 对字符串md5加密 * * @param str * @return */ public static String getMD5(String str) { try { // 生成一个MD5加密计算摘要 MessageDigest md = MessageDigest.getInstance("MD5"); // 计算md5函数 md.update(str.getBytes()); // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符 // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值 return new BigInteger(1, md.digest()).toString(16); } catch (Exception e) { return UUID.randomUUID().toString(); } } }
9240a11d20bbcda3cadb8759ee5c79e99aff24d2
289
java
Java
src/main/java/com/scheduler/aspects/TrackTime.java
MykhailoRomanenko/SpringBootScheduler
ce2b6f588934b38740c1ab0cd59d0ca2ac666b3d
[ "MIT" ]
null
null
null
src/main/java/com/scheduler/aspects/TrackTime.java
MykhailoRomanenko/SpringBootScheduler
ce2b6f588934b38740c1ab0cd59d0ca2ac666b3d
[ "MIT" ]
1
2021-11-10T19:04:11.000Z
2021-11-10T19:04:11.000Z
src/main/java/com/scheduler/aspects/TrackTime.java
MykhailoRomanenko/SpringBootScheduler
ce2b6f588934b38740c1ab0cd59d0ca2ac666b3d
[ "MIT" ]
3
2021-09-17T18:56:37.000Z
2021-11-08T20:31:14.000Z
26.272727
44
0.83391
1,001,603
package com.scheduler.aspects; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TrackTime { }
9240a164c8112e934d18a69e8ae7fc074c645878
987
java
Java
src/lanqiao/final2020/F.java
kid1999/Algorithmic-training
7bb246ecfa6907c7f4b9a1fb2774ad75ce110673
[ "MIT" ]
2
2019-09-16T03:56:16.000Z
2019-10-12T03:30:37.000Z
src/lanqiao/final2020/F.java
kid1999/Algorithmic-training
7bb246ecfa6907c7f4b9a1fb2774ad75ce110673
[ "MIT" ]
null
null
null
src/lanqiao/final2020/F.java
kid1999/Algorithmic-training
7bb246ecfa6907c7f4b9a1fb2774ad75ce110673
[ "MIT" ]
null
null
null
23.5
48
0.431611
1,001,604
package lanqiao.final2020; import java.util.Scanner; /** * @author kid1999 * @create 2020-11-14 19:56 * @description TODO **/ public class F { static class node{ int head; int sum; public node(int head, int sum) { this.head = head; this.sum = sum; } public node() { } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); node[] nodes = new node[n+1]; for (int i = 0; i < n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); nodes[i] = new node(a+b,a+b+c); } int[] dp1 = new int[n+1]; int[] dp2 = new int[n+1]; for (int i = 1; i <=n ; i++) { for (int j = 1; j <i ; j++) { dp1[j] = dp2[j] + nodes[j].head; dp2[j] = dp2[j] + nodes[j].sum; } } } }
9240a2250e7f3c066d8aa1137a7101f6b66c278e
3,084
java
Java
modules/core/src/main/java/org/apache/ignite/internal/visor/encryption/VisorChangeMasterKeyTask.java
tsdb-io/gridgain
6726ed9cc34a7d2671a3625600c375939d40bc35
[ "CC0-1.0" ]
218
2015-01-04T13:20:55.000Z
2022-03-28T05:28:55.000Z
modules/core/src/main/java/org/apache/ignite/internal/visor/encryption/VisorChangeMasterKeyTask.java
tsdb-io/gridgain
6726ed9cc34a7d2671a3625600c375939d40bc35
[ "CC0-1.0" ]
175
2015-02-04T23:16:56.000Z
2022-03-28T18:34:24.000Z
modules/core/src/main/java/org/apache/ignite/internal/visor/encryption/VisorChangeMasterKeyTask.java
tsdb-io/gridgain
6726ed9cc34a7d2671a3625600c375939d40bc35
[ "CC0-1.0" ]
93
2015-01-06T20:54:23.000Z
2022-03-31T08:09:00.000Z
34.266667
102
0.652399
1,001,605
/* * Copyright 2020 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.visor.encryption; import org.apache.ignite.IgniteEncryption; import org.apache.ignite.IgniteException; import org.apache.ignite.compute.ComputeJobContext; import org.apache.ignite.internal.processors.task.GridInternal; import org.apache.ignite.internal.visor.VisorJob; import org.apache.ignite.internal.visor.VisorOneNodeTask; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgniteInClosure; import org.apache.ignite.resources.JobContextResource; /** * The task for changing the master key. * * @see IgniteEncryption#changeMasterKey(String) */ @GridInternal public class VisorChangeMasterKeyTask extends VisorOneNodeTask<String, String> { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** {@inheritDoc} */ @Override protected VisorJob<String, String> job(String arg) { return new VisorChangeMasterKeyJob(arg, debug); } /** The job for changing the master key. */ private static class VisorChangeMasterKeyJob extends VisorJob<String, String> { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** */ private IgniteFuture opFut; /** Job context. */ @JobContextResource private ComputeJobContext jobCtx; /** * Create job with specified argument. * * @param masterKeyName Master key name. * @param debug Flag indicating whether debug information should be printed into node log. */ protected VisorChangeMasterKeyJob(String masterKeyName, boolean debug) { super(masterKeyName, debug); } /** {@inheritDoc} */ @Override protected String run(String masterKeyName) throws IgniteException { if (opFut == null) { opFut = ignite.encryption().changeMasterKey(masterKeyName); if (opFut.isDone()) opFut.get(); else { jobCtx.holdcc(); opFut.listen(new IgniteInClosure<IgniteFuture>() { @Override public void apply(IgniteFuture f) { jobCtx.callcc(); } }); } } opFut.get(); return "The master key changed."; } } }
9240a245375060a486ec790ce07ca683f745fee4
4,593
java
Java
symphony-client/src/main/java/com/symphony/api/clients/AuthorizationClient.java
mcleo-d/symphony-admin-bot
5412f8b189de6fb43aab9de0156e3a64a481e0ff
[ "Apache-2.0" ]
null
null
null
symphony-client/src/main/java/com/symphony/api/clients/AuthorizationClient.java
mcleo-d/symphony-admin-bot
5412f8b189de6fb43aab9de0156e3a64a481e0ff
[ "Apache-2.0" ]
1
2019-11-13T01:27:13.000Z
2019-11-13T01:27:13.000Z
symphony-client/src/main/java/com/symphony/api/clients/AuthorizationClient.java
mcleo-d/symphony-admin-bot
5412f8b189de6fb43aab9de0156e3a64a481e0ff
[ "Apache-2.0" ]
3
2018-11-30T00:52:09.000Z
2019-12-18T13:31:27.000Z
34.795455
116
0.731983
1,001,606
/* * Copyright 2017 The Symphony Software Foundation * * Licensed to The Symphony Software Foundation (SSF) 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 com.symphony.api.clients; import com.symphony.api.auth.api.AuthenticationApi; import com.symphony.api.auth.client.ApiClient; import com.symphony.api.auth.client.ApiException; import com.symphony.api.auth.client.Configuration; import com.symphony.api.clients.model.SymphonyAuth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.security.KeyStore; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; /** * Created by nick.tarsillo on 7/1/17. */ public class AuthorizationClient { private final Logger LOG = LoggerFactory.getLogger(AuthorizationClient.class); private final String sessionAuthUrl; private final String keyAuthUrl; private Client httpClient; public AuthorizationClient(String sessionAuthUrl, String keyAuthUrl){ this.sessionAuthUrl = sessionAuthUrl; this.keyAuthUrl = keyAuthUrl; } public AuthorizationClient(SymphonyAuth symAuth) { this.sessionAuthUrl = symAuth.getSessionUrl(); this.keyAuthUrl = symAuth.getKeyUrl(); this.httpClient = symAuth.getClient(); } public SymphonyAuth authenticate() throws ApiException { if(sessionAuthUrl == null || keyAuthUrl == null) throw new NullPointerException("Session URL or Keystore URL is null."); SymphonyAuth symAuth = new SymphonyAuth(); symAuth.setKeyUrl(keyAuthUrl); symAuth.setSessionUrl(sessionAuthUrl); symAuth.setClient(httpClient); ApiClient authenticatorClient = Configuration.getDefaultApiClient(); authenticatorClient.setHttpClient(httpClient); AuthenticationApi authenticationApi = new AuthenticationApi(authenticatorClient); authenticatorClient.setBasePath(sessionAuthUrl); symAuth.setSessionToken(authenticationApi.v1AuthenticatePost()); LOG.debug("SessionToken: {} : {}", symAuth.getSessionToken().getName(), symAuth.getSessionToken().getToken()); authenticatorClient.setBasePath(keyAuthUrl); symAuth.setKeyToken(authenticationApi.v1AuthenticatePost()); LOG.debug("KeyToken: {} : {}", symAuth.getKeyToken().getName(), symAuth.getKeyToken().getToken()); return symAuth; } /** * Create custom client with specific keystores. * * @param clientKeyStore Client (BOT) keystore file * @param clientKeyStorePass Client (BOT) keystore password * @param trustStore Truststore file * @param trustStorePass Truststore password * @return Custom HttpClient * @throws Exception Generally IOExceptions thrown from instantiation. */ public void setKeystores(String trustStore, String trustStorePass, String clientKeyStore, String clientKeyStorePass) throws Exception { KeyStore cks = KeyStore.getInstance("PKCS12"); KeyStore tks = KeyStore.getInstance("JKS"); loadKeyStore(cks, clientKeyStore, clientKeyStorePass); loadKeyStore(tks, trustStore, trustStorePass); httpClient = ClientBuilder.newBuilder() .keyStore(cks, clientKeyStorePass.toCharArray()) .trustStore(tks) .hostnameVerifier((string, sll) -> true) .build(); } /** * Internal keystore loader * * @param ks Keystore object which defines the expected type (PKCS12, JKS) * @param ksFile Keystore file to process * @param ksPass Keystore password for file to process * @throws Exception Generally IOExceptions generated from file read */ private static void loadKeyStore(KeyStore ks, String ksFile, String ksPass) throws Exception { FileInputStream fis = null; try { fis = new FileInputStream(ksFile); ks.load(fis, ksPass.toCharArray()); } finally { if (fis != null) { fis.close(); } } } }
9240a4bdfc40ee01ad34248abbab674844b3f6bf
1,480
java
Java
redisson-tomcat/redisson-tomcat-9/src/main/java/org/redisson/tomcat/AttributeUpdateMessage.java
xuziming/myredisson
420e221c5f9986e8ac54b310f251679bfc48ee70
[ "Apache-2.0" ]
null
null
null
redisson-tomcat/redisson-tomcat-9/src/main/java/org/redisson/tomcat/AttributeUpdateMessage.java
xuziming/myredisson
420e221c5f9986e8ac54b310f251679bfc48ee70
[ "Apache-2.0" ]
3
2020-02-28T01:27:52.000Z
2021-03-19T20:23:20.000Z
redisson-tomcat/redisson-tomcat-9/src/main/java/org/redisson/tomcat/AttributeUpdateMessage.java
xuziming/myredisson
420e221c5f9986e8ac54b310f251679bfc48ee70
[ "Apache-2.0" ]
null
null
null
28.461538
131
0.720946
1,001,607
/** * Copyright (c) 2013-2019 Nikita Koksharov * * 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.redisson.tomcat; import java.io.IOException; import org.redisson.client.protocol.Decoder; import org.redisson.client.protocol.Encoder; /** * * @author Nikita Koksharov * */ public class AttributeUpdateMessage extends AttributeMessage { private static final long serialVersionUID = 8554286351993846194L; private String name; private byte[] value; public AttributeUpdateMessage() { } public AttributeUpdateMessage(String nodeId, String sessionId, String name, Object value, Encoder encoder) throws IOException { super(nodeId, sessionId); this.name = name; this.value = toByteArray(encoder, value); } public String getName() { return name; } public Object getValue(Decoder<?> decoder) throws IOException, ClassNotFoundException { return toObject(decoder, value); } }
9240a52b9730267e53f023d8c7a8e86b11033d72
2,025
java
Java
bundles/org.opt4j/src/org/opt4j/genotype/PermutationGenotype.java
PalladioSimulator/Palladio-ThirdParty-Wrapper
2e50aade824d7695c720d1bec0672f1c84d8dddd
[ "Apache-2.0" ]
null
null
null
bundles/org.opt4j/src/org/opt4j/genotype/PermutationGenotype.java
PalladioSimulator/Palladio-ThirdParty-Wrapper
2e50aade824d7695c720d1bec0672f1c84d8dddd
[ "Apache-2.0" ]
null
null
null
bundles/org.opt4j/src/org/opt4j/genotype/PermutationGenotype.java
PalladioSimulator/Palladio-ThirdParty-Wrapper
2e50aade824d7695c720d1bec0672f1c84d8dddd
[ "Apache-2.0" ]
null
null
null
25
85
0.694815
1,001,608
/** * Opt4J is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Opt4J is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Opt4J. If not, see http://www.gnu.org/licenses/. */ package org.opt4j.genotype; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Random; import org.opt4j.core.Genotype; /** * The {@link PermutationGenotype} can be used as a {@link Genotype}. The order * of these elements is to be optimized. * * @param <E> * the type of elements * @author lukasiewycz * */ @SuppressWarnings("serial") public class PermutationGenotype<E> extends ArrayList<E> implements ListGenotype<E> { /** * Constructs a {@link PermutationGenotype}. */ public PermutationGenotype() { super(); } /** * Constructs a {@link PermutationGenotype}. * * @param values * the initial values */ public PermutationGenotype(Collection<E> values) { super(values); } /* * (non-Javadoc) * * @see org.opt4j.core.Genotype#newInstance() */ @Override @SuppressWarnings("unchecked") public <G extends Genotype> G newInstance() { try { return (G) this.getClass().newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } /** * Randomizes this genotype by a random permutation. * * @param random * the random number generator */ public void init(Random random) { Collections.shuffle(this, random); } }
9240a548b62f0164d106d49032c49378bbcbf7fb
1,459
java
Java
src/main/java/coordinator/models/statemachine/StateAction.java
fernandoBRS/saga-coordinator-java
ddac6327511e612ba15ef3a594d36444c974cea8
[ "MIT" ]
14
2019-07-23T08:55:38.000Z
2021-05-16T13:30:28.000Z
src/main/java/coordinator/models/statemachine/StateAction.java
fedeoliv/saga-coordinator-java
ddac6327511e612ba15ef3a594d36444c974cea8
[ "MIT" ]
3
2019-07-23T17:52:38.000Z
2019-08-08T18:32:25.000Z
src/main/java/coordinator/models/statemachine/StateAction.java
fernandoBRS/saga-coordinator-java
ddac6327511e612ba15ef3a594d36444c974cea8
[ "MIT" ]
10
2019-08-02T13:43:30.000Z
2021-03-21T17:29:43.000Z
39.432432
58
0.760795
1,001,609
package coordinator.models.statemachine; import org.springframework.statemachine.action.Action; import coordinator.models.transitions.Event; import coordinator.models.transitions.State; public interface StateAction { Action<State, Event> transferAcceptedAction(); Action<State, Event> validationStartedAction(); Action<State, Event> validationSuccededAction(); Action<State, Event> balanceStartedAction(); Action<State, Event> balanceSuccededAction(); Action<State, Event> signalingStartedAction(); Action<State, Event> signalingSuccededAction(); Action<State, Event> receiptStartedAction(); Action<State, Event> receiptSuccededAction(); Action<State, Event> transferSuccededAction(); Action<State, Event> transferFailedAction(); Action<State, Event> validationFailedAction(); Action<State, Event> validationErrorAction(); Action<State, Event> signalingErrorAction(); Action<State, Event> balanceErrorAction(); Action<State, Event> receiptErrorAction(); Action<State, Event> adhocValidationRequestedAction(); Action<State, Event> adhocSignalingRequestedAction(); Action<State, Event> adhocReceiptRequestedAction(); Action<State, Event> undoAllAction(); Action<State, Event> balanceUndoStartedAction(); Action<State, Event> balanceUndoFinishedAction(); Action<State, Event> signalingUndoStartedAction(); Action<State, Event> signalingUndoFinishedAction(); }
9240a5e0c7e3934643a8bf9a081ef64e6e97bade
10,757
java
Java
external/source/gui/msfguijava/src/msfgui/MsfguiApp.java
waynearmorize/drivesploit
7a2cc125e4363753e54a781f9d39416c2789d877
[ "OpenSSL", "Unlicense" ]
9
2015-03-13T03:59:05.000Z
2022-01-10T12:09:25.000Z
external/source/gui/msfguijava/src/msfgui/MsfguiApp.java
chenTest2013/drivesploit
7a2cc125e4363753e54a781f9d39416c2789d877
[ "OpenSSL", "Unlicense" ]
null
null
null
external/source/gui/msfguijava/src/msfgui/MsfguiApp.java
chenTest2013/drivesploit
7a2cc125e4363753e54a781f9d39416c2789d877
[ "OpenSSL", "Unlicense" ]
12
2016-01-18T02:18:37.000Z
2021-07-15T17:26:24.000Z
33.303406
140
0.695268
1,001,610
/* * MsfguiApp.java */ package msfgui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Pattern; import javax.swing.JFileChooser; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import org.jdesktop.application.Application; import org.jdesktop.application.SingleFrameApplication; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * The main class of the application. Handles global settings and system functions. * @author scriptjunkie */ public class MsfguiApp extends SingleFrameApplication { public static final int NUM_REMEMBERED_MODULES = 20; private static Element propRoot; private static List recentList = new LinkedList(); public static JFileChooser fileChooser; protected static Pattern backslash = Pattern.compile("\\\\"); static{ //get saved properties file propRoot = null; try{ String fname = System.getProperty("user.home")+File.separatorChar+".msfgui"; propRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new File(fname)).getDocumentElement(); } catch (Exception ex) { //if anything goes wrong, make new (IOException, SAXException, ParserConfigurationException, NullPointerException propRoot = getPropertiesNode();//ensure existence } Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { //Output the XML String fname = System.getProperty("user.home")+File.separatorChar+".msfgui"; try{ //save recent for(Node node = propRoot.getFirstChild(); node != null; node = node.getNextSibling()) if(node.getNodeName().equals("recent")) propRoot.removeChild(node); Document doc = propRoot.getOwnerDocument(); Node recentNode = doc.createElement("recent"); for(Object o : recentList){ Object[] args = (Object[])o; Element recentItem = doc.createElement("recentItem"); recentItem.setAttribute("moduleType",args[0].toString()); recentItem.setAttribute("fullName",args[1].toString()); for(Object p : ((Map)args[2]).entrySet()){ Map.Entry prop = (Map.Entry)p; Element propItem = doc.createElement(prop.getKey().toString()); propItem.setAttribute("val",prop.getValue().toString()); recentItem.appendChild(propItem); } recentNode.appendChild(recentItem); } propRoot.appendChild(recentNode); TransformerFactory.newInstance().newTransformer().transform( new DOMSource(propRoot), new StreamResult(new FileOutputStream(fname))); }catch (Exception ex){ } } }); } /** * At startup create and show the main frame of the application. */ @Override protected void startup() { MsfguiLog.initDefaultLog(); show(new MainFrame(this)); } /** * This method is to initialize the specified window by injecting resources. * Windows shown in our application come fully initialized from the GUI * builder, so this additional configuration is not needed. */ @Override protected void configureWindow(java.awt.Window root) { } /** * A convenient static getter for the application instance. * @return the instance of MsfguiApp */ public static MsfguiApp getApplication() { return Application.getInstance(MsfguiApp.class); } /** * Main method launching the application. */ public static void main(String[] args) { launch(MsfguiApp.class, args); } /** Application helper to launch msfrpcd or msfencode, etc. */ public static Process startMsfProc(List command) throws MsfException{ String[] args = new String[command.size()]; for(int i = 0; i < args.length; i++) args[i] = command.get(i).toString(); return startMsfProc(args); } /** Application helper to launch msfrpcd or msfencode, etc. */ public static Process startMsfProc(String[] args) throws MsfException { String msfCommand = args[0]; String prefix; try{ prefix = getPropertiesNode().getAttributeNode("commandPrefix").getValue(); }catch(Exception ex){ prefix = ""; } Process proc; String[] winArgs = null; try { args[0] = prefix + msfCommand; proc = Runtime.getRuntime().exec(args); } catch (Exception ex1) { try { proc = Runtime.getRuntime().exec(args); } catch (IOException ex2) { try { args[0] = "/opt/metasploit3/msf3/" + msfCommand; proc = Runtime.getRuntime().exec(args); } catch (IOException ex3) { try { winArgs = new String[args.length + 3]; System.arraycopy(args, 0, winArgs, 3, args.length); winArgs[0] = "cmd"; winArgs[1] = "/c"; File dir = new File(System.getenv("PROGRAMFILES") + "\\Metasploit\\Framework3\\bin\\"); if (msfCommand.equals("msfencode")) winArgs[2] = "ruby.exe"; else winArgs[2] = "rubyw.exe"; winArgs[3] = "/msf3/" + msfCommand; proc = Runtime.getRuntime().exec(winArgs, null, dir); } catch (IOException ex4) { try { File dir = new File(System.getenv("PROGRAMFILES(x86)") + "\\Metasploit\\Framework3\\bin\\"); proc = Runtime.getRuntime().exec(winArgs, null, dir); } catch (IOException ex5) { try { File dir = new File(prefix); proc = Runtime.getRuntime().exec(winArgs, null, dir); } catch (IOException ex6) { throw new MsfException("Executable not found for "+msfCommand); } } } } } } return proc; } /** Get root node of xml saved options file */ public static Element getPropertiesNode(){ if(propRoot == null){ try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = doc.createElement("root"); doc.appendChild(root); propRoot = root; } catch (ParserConfigurationException ex) { JOptionPane.showMessageDialog(null,"Error saving properties. Cannot make new properties node."); } } return propRoot; } /** Adds a module run to the recent modules list */ public static void addRecentModule(final Object[] args, final JMenu recentMenu, final RpcConnection rpcConn) { recentList.add(args); Map hash = (Map)args[2]; StringBuilder name = new StringBuilder(args[0] + " " + args[1]); for(Object ento : hash.entrySet()){ Entry ent = (Entry)ento; String propName = ent.getKey().toString(); if(propName.endsWith("HOST") || propName.endsWith("PORT") || propName.equals("PAYLOAD")) name.append(" "+propName+"-"+ent.getValue()); } final JMenuItem item = new JMenuItem(name.toString()); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new ModulePopup(rpcConn, args, recentMenu).setVisible(true); recentMenu.remove(item); recentMenu.add(item); for(int i = 0; i < recentList.size(); i++){ if(Arrays.equals((Object[])recentList.get(i), args)){ recentList.add(recentList.remove(i)); break; } } } }); recentMenu.add(item); recentMenu.setEnabled(true); if(recentMenu.getItemCount() > NUM_REMEMBERED_MODULES) recentMenu.remove(0); if(recentList.size() > NUM_REMEMBERED_MODULES) recentList.remove(0); } public static void addRecentModules(JMenu recentMenu, final RpcConnection rpcConn) { Node recentNode = null; for(Node node = propRoot.getFirstChild(); node != null; node = node.getNextSibling()) if(node.getNodeName().equals("recent")) recentNode = node; if(recentNode == null) return; NodeList recentItems = recentNode.getChildNodes(); int len = recentItems.getLength(); for(int i = 0; i < len; i++){ HashMap hash = new HashMap(); Node recentItem = recentItems.item(i); try{ String moduleType = recentItem.getAttributes().getNamedItem("moduleType").getNodeValue(); String fullName = recentItem.getAttributes().getNamedItem("fullName").getNodeValue(); NodeList recentItemProps = recentItem.getChildNodes(); int propslen = recentItemProps.getLength(); for(int j = 0; j < propslen; j++){ Node prop = recentItemProps.item(j); String propName = prop.getNodeName(); String val = prop.getAttributes().getNamedItem("val").getNodeValue(); hash.put(propName, val); } final Object[] args = new Object[]{moduleType, fullName,hash}; addRecentModule(args, recentMenu, rpcConn); }catch(NullPointerException nex){//if attribute doesn't exist, ignore } } } /** Clear history of run modules */ public static void clearHistory(JMenu recentMenu){ recentList.clear(); recentMenu.removeAll(); recentMenu.setEnabled(false); } /** Gets a temp file from system */ public static String getTempFilename(String prefix, String suffix) { try{ final File temp = File.createTempFile(prefix, suffix); String path = temp.getAbsolutePath(); temp.delete(); return path; }catch(IOException ex){ JOptionPane.showMessageDialog(null, "Cannot create temp file. This is a bad and unexpected error. What is wrong with your system?!"); return null; } } /** Gets a temp folder from system */ public static String getTempFolder() { try{ final File temp = File.createTempFile("abcde", ".bcde"); String path = temp.getParentFile().getAbsolutePath(); temp.delete(); return path; }catch(IOException ex){ JOptionPane.showMessageDialog(null, "Cannot create temp file. This is a bad and unexpected error. What is wrong with your system?!"); return null; } } /** Returns the likely local IP address for talking to the world */ public static String getLocalIp(){ try{ DatagramSocket socket = new DatagramSocket(); socket.connect(InetAddress.getByName("1.2.3.4"),1234); socket.getLocalAddress(); String answer = socket.getLocalAddress().getHostAddress(); socket.close(); return answer; } catch(IOException ioe){ try{ return InetAddress.getLocalHost().getHostAddress(); }catch (UnknownHostException uhe){ return "127.0.0.1"; } } } public static String cleanBackslashes(String input){ return backslash.matcher(input).replaceAll("/"); } public static String doubleBackslashes(String input){ return backslash.matcher(input).replaceAll("\\\\\\\\"); } }
9240a5e9afad8a22eb9a9a1466b95cc0c42d77d7
391
java
Java
mobile_app1/module420/src/main/java/module420packageJava0/Foo146.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
70
2021-01-22T16:48:06.000Z
2022-02-16T10:37:33.000Z
mobile_app1/module420/src/main/java/module420packageJava0/Foo146.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
16
2021-01-22T20:52:52.000Z
2021-08-09T17:51:24.000Z
mobile_app1/module420/src/main/java/module420packageJava0/Foo146.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
5
2021-01-26T13:53:49.000Z
2021-08-11T20:10:57.000Z
11.5
46
0.578005
1,001,611
package module420packageJava0; import java.lang.Integer; public class Foo146 { Integer int0; Integer int1; public void foo0() { new module420packageJava0.Foo145().foo5(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } }
9240a6c8b6f85e29daa79ff4caf4733e19b9096c
391
java
Java
_src/codes/chocolatestore-model/src/main/java/com/packtpub/springmvc/chocolatestore/model/service/ProductServiceImpl.java
paullewallencom/spring-978-1-7832-8653-9
3574dc7c9259b53bf969645916157e67d0dce8a7
[ "Apache-2.0" ]
null
null
null
_src/codes/chocolatestore-model/src/main/java/com/packtpub/springmvc/chocolatestore/model/service/ProductServiceImpl.java
paullewallencom/spring-978-1-7832-8653-9
3574dc7c9259b53bf969645916157e67d0dce8a7
[ "Apache-2.0" ]
null
null
null
_src/codes/chocolatestore-model/src/main/java/com/packtpub/springmvc/chocolatestore/model/service/ProductServiceImpl.java
paullewallencom/spring-978-1-7832-8653-9
3574dc7c9259b53bf969645916157e67d0dce8a7
[ "Apache-2.0" ]
null
null
null
21.722222
62
0.818414
1,001,612
package com.packtpub.springmvc.chocolatestore.model.service; import java.util.List; import org.springframework.stereotype.Service; import com.packtpub.springmvc.chocolatestore.model.Product; @Service public class ProductServiceImpl implements ProductService { @Override public List<Product> getFeaturedProducts() { return Product.findProductsByFeatured(true).getResultList(); } }
9240a850109190db12f547f1d625a35de7616afb
555
java
Java
cupdata-pms/src/main/java/com/cupdata/pms/mapper/SpuAttrValueMapper.java
heyok123/G-Store
6d317ef8acbb2f1459b7647e29553d23906ea852
[ "Apache-2.0" ]
null
null
null
cupdata-pms/src/main/java/com/cupdata/pms/mapper/SpuAttrValueMapper.java
heyok123/G-Store
6d317ef8acbb2f1459b7647e29553d23906ea852
[ "Apache-2.0" ]
null
null
null
cupdata-pms/src/main/java/com/cupdata/pms/mapper/SpuAttrValueMapper.java
heyok123/G-Store
6d317ef8acbb2f1459b7647e29553d23906ea852
[ "Apache-2.0" ]
null
null
null
23.083333
76
0.738267
1,001,613
package com.cupdata.pms.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.cupdata.pms.entity.SpuAttrValueEntity; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * spu属性值 * * @author 这周日没空 * @email [email protected] * @date 2020-12-15 13:44:06 */ @Mapper public interface SpuAttrValueMapper extends BaseMapper<SpuAttrValueEntity> { /** * @Description: 根据spuId查询检索属性及值 * Created by Wsork on 2021/1/29 11:10 */ List<SpuAttrValueEntity> querySpuAttrValueBySpuId(long spuId);}
9240a86fbe0e211a29b67355af2e2cb6505d8364
1,038
java
Java
src/main/java/dev/wakandaacademy/api/domain/wakander/service/goals/impl/CurrentWakanderGoalJpaService.java
aceleradev/wakanda-user-signup-be
aa4774a9134308bab79463c7524cdcac524930e6
[ "Apache-2.0" ]
1
2022-01-21T03:21:41.000Z
2022-01-21T03:21:41.000Z
src/main/java/dev/wakandaacademy/api/domain/wakander/service/goals/impl/CurrentWakanderGoalJpaService.java
aceleradev/wakanda-user-signup-be
aa4774a9134308bab79463c7524cdcac524930e6
[ "Apache-2.0" ]
3
2020-07-20T13:15:20.000Z
2020-10-20T20:47:44.000Z
src/main/java/dev/wakandaacademy/api/domain/wakander/service/goals/impl/CurrentWakanderGoalJpaService.java
aceleradev/wakanda-user-signup-be
aa4774a9134308bab79463c7524cdcac524930e6
[ "Apache-2.0" ]
3
2020-08-12T02:46:33.000Z
2021-12-16T18:50:01.000Z
25.317073
100
0.840077
1,001,614
package dev.wakandaacademy.api.domain.wakander.service.goals.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import dev.wakandaacademy.api.domain.wakander.model.WakanderGoal; import dev.wakandaacademy.api.domain.wakander.repository.CurrentWakanderGoalRepository; import dev.wakandaacademy.api.domain.wakander.service.goals.WakanderGoalService; import dev.wakandaacademy.api.exception.BusinessException; //@Service public class CurrentWakanderGoalJpaService implements WakanderGoalService { private static final Logger log = LoggerFactory.getLogger(WakanderGoalsJpaService.class); private CurrentWakanderGoalRepository currentWakanderGoalRepository; public CurrentWakanderGoalJpaService(CurrentWakanderGoalRepository currentWakanderGoalRepository) { this.currentWakanderGoalRepository = currentWakanderGoalRepository; } @Override public WakanderGoal getCurrentGoal(String wakanderCode) throws BusinessException { //TODO return null; } }
9240ab9e104318779648e3aa40b33e236871dc46
1,345
java
Java
java-analysis-impl/src/main/java/com/intellij/codeInspection/bytecodeAnalysis/Equation.java
consulo/consulo-java
e016b25321f49547a57e97132c013468c2a50316
[ "Apache-2.0" ]
5
2015-12-19T15:27:30.000Z
2019-08-17T10:07:23.000Z
java-analysis-impl/src/main/java/com/intellij/codeInspection/bytecodeAnalysis/Equation.java
consulo/consulo-java
e016b25321f49547a57e97132c013468c2a50316
[ "Apache-2.0" ]
47
2015-02-28T12:45:13.000Z
2021-12-15T15:42:34.000Z
java-analysis-impl/src/main/java/com/intellij/codeInspection/bytecodeAnalysis/Equation.java
consulo/consulo-java
e016b25321f49547a57e97132c013468c2a50316
[ "Apache-2.0" ]
2
2018-03-08T16:17:47.000Z
2019-08-17T18:20:38.000Z
22.04918
75
0.69145
1,001,615
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.intellij.codeInspection.bytecodeAnalysis; import javax.annotation.Nonnull; final class Equation { @Nonnull final EKey key; @Nonnull final Result result; Equation(@Nonnull EKey key, @Nonnull Result result) { this.key = key; this.result = result; } @Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } Equation equation = (Equation) o; return key.equals(equation.key) && result.equals(equation.result); } @Override public int hashCode() { return 31 * key.hashCode() + result.hashCode(); } @Override public String toString() { return "Equation{" + "key=" + key + ", result=" + result + '}'; } }
9240ac23e697b4bf3b7d637f1436206aacc79641
833
java
Java
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/facebook/stetho/inspector/protocol/module/SimpleBooleanResult.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/facebook/stetho/inspector/protocol/module/SimpleBooleanResult.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/facebook/stetho/inspector/protocol/module/SimpleBooleanResult.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
25.242424
62
0.614646
1,001,616
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.facebook.stetho.inspector.protocol.module; import com.facebook.stetho.inspector.jsonrpc.JsonRpcResult; public class SimpleBooleanResult implements JsonRpcResult { public SimpleBooleanResult() { // 0 0:aload_0 // 1 1:invokespecial #15 <Method void Object()> // 2 4:return } public SimpleBooleanResult(boolean flag) { // 0 0:aload_0 // 1 1:invokespecial #15 <Method void Object()> result = flag; // 2 4:aload_0 // 3 5:iload_1 // 4 6:putfield #19 <Field boolean result> // 5 9:return } public boolean result; }
9240ac3c1c6fbb2ad0cd38ad2197373e2b1e2c64
62
java
Java
coeey/com/google/android/gms/internal/zzbeb.java
ankurshukla1993/IOT-test
174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6
[ "Apache-2.0" ]
1
2021-08-21T17:56:56.000Z
2021-08-21T17:56:56.000Z
coeey/com/google/android/gms/internal/zzbeb.java
ankurshukla1993/IOT-test
174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6
[ "Apache-2.0" ]
null
null
null
coeey/com/google/android/gms/internal/zzbeb.java
ankurshukla1993/IOT-test
174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6
[ "Apache-2.0" ]
1
2018-11-26T08:56:33.000Z
2018-11-26T08:56:33.000Z
12.4
40
0.774194
1,001,617
package com.google.android.gms.internal; interface zzbeb { }
9240ad195d21000f5d209cb6864bc0f42545bc7b
5,191
java
Java
Map/src/BSTMap.java
joy20182018/data_structure_java
814c16ff8ecf0d92b89cf3b240244bed376f78ee
[ "MIT" ]
1
2019-12-16T07:09:16.000Z
2019-12-16T07:09:16.000Z
Map/src/BSTMap.java
joy20182018/data_structure_java
814c16ff8ecf0d92b89cf3b240244bed376f78ee
[ "MIT" ]
null
null
null
Map/src/BSTMap.java
joy20182018/data_structure_java
814c16ff8ecf0d92b89cf3b240244bed376f78ee
[ "MIT" ]
null
null
null
24.956731
81
0.479484
1,001,618
import java.util.ArrayList; // 基于二分搜索树的映射实现 public class BSTMap<K extends Comparable<K>, V> implements Map<K, V> { private class Node{ public K key; public V value; public Node left, right; public Node(K key, V value){ this.key = key; this.value = value; left = null; right = null; } } private Node root; private int size; @Override public int getSize() { return size; } @Override public boolean isEmpty() { return size == 0; } // 向二分搜索树中添加新的元素(key, value) @Override public void add(K key, V value) { root = add(root, key, value); } // 向以node为根的二分搜索树中插入元素(key, value),递归算法 // 返回插入新节点后二分搜索树的根 private Node add(Node node, K key, V value){ if(node == null){ size ++; return new Node(key, value); } if(key.compareTo(node.key) < 0) node.left = add(node.left, key, value); else if(key.compareTo(node.key) > 0) node.right = add(node.right, key, value); else // key.compareTo(node.key) == 0 node.value = value; return node; } // 返回以node为根节点的二分搜索树中,key所在的节点 private Node getNode(Node node, K key){ if (node == null) return null; if (key.compareTo(node.key) == 0) return node; else if (key.compareTo(node.key) < 0) return getNode(node.left, key); else // if (key.compareTo(node.key)) > 0 return getNode(node.right, key); } @Override public boolean contains(K key) { return getNode(root, key) != null; } @Override public V get(K key) { Node node = getNode(root, key); return node == null ? null : node.value; } // 更新操作 @Override public void set(K key, V newValue) { Node node = getNode(root, key); if (node == null) throw new IllegalArgumentException(key + " deesn`t exists"); node.value = newValue; } // 返回以node为根的二分搜索树的最小值所在的节点 private Node minimum(Node node){ if(node.left == null) return node; return minimum(node.left); } // 删除掉以node为根的二分搜索树中的最小节点 // 返回删除节点后新的二分搜索树的根 private Node removeMin(Node node){ if(node.left == null){ Node rightNode = node.right; node.right = null; size --; return rightNode; } node.left = removeMin(node.left); return node; } // 从二分搜索树中删除键为key的节点 @Override public V remove(K key) { Node node = getNode(root, key); if (node != null){ root = remove(root, key); return node.value; } return null; } // 删除以node为根的二分搜索树中键为key的节点,递归算法 // 返回删除节点后新的二分搜索树的根 private Node remove(Node node, K key){ if (node == null){ return null; } if (key.compareTo(node.key) < 0){ node.left = remove(node.left, key); return node; } else if (key.compareTo(node.key) > 0){ node.right = remove(node.right, key); return node; } else{ // key.compareTo(node.key) == 0 // 待删除节点左子树为空的情况 if (node.left == null){ // 此时的node为待删除节点 Node rightNode = node.right; node.right = null; size --; return rightNode; // 返回右子树根节点 } // 待删除节点右子树为空的情况 if (node.right == null){ Node leftNode = node.left; node.left = null; size --; return leftNode; } // 待删除节点左右子树都不为空的情况 // 找到比待删除节点大的节点, 即待删除节点右子树的最小节点 // 或比待删除结点小的节点,即左子树最大节点 // 用这个节点顶替待删除节点的位置 Node successor = minimum(node.right); successor.right = removeMin(node.right); successor.left = node.left; node.left = node.right = null; return successor; } } // public static void main(String[] args) { // // write your code here // // System.out.println("Pride and Prejudice"); // // ArrayList<String> words = new ArrayList<>(); // // if (FileOperation.readFile("e:/java/Pride and Prejudice.txt", words)){ // // System.out.println("Total words: " + words.size()); // // BSTMap<String, Integer> map = new BSTMap<>(); // // for (String word: words){ // if (map.contains(word)) // map.set(word, map.get(word) + 1); // else // map.add(word, 1); // } // System.out.println("Total different words: " + map.getSize()); // System.out.println("Frequency of By: " + map.get("By") ); // } // } }
9240ad36641457ab9adbe447b16151a356f334f2
7,286
java
Java
dhis-2/dhis-api/src/main/java/org/hisp/dhis/dashboard/DashboardContent.java
hispindia/BIHAR-2.7
207e616abaa53aae343265b4db0699263cdde5bb
[ "BSD-3-Clause" ]
null
null
null
dhis-2/dhis-api/src/main/java/org/hisp/dhis/dashboard/DashboardContent.java
hispindia/BIHAR-2.7
207e616abaa53aae343265b4db0699263cdde5bb
[ "BSD-3-Clause" ]
10
2020-06-30T23:07:53.000Z
2022-02-09T22:55:05.000Z
dhis-2/dhis-api/src/main/java/org/hisp/dhis/dashboard/DashboardContent.java
hispindia/BIHAR-2.7
207e616abaa53aae343265b4db0699263cdde5bb
[ "BSD-3-Clause" ]
null
null
null
28.912698
93
0.623113
1,001,619
package org.hisp.dhis.dashboard; /* * Copyright (c) 2004-2012, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.Dxf2Namespace; import org.hisp.dhis.common.adapter.*; import org.hisp.dhis.document.Document; import org.hisp.dhis.mapping.MapView; import org.hisp.dhis.report.Report; import org.hisp.dhis.reporttable.ReportTable; import org.hisp.dhis.user.User; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.ArrayList; import java.util.List; /** * it would make sense to make this an idObject, so that we could have nameable (switchable?) * dashboards, would be great for default content etc. * * @author Lars Helge Overland */ @XmlRootElement( name = "dashboardContent", namespace = Dxf2Namespace.NAMESPACE ) @XmlAccessorType( value = XmlAccessType.NONE ) public class DashboardContent { private final static int MAX_DASHBOARD_ELEMENTS = 6; private int id; private User user; private List<Report> reports = new ArrayList<Report>(); private List<Document> documents = new ArrayList<Document>(); private List<ReportTable> reportTables = new ArrayList<ReportTable>(); private List<MapView> mapViews = new ArrayList<MapView>(); public DashboardContent() { } public DashboardContent( User user ) { this.user = user; } public int hashCode() { return user.hashCode(); } public boolean equals( Object object ) { if ( this == object ) { return true; } if ( object == null ) { return false; } if ( object.getClass() != getClass() ) { return false; } final DashboardContent other = (DashboardContent) object; return user.equals( other.user ); } // ------------------------------------------------------------------------- // Logic // ------------------------------------------------------------------------- public void addReport( Report report ) { if ( !reports.contains( report ) ) { reports.add( 0, report ); while ( reports.size() > MAX_DASHBOARD_ELEMENTS ) { reports.remove( MAX_DASHBOARD_ELEMENTS ); } } } public void addDocument( Document document ) { if ( !documents.contains( document ) ) { documents.add( 0, document ); while ( documents.size() > MAX_DASHBOARD_ELEMENTS ) { documents.remove( MAX_DASHBOARD_ELEMENTS ); } } } public void addReportTable( ReportTable reportTable ) { if ( !reportTables.contains( reportTable ) ) { reportTables.add( 0, reportTable ); while ( reportTables.size() > MAX_DASHBOARD_ELEMENTS ) { reportTables.remove( MAX_DASHBOARD_ELEMENTS ); } } } public void addMapView( MapView mapView ) { if ( !mapViews.contains( mapView ) ) { mapViews.add( 0, mapView ); while ( mapViews.size() > MAX_DASHBOARD_ELEMENTS ) { mapViews.remove( MAX_DASHBOARD_ELEMENTS ); } } } // ------------------------------------------------------------------------- // Getters & setters // ------------------------------------------------------------------------- @XmlAttribute( name = "internalId" ) @JsonProperty( value = "internalId" ) public int getId() { return id; } public void setId( int id ) { this.id = id; } @XmlElement( name = "user" ) @XmlJavaTypeAdapter( UserXmlAdapter.class ) @JsonProperty @JsonSerialize( contentAs = BaseIdentifiableObject.class ) public User getUser() { return user; } public void setUser( User user ) { this.user = user; } @XmlElementWrapper( name = "reports" ) @XmlElement( name = "report" ) @XmlJavaTypeAdapter( ReportXmlAdapter.class ) @JsonProperty @JsonSerialize( contentAs = BaseIdentifiableObject.class ) public List<Report> getReports() { return reports; } public void setReports( List<Report> reports ) { this.reports = reports; } @XmlElementWrapper( name = "documents" ) @XmlElement( name = "document" ) @XmlJavaTypeAdapter( DocumentXmlAdapter.class ) @JsonProperty @JsonSerialize( contentAs = BaseIdentifiableObject.class ) public List<Document> getDocuments() { return documents; } public void setDocuments( List<Document> documents ) { this.documents = documents; } @XmlElementWrapper( name = "reportTables" ) @XmlElement( name = "reportTable" ) @XmlJavaTypeAdapter( ReportTableXmlAdapter.class ) @JsonProperty @JsonSerialize( contentAs = BaseIdentifiableObject.class ) public List<ReportTable> getReportTables() { return reportTables; } public void setReportTables( List<ReportTable> reportTables ) { this.reportTables = reportTables; } @XmlElementWrapper( name = "mapViews" ) @XmlElement( name = "mapView" ) @XmlJavaTypeAdapter( MapViewXmlAdapter.class ) @JsonProperty @JsonSerialize( contentAs = BaseIdentifiableObject.class ) public List<MapView> getMapViews() { return mapViews; } public void setMapViews( List<MapView> mapViews ) { this.mapViews = mapViews; } }
9240ad9430e89afdbf99936a5566e3a184d2c984
8,825
java
Java
uimaj-core/src/main/java/org/apache/uima/UIMAException.java
matthkoch/uima-uimaj
6fa03e80753213ea072c257dd3baa37007412fe5
[ "Apache-2.0" ]
41
2015-04-05T21:51:49.000Z
2021-11-06T22:04:26.000Z
uimaj-core/src/main/java/org/apache/uima/UIMAException.java
matthkoch/uima-uimaj
6fa03e80753213ea072c257dd3baa37007412fe5
[ "Apache-2.0" ]
42
2018-03-28T21:15:49.000Z
2022-01-21T15:11:00.000Z
uimaj-core/src/main/java/org/apache/uima/UIMAException.java
matthkoch/uima-uimaj
6fa03e80753213ea072c257dd3baa37007412fe5
[ "Apache-2.0" ]
46
2015-06-03T22:50:04.000Z
2021-11-26T14:29:19.000Z
36.020408
100
0.693711
1,001,620
/* * 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.uima; import java.util.Locale; /** * This is the superclass for all checked exceptions in UIMA. * * It adds use of a "standard" bundle resource, if the subclasses don't define this. * * <p> * <code>UIMAException</code> extends {@link InternationalizedException} for internationalization * support. Since UIMA Exceptions are internationalized, the thrower does not supply a hardcoded * message. Instead, the thrower specifies a key that identifies the message. That key is then * looked up in a locale-specific {@link java.util.ResourceBundle ResourceBundle} to find the actual * message associated with this exception. * <p> * The thrower may specify the name of the <code>ResourceBundle</code> in which to find the * exception message. Any name may be used. If the name is omitted, the resource bundle identified * by {@link #STANDARD_MESSAGE_CATALOG} will be used. This contains the standard UIMA exception * messages. */ public class UIMAException extends Exception implements I18nExceptionI { private static final long serialVersionUID = 7521732353239537026L; /** * The name of the {@link java.util.ResourceBundle ResourceBundle} containing the standard UIMA * Exception messages. */ public static final String STANDARD_MESSAGE_CATALOG = "org.apache.uima.UIMAException_Messages"; /** * The base name of the resource bundle in which the message for this exception is located. */ private String mResourceBundleName = STANDARD_MESSAGE_CATALOG; // use a default /** * An identifier that maps to the message for this exception. */ private String mMessageKey; /** * The arguments to this exception's message, if any. This allows an * <code>InternationalizedException</code> to have a compound message, made up of multiple parts * that are concatenated in a language-neutral way. */ private Object[] mArguments; /** * The exception that caused this exception to occur. */ private Throwable mCause; /** * Creates a new exception with a null message. */ public UIMAException() { } /** * Creates a new exception with the specified cause and a null message. * * @param aCause * the original exception that caused this exception to be thrown, if any */ public UIMAException(Throwable aCause) { super(aCause); mCause = aCause; if (mMessageKey == null && (aCause instanceof I18nExceptionI)) { I18nExceptionI cause = (I18nExceptionI) aCause; mMessageKey = cause.getMessageKey(); mArguments = cause.getArguments(); } } /** * Creates a new exception with a the specified message. * * @param aResourceBundleName * the base name of the resource bundle in which the message for this exception is * located. * @param aMessageKey * an identifier that maps to the message for this exception. The message may contain * placeholders for arguments as defined by the {@link java.text.MessageFormat * MessageFormat} class. * @param aArguments * The arguments to the message. <code>null</code> may be used if the message has no * arguments. */ public UIMAException(String aResourceBundleName, String aMessageKey, Object... aArguments) { this(aResourceBundleName, aMessageKey, aArguments, null); } /** * Creates a new exception with the specified message and cause. * * @param aResourceBundleName * the base name of the resource bundle in which the message for this exception is * located. * @param aMessageKey * an identifier that maps to the message for this exception. The message may contain * placeholders for arguments as defined by the {@link java.text.MessageFormat * MessageFormat} class. * @param aArguments * The arguments to the message. <code>null</code> may be used if the message has no * arguments. * @param aCause * the original exception that caused this exception to be thrown, if any */ public UIMAException(String aResourceBundleName, String aMessageKey, Object[] aArguments, Throwable aCause) { super(aCause); this.mResourceBundleName = aResourceBundleName; this.mMessageKey = aMessageKey; this.mArguments = aArguments; this.mCause = aCause; } /** * Creates a new exception with a message from the {@link #STANDARD_MESSAGE_CATALOG}. * * @param aMessageKey * an identifier that maps to the message for this exception. The message may contain * placeholders for arguments as defined by the {@link java.text.MessageFormat * MessageFormat} class. * @param aArguments * The arguments to the message. <code>null</code> may be used if the message has no * arguments. */ public UIMAException(String aMessageKey, Object[] aArguments) { this(STANDARD_MESSAGE_CATALOG, aMessageKey, aArguments, null); } /** * Creates a new exception with the specified cause and a message from the * {@link #STANDARD_MESSAGE_CATALOG}. * * @param aMessageKey * an identifier that maps to the message for this exception. The message may contain * placeholders for arguments as defined by the {@link java.text.MessageFormat * MessageFormat} class. * @param aArguments * The arguments to the message. <code>null</code> may be used if the message has no * arguments. * @param aCause * the original exception that caused this exception to be thrown, if any */ public UIMAException(String aMessageKey, Object[] aArguments, Throwable aCause) { this(STANDARD_MESSAGE_CATALOG, aMessageKey, aArguments, aCause); } /** * Gets the cause of this Exception. * * @return the Throwable that caused this Exception to occur, if any. Returns <code>null</code> if * there is no such cause. */ @Override public Throwable getCause() { return mCause; } @Override public synchronized Throwable initCause(Throwable cause) { mCause = cause; return this; } /** * Gets the base name of the resource bundle in which the message for this exception is located. * * @return the resource bundle base name. May return <code>null</code> if this exception has no * message. */ @Override public String getResourceBundleName() { return mResourceBundleName; } /** * Gets the identifier for this exception's message. This identifier can be looked up in this * exception's {@link java.util.ResourceBundle ResourceBundle} to get the locale-specific message * for this exception. * * @return the resource identifier for this exception's message. May return <code>null</code> if * this exception has no message. */ @Override public String getMessageKey() { return mMessageKey; } /** * Gets the arguments to this exception's message. Arguments allow a * <code>InternationalizedException</code> to have a compound message, made up of multiple parts * that are concatenated in a language-neutral way. * * @return the arguments to this exception's message. */ @Override public Object[] getArguments() { if (mArguments == null) { return new Object[0]; } return mArguments.clone(); } /** * @return The message of the exception. Useful for including the text in another exception. */ @Override public String getMessage() { return getLocalizedMessage(Locale.ENGLISH); } /** * Gets the localized detail message for this exception. This uses the default Locale for this * JVM. A Locale may be specified using {@link #getLocalizedMessage(Locale)}. * * @return this exception's detail message, localized for the default Locale. */ @Override public String getLocalizedMessage() { return getLocalizedMessage(Locale.getDefault()); } }
9240adc7b32dcfb4de9d3d8e50a39ae319975299
1,965
java
Java
discovery/src/main/java/com/proofpoint/discovery/client/ServiceTypeImpl.java
johngmyers/platform
b5bd4a70adcde319ee93df6cd5cc1cbc4fe31843
[ "ECL-2.0", "Apache-2.0" ]
37
2015-01-16T03:22:57.000Z
2022-02-28T18:10:15.000Z
discovery/src/main/java/com/proofpoint/discovery/client/ServiceTypeImpl.java
johngmyers/platform
b5bd4a70adcde319ee93df6cd5cc1cbc4fe31843
[ "ECL-2.0", "Apache-2.0" ]
267
2015-01-09T22:22:47.000Z
2021-09-27T17:42:23.000Z
discovery/src/main/java/com/proofpoint/discovery/client/ServiceTypeImpl.java
johngmyers/platform
b5bd4a70adcde319ee93df6cd5cc1cbc4fe31843
[ "ECL-2.0", "Apache-2.0" ]
45
2015-01-30T21:31:32.000Z
2022-02-03T19:24:06.000Z
24.873418
143
0.613232
1,001,621
/* * Copyright 2010 Proofpoint, Inc. * * 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.proofpoint.discovery.client; import java.lang.annotation.Annotation; import static java.util.Objects.requireNonNull; class ServiceTypeImpl implements ServiceType { private final String value; ServiceTypeImpl(String value) { requireNonNull(value, "value is null"); this.value = value; } @Override public String value() { return value; } @Override public String toString() { var isJava11 = System.getProperty("java.version").startsWith("11."); return String.format("@%s(%s\"%s\")", ServiceType.class.getName(), isJava11 ? "value=" : "", value.replaceAll("([\\\\\"])", "\\\\$1")); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ServiceType)) { return false; } ServiceType that = (ServiceType) o; if (!value.equals(that.value())) { return false; } return true; } @Override public int hashCode() { // see Annotation.hashCode() int result = 0; result += ((127 * "value".hashCode()) ^ value.hashCode()); return result; } @Override public Class<? extends Annotation> annotationType() { return ServiceType.class; } }
9240ae370ef9178028320a902c441a876241ec5f
1,823
java
Java
src/main/java/com/programcreek/designpatterns/mediator/MediatorExample.java
bobozhengsir/DesignPatternsStories
6a0de23748cc1428b760fb7c41ae3fe766d6765e
[ "Unlicense" ]
null
null
null
src/main/java/com/programcreek/designpatterns/mediator/MediatorExample.java
bobozhengsir/DesignPatternsStories
6a0de23748cc1428b760fb7c41ae3fe766d6765e
[ "Unlicense" ]
null
null
null
src/main/java/com/programcreek/designpatterns/mediator/MediatorExample.java
bobozhengsir/DesignPatternsStories
6a0de23748cc1428b760fb7c41ae3fe766d6765e
[ "Unlicense" ]
1
2018-10-31T01:38:31.000Z
2018-10-31T01:38:31.000Z
20.954023
61
0.647285
1,001,622
package com.programcreek.designpatterns.mediator; /** * Created with IntelliJ IDEA. * User: wujiaoniao * Date: 13-12-17 * Time: 下午6:42 * Description: Mediator(中介者模式). */ interface IMediator { public void fight(); public void talk(); public void registerA(ColleagueA a); public void registerB(ColleagueB b); } //concrete mediator class ConcreteMediator implements IMediator { ColleagueA talk; ColleagueB fight; @Override public void registerA(ColleagueA a) { this.talk = a; } @Override public void registerB(ColleagueB b) { this.fight = b; } @Override public void fight() { System.out.println("Mediator is fighting."); //let the fight colleague do some stuff } @Override public void talk() { System.out.println("Mediator is talking."); //let the talk colleague do some stuff } } abstract class Colleague { IMediator mediator; public abstract void doSomething(); } class ColleagueA extends Colleague { public ColleagueA(IMediator mediator) { this.mediator = mediator; } @Override public void doSomething() { this.mediator.talk(); this.mediator.registerA(this); } } class ColleagueB extends Colleague { public ColleagueB(IMediator mediator) { this.mediator = mediator; this.mediator.registerB(this); } @Override public void doSomething() { this.mediator.fight(); } } public class MediatorExample { public static void run() { IMediator mediator = new ConcreteMediator(); ColleagueA talkColleague = new ColleagueA(mediator); ColleagueB fightColleague = new ColleagueB(mediator); talkColleague.doSomething(); fightColleague.doSomething(); } }
9240b03f28de6f1a8c2bd3e8523d4923d8de07b4
270
java
Java
src/main/java/tn/esprit/spring/repository/LineRepository.java
nejiba99/ConsommiTounsi
49469a89788ddde4cf8ad1f98b197b46e6cb8585
[ "Apache-2.0" ]
null
null
null
src/main/java/tn/esprit/spring/repository/LineRepository.java
nejiba99/ConsommiTounsi
49469a89788ddde4cf8ad1f98b197b46e6cb8585
[ "Apache-2.0" ]
null
null
null
src/main/java/tn/esprit/spring/repository/LineRepository.java
nejiba99/ConsommiTounsi
49469a89788ddde4cf8ad1f98b197b46e6cb8585
[ "Apache-2.0" ]
null
null
null
22.5
68
0.833333
1,001,623
package tn.esprit.spring.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import tn.esprit.spring.entity.Line; @Repository public interface LineRepository extends CrudRepository<Line, Long> { }
9240b0889b96387b4f0dea5677fecf6d9d015d27
678
java
Java
core/src/test/java/com/khubla/simpleioc/annotation/TestRegistryBeanAnnotation.java
teverett/simpleioc
16647adc2746dcc12eb0760c1e5d2f8ed88a7887
[ "BSD-3-Clause" ]
1
2016-06-15T09:43:50.000Z
2016-06-15T09:43:50.000Z
core/src/test/java/com/khubla/simpleioc/annotation/TestRegistryBeanAnnotation.java
teverett/simpleioc
16647adc2746dcc12eb0760c1e5d2f8ed88a7887
[ "BSD-3-Clause" ]
8
2016-07-22T14:53:55.000Z
2022-02-15T22:04:09.000Z
core/src/test/java/com/khubla/simpleioc/annotation/TestRegistryBeanAnnotation.java
teverett/simpleioc
16647adc2746dcc12eb0760c1e5d2f8ed88a7887
[ "BSD-3-Clause" ]
1
2018-11-23T11:14:45.000Z
2018-11-23T11:14:45.000Z
25.111111
103
0.737463
1,001,624
package com.khubla.simpleioc.annotation; import org.junit.*; import com.khubla.simpleioc.*; import com.khubla.simpleioc.impl.*; /** * @author tome */ public class TestRegistryBeanAnnotation { @Test public void test1() { try { final IOCBeanRegistry autobeanRegistry = new DefaultIOCBeanRegistry(); autobeanRegistry.load(); Assert.assertNotNull(autobeanRegistry); final ExampleAnnotatedBean exampleBean = (ExampleAnnotatedBean) autobeanRegistry.getBean("regBean"); Assert.assertNotNull(exampleBean); Assert.assertTrue(exampleBean.getField().compareTo("hi there") == 0); } catch (final Exception e) { e.printStackTrace(); Assert.fail(); } } }
9240b0e9b46c018b9496aaafef364192f2c41f19
1,113
java
Java
server/dal/src/main/java/com/vmware/bdd/dal/impl/ServerInfoDAO.java
isabella232/serengeti-ws
fb764f066178cd631ca66d0e735bf047db0db623
[ "Apache-2.0" ]
15
2015-06-04T10:55:30.000Z
2020-02-19T09:05:00.000Z
server/dal/src/main/java/com/vmware/bdd/dal/impl/ServerInfoDAO.java
vmware-serengeti/serengeti-ws
fb764f066178cd631ca66d0e735bf047db0db623
[ "Apache-2.0" ]
8
2015-03-04T07:19:37.000Z
2021-01-20T22:25:38.000Z
server/dal/src/main/java/com/vmware/bdd/dal/impl/ServerInfoDAO.java
isabella232/serengeti-ws
fb764f066178cd631ca66d0e735bf047db0db623
[ "Apache-2.0" ]
13
2015-03-15T04:23:36.000Z
2020-12-12T10:48:52.000Z
33.727273
88
0.649596
1,001,625
/*************************************************************************** * Copyright (c) 2012-2013 VMware, Inc. 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.vmware.bdd.dal.impl; import org.springframework.stereotype.Repository; import com.vmware.bdd.dal.IServerInfoDAO; import com.vmware.bdd.entity.ServerInfoEntity; /** * @author Jarred Li * @since 0.8 * @version 0.8 * */ @Repository public class ServerInfoDAO extends BaseDAO<ServerInfoEntity> implements IServerInfoDAO { }
9240b13924356f63b747a339224f554baf3aa743
300
java
Java
src/main/java/Model/Item/ItemProperty/ExplosiveProperty.java
ftvkyo/pt-strategy
c935834b1ca7372202ce86205dd68ca2b337092c
[ "MIT" ]
null
null
null
src/main/java/Model/Item/ItemProperty/ExplosiveProperty.java
ftvkyo/pt-strategy
c935834b1ca7372202ce86205dd68ca2b337092c
[ "MIT" ]
null
null
null
src/main/java/Model/Item/ItemProperty/ExplosiveProperty.java
ftvkyo/pt-strategy
c935834b1ca7372202ce86205dd68ca2b337092c
[ "MIT" ]
2
2020-01-31T07:48:39.000Z
2021-03-21T20:57:05.000Z
20
84
0.756667
1,001,626
package Model.Item.ItemProperty; import Model.Item.GenericItem; import Model.Unit.IUnit; public class ExplosiveProperty extends GenericProperty { @Override public void onActivate(GenericItem thisItem, IUnit thisUnit, IUnit targetUnit) { thisUnit.changeHealthPoints(-10); } }
9240b1d0a1baffd7fe67f655182bd79cb34b40bc
1,009
java
Java
sunbird_portal/src/test/java/org/sunbird/testscripts/Reviewer_TC01.java
neha0305verma/sunbird-functional-tests
8dc11b9c4e3251a1f7f12714f8efc954b12c4ddc
[ "MIT" ]
1
2019-07-02T07:05:26.000Z
2019-07-02T07:05:26.000Z
sunbird_portal/src/test/java/org/sunbird/testscripts/Reviewer_TC01.java
neha0305verma/sunbird-functional-tests
8dc11b9c4e3251a1f7f12714f8efc954b12c4ddc
[ "MIT" ]
9
2018-07-18T05:47:31.000Z
2018-12-21T13:22:44.000Z
sunbird_portal/src/test/java/org/sunbird/testscripts/Reviewer_TC01.java
neha0305verma/sunbird-functional-tests
8dc11b9c4e3251a1f7f12714f8efc954b12c4ddc
[ "MIT" ]
22
2018-07-27T11:43:09.000Z
2022-03-31T06:03:44.000Z
28.828571
99
0.815659
1,001,627
package org.sunbird.testscripts; import org.testng.annotations.Test; import java.util.List; import org.sunbird.generic.ReadTestDataFromExcel; import org.sunbird.pageobjects.CreatorUserPageObj; import org.sunbird.pageobjects.SignUpObj; import org.sunbird.startup.BaseTest; import org.sunbird.testdata.TestDataForSunbird; import org.testng.annotations.Test; public class Reviewer_TC01 extends BaseTest { @Test public void testCase01() throws Exception { List <TestDataForSunbird> objListOFTestDataForSunbird= null ; objListOFTestDataForSunbird = ReadTestDataFromExcel.getTestDataForSunbird("testdatasheetcourse"); SignUpObj signupObj = new SignUpObj(); CreatorUserPageObj creatorUserPageObj = new CreatorUserPageObj(); //Login as content creator signupObj.userLogin(CREATOR); //create a course creatorUserPageObj.createResource(objListOFTestDataForSunbird); //Submit the course for review creatorUserPageObj.saveAndSendCourseForReview(objListOFTestDataForSunbird); } }
9240b1d549c2c47214aa18ab91cc6a72f3e99c88
1,751
java
Java
src/main/java/io/codera/quant/strategy/meanrevertion/ZScoreExitCriterion.java
dataronio/quant
d421d676c0c35814dc885a36ca3f3a034f824ef7
[ "MIT" ]
77
2017-08-01T06:06:29.000Z
2020-09-15T14:41:00.000Z
src/main/java/io/codera/quant/strategy/meanrevertion/ZScoreExitCriterion.java
dataronio/quant
d421d676c0c35814dc885a36ca3f3a034f824ef7
[ "MIT" ]
1
2020-06-18T15:39:08.000Z
2020-06-18T15:39:08.000Z
src/main/java/io/codera/quant/strategy/meanrevertion/ZScoreExitCriterion.java
dataronio/quant
d421d676c0c35814dc885a36ca3f3a034f824ef7
[ "MIT" ]
42
2017-08-28T17:30:02.000Z
2020-09-15T14:41:01.000Z
33.037736
99
0.7253
1,001,628
package io.codera.quant.strategy.meanrevertion; import io.codera.quant.context.TradingContext; import io.codera.quant.exception.CriterionViolationException; import io.codera.quant.exception.NoOrderAvailable; import io.codera.quant.exception.PriceNotAvailableException; import io.codera.quant.strategy.Criterion; /** * */ public class ZScoreExitCriterion implements Criterion { private final String firstSymbol; private final String secondSymbol; private ZScore zScore; private TradingContext tradingContext; private double exitZScore; public ZScoreExitCriterion(String firstSymbol, String secondSymbol, ZScore zScore, TradingContext tradingContext) { this.zScore = zScore; this.firstSymbol = firstSymbol; this.secondSymbol = secondSymbol; this.tradingContext = tradingContext; } public ZScoreExitCriterion(String firstSymbol, String secondSymbol, double exitZScore, ZScore zScore, TradingContext tradingContext) { this(firstSymbol, secondSymbol, zScore, tradingContext); this.exitZScore = exitZScore; } @Override public boolean isMet() throws CriterionViolationException { try { double zs = zScore.get( tradingContext.getLastPrice(firstSymbol), tradingContext.getLastPrice(secondSymbol)); if(tradingContext.getLastOrderBySymbol(firstSymbol).isShort() && zs < exitZScore || tradingContext.getLastOrderBySymbol(firstSymbol).isLong() && zs > exitZScore) { return true; } } catch (PriceNotAvailableException e) { return false; } catch (NoOrderAvailable noOrderAvailable) { noOrderAvailable.printStackTrace(); return false; } return false; } }
9240b22e0add5eaf109f2f11f34a56baca8e3ca8
1,297
java
Java
src/main/java/net/alpenblock/bungeeperms/config/YamlRepresenter.java
spikeyrobot/BungeePerms
a53177973f1c0faf421480fe16acdcd02eeb10be
[ "MIT" ]
null
null
null
src/main/java/net/alpenblock/bungeeperms/config/YamlRepresenter.java
spikeyrobot/BungeePerms
a53177973f1c0faf421480fe16acdcd02eeb10be
[ "MIT" ]
null
null
null
src/main/java/net/alpenblock/bungeeperms/config/YamlRepresenter.java
spikeyrobot/BungeePerms
a53177973f1c0faf421480fe16acdcd02eeb10be
[ "MIT" ]
null
null
null
36.027778
133
0.730918
1,001,629
package net.alpenblock.bungeeperms.config; import java.util.LinkedHashMap; import java.util.Map; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.representer.Representer; public class YamlRepresenter extends Representer { public YamlRepresenter() { this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection()); this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); } private class RepresentConfigurationSection extends RepresentMap { @Override public Node representData(Object data) { return super.representData(((ConfigurationSection) data).getValues(false)); } } private class RepresentConfigurationSerializable extends RepresentMap { @Override public Node representData(Object data) { ConfigurationSerializable serializable = (ConfigurationSerializable) data; Map<String, Object> values = new LinkedHashMap<String, Object>(); values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass())); values.putAll(serializable.serialize()); return super.representData(values); } } }
9240b3c195987f07d68bdeaa875e77c82f64e1d8
3,243
java
Java
app/src/main/java/com/example/satellite/fragment/PicFragment.java
tulipper/Satellite
a2248ce9842f7f9e2d95fc4abb5047501d7402ab
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/satellite/fragment/PicFragment.java
tulipper/Satellite
a2248ce9842f7f9e2d95fc4abb5047501d7402ab
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/satellite/fragment/PicFragment.java
tulipper/Satellite
a2248ce9842f7f9e2d95fc4abb5047501d7402ab
[ "Apache-2.0" ]
null
null
null
39.072289
133
0.651866
1,001,630
package com.example.satellite.fragment; import android.media.Image; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.widget.ZoomControls; import com.bumptech.glide.Glide; import com.example.satellite.R; import org.w3c.dom.Text; /** * Created by Administrator on 2018/4/25. */ public class PicFragment extends Fragment { private View view; private ImageView imageView; private ZoomControls zoomControls; private ImageView backImage; private TextView titleText; private String rootUrl; private String title; private int maxLeval; private int minLeval = 1; private int currentLevel = 1; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.pic_fragment, container, false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); imageView = (ImageView) view.findViewById(R.id.image); backImage = (ImageView) view.findViewById(R.id.back_image); zoomControls = (ZoomControls) view.findViewById(R.id.zoomcontrol); titleText = (TextView) view.findViewById(R.id.title_text); Bundle bundle = getArguments(); rootUrl = bundle.getString("url", ""); title = bundle.getString("city", "") + "遥感图像"; //设置ImageView的初始显示图像 Glide.with(this).load(rootUrl + currentLevel + ".jpg").placeholder(R.drawable.loading).into(imageView); zoomControls.setOnZoomInClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentLevel == maxLeval) { zoomControls.setIsZoomInEnabled(false); Toast.makeText(getContext(), "已到最大级别", Toast.LENGTH_SHORT).show(); return; } zoomControls.setIsZoomOutEnabled(true); currentLevel ++; Glide.with(PicFragment.this).load(rootUrl + currentLevel + ".jpg").placeholder(R.drawable.loading).into(imageView); } }); zoomControls.setOnZoomOutClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentLevel == minLeval) { zoomControls.setIsZoomOutEnabled(false); Toast.makeText(getContext(), "已是最小缩放级别", Toast.LENGTH_SHORT).show(); return; } zoomControls.setIsZoomInEnabled(true); //Glide.with(PicFragment.this).load(rootUrl + currentLevel + ".jpg").placeholder(R.drawable.loading).into(imageView); currentLevel --; Glide.with(PicFragment.this).load(rootUrl + currentLevel + ".jpg").placeholder(R.drawable.loading).into(imageView); } }); } }
9240b4375d7d6cc5c44f40634cc0bc1c1af50d67
1,089
java
Java
src/main/java/pro/fessional/mirana/data/CodeEnum.java
trydofor/pro.fessional.mirana
e6fcc34d879499f94a4498359b53239bbfbef01b
[ "Apache-2.0" ]
4
2019-07-03T13:31:58.000Z
2022-03-01T07:16:04.000Z
src/main/java/pro/fessional/mirana/data/CodeEnum.java
trydofor/pro.fessional.mirana
e6fcc34d879499f94a4498359b53239bbfbef01b
[ "Apache-2.0" ]
1
2020-11-24T11:30:40.000Z
2020-11-24T11:30:40.000Z
src/main/java/pro/fessional/mirana/data/CodeEnum.java
trydofor/pro.fessional.mirana
e6fcc34d879499f94a4498359b53239bbfbef01b
[ "Apache-2.0" ]
2
2019-07-04T02:41:25.000Z
2021-11-18T03:01:20.000Z
17.564516
62
0.59045
1,001,631
package pro.fessional.mirana.data; import org.jetbrains.annotations.NotNull; import pro.fessional.mirana.i18n.I18nString; import java.io.Serializable; /** * code 一般为业务code,也可以作为i18nCode * * @author trydofor * @since 2019-09-17 */ public interface CodeEnum extends Serializable { /** * 业务code * * @return 业务code */ @NotNull String getCode(); /** * 默认消息或模板 * * @return 消息 */ @NotNull String getHint(); /** * 获得多国语有关的code,默认使用getCode * * @return i18nCode */ @NotNull default String getI18nCode() { return getCode(); } /** * 用i18nCode和message生成默认的i18nString * * @return I18nString */ @NotNull default I18nString toI18nString() { return new I18nString(getI18nCode(), getHint()); } /** * 用i18nCode和message生成默认的i18nString * * @param args 参数 * @return I18nString */ @NotNull default I18nString toI18nString(Object... args) { return new I18nString(getI18nCode(), getHint(), args); } }
9240b66fbfc292829ddb8c243339a39cd7764084
856
java
Java
chartMgrServer/chart-api/src/main/java/com/chart/api/charting/ChartBookControllerApi.java
visualization-project/visualization
3c8ef9aabcb3da8e7f3fa554f4d6ca4c899588d1
[ "Apache-2.0" ]
null
null
null
chartMgrServer/chart-api/src/main/java/com/chart/api/charting/ChartBookControllerApi.java
visualization-project/visualization
3c8ef9aabcb3da8e7f3fa554f4d6ca4c899588d1
[ "Apache-2.0" ]
10
2021-03-10T02:28:40.000Z
2022-02-26T21:37:48.000Z
chartMgrServer/chart-api/src/main/java/com/chart/api/charting/ChartBookControllerApi.java
visualization-project/visualization
3c8ef9aabcb3da8e7f3fa554f4d6ca4c899588d1
[ "Apache-2.0" ]
null
null
null
25.939394
63
0.747664
1,001,632
package com.chart.api.charting; import com.chart.domain.charting.ChartBook; import com.chart.domain.charting.ChartInstance; import com.chart.framework.model.response.ResponseResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import java.util.List; /** * @Author: Caiqin * @Date: 2019/12/21 17:26 */ @Api(value = "图册管理接口",description = "提供图册的增删改查") public interface ChartBookControllerApi { @ApiOperation( "查询图册" ) public ResponseResult findAll(); @ApiOperation( "添加图册" ) public ResponseResult addChartBook(ChartBook chartBook); @ApiOperation( "根据图册ID查询图册,图表" ) public ResponseResult findChartBook(String id); @ApiOperation( "修改图册" ) public ResponseResult updateChartBook(ChartBook chartBook); @ApiOperation( "删除图册" ) public ResponseResult deleteChartBook(String id); }
9240b6c84292e03c45d05d468982648d390b87af
4,927
java
Java
app/src/main/java/gr/invision/gpstracker/build/Constructor.java
nimakos/GpsTracker
81c15f2c1b4c89ef5fcf7dd979a61cd76f5ead76
[ "Apache-2.0" ]
3
2019-06-27T18:56:45.000Z
2020-02-02T21:22:24.000Z
app/src/main/java/gr/invision/gpstracker/build/Constructor.java
nimakos/GpsTracker
81c15f2c1b4c89ef5fcf7dd979a61cd76f5ead76
[ "Apache-2.0" ]
null
null
null
app/src/main/java/gr/invision/gpstracker/build/Constructor.java
nimakos/GpsTracker
81c15f2c1b4c89ef5fcf7dd979a61cd76f5ead76
[ "Apache-2.0" ]
null
null
null
32.629139
131
0.668764
1,001,633
package gr.invision.gpstracker.build; import android.os.Environment; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.converters.basic.BooleanConverter; import com.thoughtworks.xstream.converters.basic.DateConverter; import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import gr.invision.gpstracker.BuildConfig; public class Constructor { private static final String DATE_FMT = "yyyy-MM-dd'T'HH:mm:ss"; private final static String ROOT = Environment.getExternalStorageDirectory().getPath() + "/Android/data/!gr.invision.iservice"; private final static String DATAFILES = ROOT + "/DataFiles"; private final static String DATAFILES_OUT = DATAFILES + "/Out"; /** * Main builder function constructs the request data for the request * with given command id and any pod object for its additional data * * @param commandId command id * @param functionData The function data object * @param <T> generic object * @return String */ public <T> String createRequestData(int commandId, T functionData) { return constructRequestData(commandId, functionData); } private <T> String constructRequestData(int commandId, T functionData) { AppRequestData appRequestData = new AppRequestData(); appRequestData.appName = ""; appRequestData.appVersion = BuildConfig.VERSION_NAME; appRequestData.deviceID = ""; appRequestData.IPv4 = ""; appRequestData.IPv6 = ""; appRequestData.messageID = 0L; appRequestData.messageSubmitDate = new Date(); appRequestData.actualData = constructInputData(commandId, functionData); return serializeFromObjectToString(appRequestData); } private <T> String constructInputData(int commandId, T functionData) { InputData inputData = new InputData(); inputData.commandData.uiLanguage = ""; inputData.commandData.deviceId = ""; inputData.commandData.userId = 0; inputData.commandData.shiftId = 0; inputData.commandData.shiftDate = new Date(); inputData.commandData.subEntityId = 0; inputData.commandData.messageSubmitDate = new Date(); inputData.commandData.messageId = 0L; inputData.commandData.messageAppName = ""; inputData.commandData.uiAppVersion = "" + BuildConfig.VERSION_NAME; inputData.commandData.serviceAppVersion = ""; inputData.commandData.gpsLong = 0L; inputData.commandData.gpsLat = 0L; inputData.commandData.commandId = commandId; inputData.functionData.functionParams = constructFunctionData(functionData); return serializeFromObjectToString(inputData); } /** * Serializes the request file rf to String * * @param rf request file * @return xml string */ private <T> String constructFunctionData(T rf) { XStream xstream = new XStream(); xstream.autodetectAnnotations(true); xstream.registerConverter(new DateConverter(DATE_FMT, null)); return xstream.toXML(rf); } /** * Generic method to auto serialize an object * * @param object The object to be serializable * @param <T> Generic object * @return The string value from the serialization */ private <T> String serializeFromObjectToString(T object) { XStream xstream = new XStream(); xstream.autodetectAnnotations(true); xstream.registerConverter(new DateConverter(DATE_FMT, null)); xstream.registerConverter((SingleValueConverter) new EncodedByteArrayConverter()); xstream.registerConverter(new BooleanConverter("1", "0", false)); xstream.ignoreUnknownElements(); return xstream.toXML(object); } /** * Utility to write bytes to file * * @param path path * @param filename filename * @param data an array of bytes */ public void writeFile(String path, String filename, byte[] data) { try { File f = new File(path, filename); OutputStream out; out = new BufferedOutputStream(new FileOutputStream(f)); out.write(data); out.close(); } catch (IOException ignore) { } } /** * Create data files out folder */ public static void createDatafilesOut() { File f; f = new File(DATAFILES_OUT); if (!f.exists()) f.mkdirs(); } /** * Get data files out folder * * @return path */ public String getDatafilesOut() { return DATAFILES_OUT; } }
9240b6d3b5c8e36b2bb9e4576651b204b042d051
4,207
java
Java
chrome/browser/webauthn/android/java/src/org/chromium/chrome/browser/webauthn/CableAuthenticatorModuleProvider.java
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/webauthn/android/java/src/org/chromium/chrome/browser/webauthn/CableAuthenticatorModuleProvider.java
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/webauthn/android/java/src/org/chromium/chrome/browser/webauthn/CableAuthenticatorModuleProvider.java
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
39.688679
100
0.687426
1,001,634
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.webauthn; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.modules.cablev2_authenticator.Cablev2AuthenticatorModule; /** * Provides a UI that attempts to install the caBLEv2 Authenticator module. If already installed, or * successfully installed, it replaces itself in the back-stack with the authenticator UI. * * This code lives in the base module, i.e. is _not_ part of the dynamically-loaded module. * * This does not use {@link ModuleInstallUi} because it needs to integrate into the Fragment-based * settings UI, while {@link ModuleInstallUi} assumes that the UI does in a {@link Tab}. */ public class CableAuthenticatorModuleProvider extends Fragment { // NETWORK_CONTEXT_KEY is the key under which a pointer to a NetworkContext // is passed (as a long) in the arguments {@link Bundle} to the {@link // Fragment} in the module. private static final String NETWORK_CONTEXT_KEY = "org.chromium.chrome.modules.cablev2_authenticator.NetworkContext"; private TextView mStatus; @Override @SuppressLint("SetTextI18n") public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final Context context = getContext(); // This UI is a placeholder for development, has not been reviewed by // UX, and thus just uses untranslated strings for now. getActivity().setTitle("Installing"); mStatus = new TextView(context); mStatus.setPadding(0, 60, 0, 60); LinearLayout layout = new LinearLayout(context); layout.setOrientation(LinearLayout.VERTICAL); layout.setGravity(Gravity.CENTER_HORIZONTAL); layout.addView(mStatus, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); if (Cablev2AuthenticatorModule.isInstalled()) { showModule(); } else { mStatus.setText("Installing security key functionality…"); Cablev2AuthenticatorModule.install((success) -> { if (!success) { mStatus.setText("Failed to install."); return; } showModule(); }); } return layout; } @SuppressLint("SetTextI18n") private void showModule() { mStatus.setText("Installed."); FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction(); Fragment fragment = Cablev2AuthenticatorModule.getImpl().getFragment(); Bundle arguments = getArguments(); if (arguments == null) { arguments = new Bundle(); } arguments.putLong(NETWORK_CONTEXT_KEY, CableAuthenticatorModuleProviderJni.get().getSystemNetworkContext()); fragment.setArguments(arguments); transaction.replace(getId(), fragment); // This fragment is deliberately not added to the back-stack here so // that it appears to have been "replaced" by the authenticator UI. transaction.commit(); } @NativeMethods interface Natives { // getSystemNetworkContext returns a pointer, encoded in a long, to the // global NetworkContext for system services that hangs off // |g_browser|. This is needed because //chrome/browser, being a // static_library, cannot be depended on by another component thus we // pass this value into the feature module. long getSystemNetworkContext(); } }
9240b6e0d88548a5215ca711d3e8e5fcc705186d
2,001
java
Java
src/main/java/seedu/address/logic/parser/DeleteFilterCommandParser.java
CS2103-AY1819S2-W15-3/main
075139feff453db31f5f13b18a484e08dda636f5
[ "MIT" ]
null
null
null
src/main/java/seedu/address/logic/parser/DeleteFilterCommandParser.java
CS2103-AY1819S2-W15-3/main
075139feff453db31f5f13b18a484e08dda636f5
[ "MIT" ]
153
2019-02-12T11:27:48.000Z
2019-04-15T15:52:58.000Z
src/main/java/seedu/address/logic/parser/DeleteFilterCommandParser.java
CS2103-AY1819S2-W15-3/main
075139feff453db31f5f13b18a484e08dda636f5
[ "MIT" ]
10
2019-02-08T18:14:31.000Z
2019-04-04T14:51:07.000Z
43.5
93
0.738131
1,001,635
package seedu.address.logic.parser; import static seedu.address.logic.commands.DeleteFilterCommand.MESSAGE_LACK_FILTERNAME; import static seedu.address.logic.commands.DeleteFilterCommand.MESSAGE_USAGE_ALLJOB_SCREEN; import static seedu.address.logic.commands.DeleteFilterCommand.MESSAGE_USAGE_DETAIL_SCREEN; import static seedu.address.logic.parser.CliSyntax.PREFIX_FILTERNAME; import seedu.address.logic.commands.DeleteFilterCommand; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.job.JobListName; /** * Parses input arguments and creates a new DeleteFilterCommand object */ public class DeleteFilterCommandParser implements Parser<DeleteFilterCommand> { /** * Parses the given {@code String} of arguments in the context of the DeleteFilterCommand * and returns an DeleteFilterCommand object for execution. * * @throws ParseException if the user input does not conform the expected format */ public DeleteFilterCommand parse(String args) throws ParseException { ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_FILTERNAME); JobListName listName; String commandName; if (argMultimap.getValue(PREFIX_FILTERNAME).isPresent()) { commandName = argMultimap.getValue(PREFIX_FILTERNAME).get().trim(); } else { throw new ParseException(String.format(MESSAGE_LACK_FILTERNAME, MESSAGE_USAGE_ALLJOB_SCREEN + MESSAGE_USAGE_DETAIL_SCREEN)); } String preambleString = argMultimap.getPreamble(); String listNameString = preambleString.trim(); try { listName = ParserUtil.parseJobListName(listNameString); return new DeleteFilterCommand(listName, commandName); } catch (ParseException pe) { throw new ParseException(String.format(pe.getMessage(), MESSAGE_USAGE_ALLJOB_SCREEN + MESSAGE_USAGE_DETAIL_SCREEN), pe); } } }
9240b74401b3e54f973089f3c48236757b7aa61b
492
java
Java
SpringWEB/SpringSecurity/LiveSessions/BootCamp/src/main/java/com/example/bootcamp/BootcampApplication.java
anupamdev/Spring
3236bce601779f65809ead080621cff9c743ea7f
[ "Apache-2.0" ]
25
2020-08-24T20:07:37.000Z
2022-03-04T20:13:20.000Z
SpringWEB/SpringSecurity/LiveSessions/BootCamp/src/main/java/com/example/bootcamp/BootcampApplication.java
anupamdev/Spring
3236bce601779f65809ead080621cff9c743ea7f
[ "Apache-2.0" ]
20
2021-05-18T19:45:12.000Z
2022-03-24T06:25:40.000Z
SpringWEB/SpringSecurity/LiveSessions/BootCamp/src/main/java/com/example/bootcamp/BootcampApplication.java
anupamdev/Spring
3236bce601779f65809ead080621cff9c743ea7f
[ "Apache-2.0" ]
19
2020-09-07T10:01:20.000Z
2022-03-05T11:34:45.000Z
23.428571
68
0.813008
1,001,636
package com.example.bootcamp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class BootcampApplication { @Bean RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(BootcampApplication.class, args); } }
9240b8d05907b8c962591b23b82522e8c4eb38e7
152
java
Java
System/src/systemain/CommandListener.java
VJsong02/System
51d94329565a8fffbe5d9aa611cd88510c7996dc
[ "Unlicense" ]
null
null
null
System/src/systemain/CommandListener.java
VJsong02/System
51d94329565a8fffbe5d9aa611cd88510c7996dc
[ "Unlicense" ]
null
null
null
System/src/systemain/CommandListener.java
VJsong02/System
51d94329565a8fffbe5d9aa611cd88510c7996dc
[ "Unlicense" ]
null
null
null
16.888889
68
0.776316
1,001,637
package systemain; import java.util.ArrayList; public class CommandListener { public static ArrayList<String> commands = new ArrayList<String>(); }
9240b9ebce298e7dfce23766e94b88ab61d6c040
2,000
java
Java
library/baselibrary/src/main/java/com/sxu/baselibrary/commonutils/DisplayUtil.java
Liberuman/SimpleProject
cf5ba0030136baf40238d1860930893192fc1123
[ "MIT" ]
33
2019-03-16T04:20:37.000Z
2021-06-28T06:25:29.000Z
library/baselibrary/src/main/java/com/sxu/baselibrary/commonutils/DisplayUtil.java
JuHonggang/SimpleProject
cf5ba0030136baf40238d1860930893192fc1123
[ "MIT" ]
1
2018-08-23T02:31:32.000Z
2018-08-24T07:27:23.000Z
library/baselibrary/src/main/java/com/sxu/baselibrary/commonutils/DisplayUtil.java
Liberuman/SimpleProject
cf5ba0030136baf40238d1860930893192fc1123
[ "MIT" ]
13
2019-04-08T05:49:55.000Z
2021-04-13T06:27:43.000Z
19.607843
89
0.6135
1,001,638
package com.sxu.baselibrary.commonutils; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Rect; /******************************************************************************* * Description: 获取屏幕信息 * * Author: Freeman * * Date: 2017/06/20 * * Copyright: all rights reserved by Freeman. *******************************************************************************/ public class DisplayUtil { private DisplayUtil() { } /** * 获取屏幕宽度 * @return */ public static int getScreenWidth() { return Resources.getSystem().getDisplayMetrics().widthPixels; } /** * 获取屏幕高度 * @return */ public static int getScreenHeight() { return Resources.getSystem().getDisplayMetrics().heightPixels; } /** * 获取屏幕物理像素密度 * @return */ public static float getScreenDensity() { return Resources.getSystem().getDisplayMetrics().density; } /** * dp转px * @param dp * @return */ public static int dpToPx(int dp) { return Math.round(Resources.getSystem().getDisplayMetrics().density * dp + 0.5f); } /** * sp转px * @param sp * @return */ public static int spToPx(int sp) { return Math.round(Resources.getSystem().getDisplayMetrics().scaledDensity * sp + 0.5f); } /** * px转dp * @param px * @return */ public static int pxToDp(int px) { return Math.round(px / Resources.getSystem().getDisplayMetrics().density + 0.5f); } /** * px转sp * @param px * @return */ public static int pxToSp(int px) { return Math.round(px / Resources.getSystem().getDisplayMetrics().scaledDensity + 0.5f); } /** * 获取状态栏的高度 * @param context * @return */ public static int getStatusHeight(Context context) { Rect rect = new Rect(); ((Activity)context).getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); return rect.top; } /** * 获取屏幕参数 * @return */ public static String getScreenParams() { return getScreenWidth() + "*" + getScreenHeight(); } }
9240ba753e791adadfb7652a345cd162163a082b
8,803
java
Java
examples/examples-simulated/src/main/java/com/opengamma/examples/simulated/generator/SwaptionPortfolioGeneratorTool.java
McLeodMoores/starling
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
[ "Apache-2.0" ]
3
2017-12-18T09:32:40.000Z
2021-03-08T20:05:54.000Z
examples/examples-simulated/src/main/java/com/opengamma/examples/simulated/generator/SwaptionPortfolioGeneratorTool.java
McLeodMoores/starling
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
[ "Apache-2.0" ]
10
2017-01-19T13:32:36.000Z
2021-09-20T20:41:48.000Z
examples/examples-simulated/src/main/java/com/opengamma/examples/simulated/generator/SwaptionPortfolioGeneratorTool.java
McLeodMoores/starling
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
[ "Apache-2.0" ]
3
2017-12-14T12:46:18.000Z
2020-12-11T19:52:37.000Z
52.39881
152
0.758378
1,001,639
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.examples.simulated.generator; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.threeten.bp.ZoneOffset; import org.threeten.bp.ZonedDateTime; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.financial.convention.businessday.BusinessDayConvention; import com.opengamma.financial.convention.businessday.BusinessDayConventions; import com.opengamma.financial.convention.daycount.DayCount; import com.opengamma.financial.convention.daycount.DayCounts; import com.opengamma.financial.convention.frequency.Frequency; import com.opengamma.financial.convention.frequency.PeriodFrequency; import com.opengamma.financial.generator.AbstractPortfolioGeneratorTool; import com.opengamma.financial.generator.LeafPortfolioNodeGenerator; import com.opengamma.financial.generator.NameGenerator; import com.opengamma.financial.generator.PortfolioGenerator; import com.opengamma.financial.generator.PortfolioNodeGenerator; import com.opengamma.financial.generator.PositionGenerator; import com.opengamma.financial.generator.SecurityGenerator; import com.opengamma.financial.generator.SimplePositionGenerator; import com.opengamma.financial.generator.StaticNameGenerator; import com.opengamma.financial.security.option.SwaptionSecurity; import com.opengamma.financial.security.swap.FixedInterestRateLeg; import com.opengamma.financial.security.swap.FloatingInterestRateLeg; import com.opengamma.financial.security.swap.FloatingRateType; import com.opengamma.financial.security.swap.InterestRateNotional; import com.opengamma.financial.security.swap.SwapLeg; import com.opengamma.financial.security.swap.SwapSecurity; import com.opengamma.id.ExternalId; import com.opengamma.master.security.SecurityDocument; import com.opengamma.master.security.SecurityMaster; import com.opengamma.util.money.Currency; import com.opengamma.util.time.DateUtils; import com.opengamma.util.time.Expiry; /** * Generates a portfolio of multi-currency swaptions. */ public class SwaptionPortfolioGeneratorTool extends AbstractPortfolioGeneratorTool { /** The strike formatter */ private static final DecimalFormat STRIKE_FORMATTER = new DecimalFormat("#.####"); /** The day count */ private static final DayCount DAY_COUNT = DayCounts.ACT_360; /** The business day convention */ private static final BusinessDayConvention BDC = BusinessDayConventions.FOLLOWING; /** Map of currency to region */ private static final Map<Currency, ExternalId> REGIONS = new HashMap<>(); /** Map of currency to synthetic ibor tickers */ private static final Map<Currency, ExternalId> TICKERS = new HashMap<>(); static { REGIONS.put(Currency.USD, ExternalSchemes.financialRegionId("US")); REGIONS.put(Currency.EUR, ExternalSchemes.financialRegionId("EU")); REGIONS.put(Currency.GBP, ExternalSchemes.financialRegionId("GB")); REGIONS.put(Currency.JPY, ExternalSchemes.financialRegionId("JP")); REGIONS.put(Currency.CHF, ExternalSchemes.financialRegionId("CH")); TICKERS.put(Currency.USD, ExternalSchemes.syntheticSecurityId("USDLIBORP3M")); TICKERS.put(Currency.EUR, ExternalSchemes.syntheticSecurityId("EUREURIBORP6M")); TICKERS.put(Currency.GBP, ExternalSchemes.syntheticSecurityId("GBPLIBORP6M")); TICKERS.put(Currency.JPY, ExternalSchemes.syntheticSecurityId("JPYLIBORP6M")); TICKERS.put(Currency.CHF, ExternalSchemes.syntheticSecurityId("CHFLIBORP6M")); } @Override public PortfolioGenerator createPortfolioGenerator(final NameGenerator portfolioNameGenerator) { final SwaptionSecurity[] swaptions = createSwaptions(PORTFOLIO_SIZE); final SecurityGenerator<SwaptionSecurity> securities = createSwaptionSecurityGenerator(swaptions, PORTFOLIO_SIZE); configure(securities); final PositionGenerator positions = new SimplePositionGenerator<>(securities, getSecurityPersister(), getCounterPartyGenerator()); final PortfolioNodeGenerator rootNode = new LeafPortfolioNodeGenerator(new StaticNameGenerator("Swaptions"), positions, PORTFOLIO_SIZE); return new PortfolioGenerator(rootNode, portfolioNameGenerator); } @Override public PortfolioNodeGenerator createPortfolioNodeGenerator(final int size) { final SwaptionSecurity[] swaptions = createSwaptions(size); final SecurityGenerator<SwaptionSecurity> securities = createSwaptionSecurityGenerator(swaptions, size); configure(securities); final PositionGenerator positions = new SimplePositionGenerator<>(securities, getSecurityPersister(), getCounterPartyGenerator()); return new LeafPortfolioNodeGenerator(new StaticNameGenerator("Swaptions"), positions, size); } private SwaptionSecurity[] createSwaptions(final int size) { final SecurityMaster securityMaster = getToolContext().getSecurityMaster(); final List<Currency> currencies = new ArrayList<>(REGIONS.keySet()); final ZonedDateTime[] tradeDates = new ZonedDateTime[size]; final Random rng = new Random(123); final ZonedDateTime date = DateUtils.previousWeekDay().atStartOfDay(ZoneOffset.UTC); Arrays.fill(tradeDates, date); final SwaptionSecurity[] swaptions = new SwaptionSecurity[size]; for (int i = 0; i < size; i++) { final Currency currency = currencies.get(rng.nextInt(currencies.size())); final ExternalId region = REGIONS.get(currency); final ExternalId floatingRate = TICKERS.get(currency); final int swaptionYears = 1 + rng.nextInt(9); final ZonedDateTime swaptionExpiry = date.plusYears(swaptionYears); final int swapYears = 1 + rng.nextInt(28); final ZonedDateTime swapMaturity = swaptionExpiry.plusMonths(swapYears); final double amount = 100000 * (1 + rng.nextInt(30)); final InterestRateNotional notional = new InterestRateNotional(currency, amount); final double rate = swapYears * rng.nextDouble() / 500; final Frequency frequency = currency.equals(Currency.USD) ? PeriodFrequency.QUARTERLY : PeriodFrequency.SEMI_ANNUAL; final SwapLeg fixedLeg = new FixedInterestRateLeg(DAY_COUNT, PeriodFrequency.SEMI_ANNUAL, region, BDC, notional, false, rate); final SwapLeg floatLeg = new FloatingInterestRateLeg(DAY_COUNT, frequency, region, BDC, notional, false, floatingRate, FloatingRateType.IBOR); final SwapLeg payLeg, receiveLeg; final String swapName, swaptionName; final boolean isLong = rng.nextBoolean(); final boolean isCashSettled = rng.nextBoolean(); final boolean payer; if (rng.nextBoolean()) { payLeg = fixedLeg; receiveLeg = floatLeg; swapName = swapYears + "Y pay " + currency + " " + notional.getAmount() + " @ " + STRIKE_FORMATTER.format(rate); swaptionName = (isLong ? "Long " : "Short ") + swaptionYears + "Y x " + swapYears + "Y pay " + currency + " " + notional.getAmount() + " @ " + STRIKE_FORMATTER.format(rate); payer = true; } else { payLeg = floatLeg; receiveLeg = fixedLeg; swapName = swapYears + "Y receive " + currency + " " + notional.getAmount() + " @ " + STRIKE_FORMATTER.format(rate); swaptionName = (isLong ? "Long " : "Short ") + swaptionYears + "Y x " + swapYears + "Y receive " + currency + " " + notional.getAmount() + " @ " + STRIKE_FORMATTER.format(rate); payer = false; } final SwapSecurity swap = new SwapSecurity(swaptionExpiry, swaptionExpiry.plusDays(2), swapMaturity, COUNTER_PARTY_OPT, payLeg, receiveLeg); swap.setName(swapName); final SecurityDocument toAddDoc = new SecurityDocument(); toAddDoc.setSecurity(swap); securityMaster.add(toAddDoc); final ExternalId swapId = getSecurityPersister().storeSecurity(swap).iterator().next(); final SwaptionSecurity swaption = new SwaptionSecurity(payer, swapId, isLong, new Expiry(swaptionExpiry), isCashSettled, currency); swaption.setName(swaptionName); swaptions[i] = swaption; } return swaptions; } private SecurityGenerator<SwaptionSecurity> createSwaptionSecurityGenerator(final SwaptionSecurity[] swaptions, final int size) { final SecurityGenerator<SwaptionSecurity> securities = new SecurityGenerator<SwaptionSecurity>() { private int _count; @Override public SwaptionSecurity createSecurity() { if (_count > size - 1) { throw new IllegalStateException("Should not ask for more than " + size + " securities"); } return swaptions[_count++]; } }; configure(securities); return securities; } }
9240ba764f453222f75a365dccaa31bfa8c4dc45
3,684
java
Java
server/src/main/java/com/game/server/userservice/UserObject.java
actumn/Tilemap_MMORPG2
7ef013bb15ece66f4bd8b0184586dc6631c651f8
[ "MIT" ]
null
null
null
server/src/main/java/com/game/server/userservice/UserObject.java
actumn/Tilemap_MMORPG2
7ef013bb15ece66f4bd8b0184586dc6631c651f8
[ "MIT" ]
2
2018-07-15T06:07:27.000Z
2018-07-15T06:07:32.000Z
server/src/main/java/com/game/server/userservice/UserObject.java
actumn/gdx-tilemap-rpg
7ef013bb15ece66f4bd8b0184586dc6631c651f8
[ "MIT" ]
null
null
null
22.192771
94
0.612106
1,001,640
package com.game.server.userservice; import com.game.server.Server; import com.game.server.db.DBManager; import io.netty.channel.Channel; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import protocol.Packet.JsonPacketFactory; import protocol.Packet.PacketFactory; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by Lee on 2016-06-01. */ public class UserObject { private Channel channel; private int dbid; private long uuid; private MapProxy map; private long mapId; private int level; private int currentExp; private int maxExp; private int jobId; private String name; private int x,y; private Inventory inventory; private PacketFactory packetFactory; public UserObject(PacketFactory packetFactory) { this.inventory = new Inventory(); this.uuid = Server.uniqueId+=1; this.packetFactory = packetFactory; } public UserObject dbid(int dbid) { this.dbid = dbid; return this; } public UserObject channel(Channel channel) { this.channel = channel; return this; } public UserObject name(String name) { this.name = name; return this; } public UserObject level(int level) { this.level = level; return this; } public UserObject currentExp(int currentExp) { this.currentExp = currentExp; return this; } public UserObject maxExp(int maxExp) { this.maxExp = maxExp; return this; } public UserObject jobId(int jobId) { this.jobId = jobId; return this; } public UserObject mapId(int mapId) { this.mapId = mapId; return this; } public UserObject XY(int x, int y) { this.x = x; this.y = y; return this; } public void initMap(MapProxy map) { this.map = map; this.map.joinUser(this); } public MapProxy getMap() { return map; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public long getUuid() { return uuid; } public int getDbid() { return dbid; } public Channel getChannel() { return channel; } public int getX() { return x; } public int getY() { return y; } public long getMapId() { return mapId; } public String getName() { return name; } public int getJobId() { return jobId; } public void setMap(MapProxy map) { this.map = map; this.mapId = map.getMap_id(); } public int getLevel() { return level; } public int getCurrentExp() { return currentExp; } public void addExp(JSONObject packet) { int exp = (int) packet.get("exp"); this.currentExp += exp; this.channel.writeAndFlush(packetFactory.updateExp(currentExp).toJSONString()+"\r\n"); if (currentExp >= maxExp) levelUp(); } private void levelUp() { if (currentExp < maxExp) return; this.currentExp -= maxExp; this.channel.writeAndFlush(packetFactory.updateExp(currentExp).toJSONString()+"\r\n"); this.level += 1; this.map.notifyLevelUp(uuid, level); this.maxExp = nextMaxExp(this.level); } private int nextMaxExp(int level) { return ExpTable.get(level); } }
9240bac639ccd2402da27b735487177eb9ed74c3
1,940
java
Java
src/main/java/de/geolykt/starloader/api/actor/wrapped/WrappingActor.java
Geolykt/Starloader-API
ee52b6fe04bf4844ea93f55a740295116900751f
[ "Apache-2.0" ]
2
2021-09-03T12:58:53.000Z
2022-02-24T20:35:10.000Z
src/main/java/de/geolykt/starloader/api/actor/wrapped/WrappingActor.java
Geolykt/Starloader-API
ee52b6fe04bf4844ea93f55a740295116900751f
[ "Apache-2.0" ]
null
null
null
src/main/java/de/geolykt/starloader/api/actor/wrapped/WrappingActor.java
Geolykt/Starloader-API
ee52b6fe04bf4844ea93f55a740295116900751f
[ "Apache-2.0" ]
null
null
null
40.416667
114
0.710825
1,001,641
package de.geolykt.starloader.api.actor.wrapped; import org.jetbrains.annotations.NotNull; import de.geolykt.starloader.api.actor.ActorSpec; /** * Implementation of an actor that calls callbacks to a pseudo-actor. * Note: while the the API does not initially suggest that this interface is a subclass * of an {@link ActorSpec}, the Implementation of this class should at least attempt to subclass * {@link ActorSpec}. Alternatively {@link #cast()} can be used for maximum safety. * * @param <T> The actor specification type that is wrapped by this actor. * @deprecated Actor wrapping is a feature scheduled for removal. */ @Deprecated(forRemoval = true, since = "1.5.0") public interface WrappingActor<T extends ActorSpec> { /** * Obtains the actor the wrapper is using to delegate to. * * @return The actor specification that is used as a delegate * @deprecated Actor wrapping is a feature scheduled for removal. */ @Deprecated(forRemoval = true, since = "1.5.0") public @NotNull T getWrappedSpec(); /** * Obtains the configuration that is valid for this actor. * This configuration should be honoured by the Implementation of this interface. * * @return The {@link WrappingConfiguration} assigned to this actor * @deprecated Actor wrapping is a feature scheduled for removal. */ @Deprecated(forRemoval = true, since = "1.5.0") public @NotNull WrappingConfiguration getConfiguration(); /** * Obtains the Actor Wrapper as an ActorSpec (workaround to a potential Structure flaw in the implementation). * This is usually a cast result, but it is safer to use for non-standard implementations. * * @return This wrapper represented as an {@link ActorSpec}. * @deprecated Actor wrapping is a feature scheduled for removal. */ @Deprecated(forRemoval = true, since = "1.5.0") public @NotNull ActorSpec cast(); }
9240bb8a5da2db26dd00fa1c50ddbcc5f6f19aba
6,996
java
Java
src/hl7v2_pidfeed/src/ca/uhn/hl7v2/app/MessageTypeRouter.java
kef/hieos
7d75d1465337293fc6b6832c4b52754b1fea4cc0
[ "ECL-2.0", "BSD-3-Clause-No-Nuclear-Warranty", "Apache-2.0" ]
4
2016-02-10T09:26:31.000Z
2021-11-27T10:56:53.000Z
src/hl7v2_pidfeed/src/ca/uhn/hl7v2/app/MessageTypeRouter.java
kef/hieos
7d75d1465337293fc6b6832c4b52754b1fea4cc0
[ "ECL-2.0", "BSD-3-Clause-No-Nuclear-Warranty", "Apache-2.0" ]
null
null
null
src/hl7v2_pidfeed/src/ca/uhn/hl7v2/app/MessageTypeRouter.java
kef/hieos
7d75d1465337293fc6b6832c4b52754b1fea4cc0
[ "ECL-2.0", "BSD-3-Clause-No-Nuclear-Warranty", "Apache-2.0" ]
12
2015-04-24T10:38:35.000Z
2020-05-19T21:14:53.000Z
42.658537
113
0.656947
1,001,642
/** The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is "Connection.java". Description: "A TCP/IP connection to a remote HL7 server." The Initial Developer of the Original Code is University Health Network. Copyright (C) 2002. All Rights Reserved. Contributor(s): ______________________________________. Alternatively, the contents of this file may be used under the terms of the GNU General Public License (the �GPL�), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL License. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. */ // HIEOS - Minor modifications to pass accepted socket to message handler. package ca.uhn.hl7v2.app; import java.util.HashMap; import ca.uhn.hl7v2.model.Message; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.util.Terser; import ca.uhn.log.HapiLog; import ca.uhn.log.HapiLogFactory; // +++++ HIEOS CHANGES BEGIN HERE +++++ import java.net.Socket; import com.vangent.hieos.services.xds.registry.transactions.hl7v2.HL7Application; // +++++ HIEOS CHANGES END HERE +++++ /** * Routes messages to various Applications based on message type and trigger event. * The router is told which Application to which to route various messages by calling * the method <code>registerApplication(...)</code>. * @author Bryan Tripp */ public class MessageTypeRouter implements Application { private static final HapiLog log = HapiLogFactory.getHapiLog(MessageTypeRouter.class); private HashMap apps; /** Creates a new instance of MessageTypeRouter */ public MessageTypeRouter() { apps = new HashMap(20); } /** * Returns true if at least one application has been registered to accept this * type of message. Applications are registered using <code>registerApplication(...)</code>. */ public boolean canProcess(Message in) { boolean can = false; try { Application matches = this.getMatchingApplication(in); if (matches != null) can = true; } catch (HL7Exception e) { can = false; } return can; } /** * Forwards the given message to any Applications that have been registered to * accept messages of that type and trigger event. * @throws ApplicationException if no such Applications are registered, or if * the underlying Application throws this exception during processing. */ public Message processMessage(Message in) throws ApplicationException { Message out; try { Application matchingApp = this.getMatchingApplication(in); out = matchingApp.processMessage(in); } catch (HL7Exception e) { throw new ApplicationException("Error internally routing message: " + e.toString(), e); } return out; } // +++++ HIEOS CHANGES BEGIN HERE +++++ public Message processMessage(Message in, Socket socket) throws ApplicationException { Message out; try { Application matchingApp = this.getMatchingApplication(in); if (matchingApp instanceof HL7Application) { out = ((HL7Application)matchingApp).processMessage(in, socket); } else { out = matchingApp.processMessage(in); } } catch (HL7Exception e) { throw new ApplicationException("Error internally routing message: " + e.toString(), e); } return out; } // +++++ HIEOS CHANGES END HERE +++++ /** * Registers the given application to handle messages corresponding to the given type * and trigger event. Only one application can be registered for a given message type * and trigger event combination. A repeated registration for a particular combination * of type and trigger event over-writes the previous one. Use "*" as a wildcard (e.g. * registerApplication("ADT", "*", myApp) would register your app for all ADT messages). */ public synchronized void registerApplication(String messageType, String triggerEvent, Application handler) { this.apps.put(getKey(messageType, triggerEvent), handler); //status message StringBuffer buf = new StringBuffer(); buf.append(handler.getClass().getName()); buf.append(" registered to handle "); buf.append(messageType); buf.append("^"); buf.append(triggerEvent); buf.append(" messages"); log.info(buf.toString()); } /** * Returns the Applications that has been registered to handle * messages of the type and trigger event of the given message, or null if * there are none. */ private Application getMatchingApplication(Message message) throws HL7Exception { Terser t = new Terser(message); String messageType = t.get("/MSH-9-1"); String triggerEvent = t.get("/MSH-9-2"); return this.getMatchingApplication(messageType, triggerEvent); } /** * Returns the Applications that has been registered to handle * messages of the given type and trigger event, or null if * there are none. If there is not an exact match, wildcards * ("*") are tried as well. */ private synchronized Application getMatchingApplication(String messageType, String triggerEvent) { Application matchingApp = null; Object o = this.apps.get(getKey(messageType, triggerEvent)); if (o == null) o = this.apps.get(getKey(messageType, "*")); if (o == null) o = this.apps.get(getKey("*", triggerEvent)); if (o == null) o = this.apps.get(getKey("*", "*")); if (o != null) matchingApp = (Application)o; return matchingApp; } /** * Creates reproducible hash key. */ private String getKey(String messageType, String triggerEvent) { //create hash key string by concatenating type and trigger event return messageType + "|" + triggerEvent; } }
9240bcf82e92d8c1e424c493604f13c06bf10b72
2,140
java
Java
docker-compose-rule-core/src/test/java/com/palantir/docker/compose/AggressiveShutdownStrategyTest.java
saavkaar/docker-compose-rule
27e485c2101bf5e1f4919c2a9b0741630b988c33
[ "Apache-2.0" ]
null
null
null
docker-compose-rule-core/src/test/java/com/palantir/docker/compose/AggressiveShutdownStrategyTest.java
saavkaar/docker-compose-rule
27e485c2101bf5e1f4919c2a9b0741630b988c33
[ "Apache-2.0" ]
null
null
null
docker-compose-rule-core/src/test/java/com/palantir/docker/compose/AggressiveShutdownStrategyTest.java
saavkaar/docker-compose-rule
27e485c2101bf5e1f4919c2a9b0741630b988c33
[ "Apache-2.0" ]
1
2021-02-13T10:34:13.000Z
2021-02-13T10:34:13.000Z
36.896552
109
0.73785
1,001,643
/* * Copyright 2016 Palantir Technologies, Inc. All rights reserved. */ package com.palantir.docker.compose; import static org.mockito.Matchers.anyListOf; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.palantir.docker.compose.configuration.ShutdownStrategy; import com.palantir.docker.compose.execution.Docker; import com.palantir.docker.compose.execution.DockerCompose; import com.palantir.docker.compose.execution.DockerExecutionException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class AggressiveShutdownStrategyTest { @Rule public final ExpectedException exception = ExpectedException.none(); private final DockerCompose mockDockerCompose = mock(DockerCompose.class); private final Docker mockDocker = mock(Docker.class); private static final String btrfs_message = "'docker rm -f test-1.container.name test-2.container.name' " + "returned exit code 1\nThe output was:\nFailed to remove container (test-1.container.name): " + "Error response from daemon: Driver btrfs failed to remove root filesystem "; @Test public void first_btrfs_error_should_be_caught_silently_and_retried() throws Exception { doThrow(new DockerExecutionException(btrfs_message)) .doNothing() .when(mockDocker) .rm(anyListOf(String.class)); ShutdownStrategy.AGGRESSIVE.shutdown(mockDockerCompose, mockDocker); verify(mockDocker, times(2)).rm(anyListOf(String.class)); } @Test public void after_two_btrfs_failures_we_should_just_log_and_continue() throws Exception { doThrow(new DockerExecutionException(btrfs_message)) .doThrow(new DockerExecutionException(btrfs_message)) .when(mockDocker) .rm(anyListOf(String.class)); ShutdownStrategy.AGGRESSIVE.shutdown(mockDockerCompose, mockDocker); verify(mockDocker, times(2)).rm(anyListOf(String.class)); } }
9240bd154e9ffccdc45107145980261548b1e29e
907
java
Java
hsven-db/hsven-db-dataloader/src/main/java/org/framework/hsven/dataloader/related/dependency/SimpleLazyChildTableGroup.java
hubeixiang/hsven-framework
e5162ce9d19fb03bed188aad8d7116ac603e0afd
[ "Apache-2.0" ]
null
null
null
hsven-db/hsven-db-dataloader/src/main/java/org/framework/hsven/dataloader/related/dependency/SimpleLazyChildTableGroup.java
hubeixiang/hsven-framework
e5162ce9d19fb03bed188aad8d7116ac603e0afd
[ "Apache-2.0" ]
null
null
null
hsven-db/hsven-db-dataloader/src/main/java/org/framework/hsven/dataloader/related/dependency/SimpleLazyChildTableGroup.java
hubeixiang/hsven-framework
e5162ce9d19fb03bed188aad8d7116ac603e0afd
[ "Apache-2.0" ]
null
null
null
37.791667
108
0.796031
1,001,644
package org.framework.hsven.dataloader.related.dependency; import org.framework.hsven.dataloader.beans.loader.DefineRelatedFields; import org.framework.hsven.dataloader.beans.loader.LazyRelatedFieldsAndRowIndexGroup; public class SimpleLazyChildTableGroup extends ChildTableGroup { private final LazyRelatedFieldsAndRowIndexGroup lazyRelatedFieldsAndRowIndexGroup; public SimpleLazyChildTableGroup(DefineRelatedFields defineRelatedFields) { super(defineRelatedFields); this.lazyRelatedFieldsAndRowIndexGroup = new LazyRelatedFieldsAndRowIndexGroup(defineRelatedFields); } public LazyRelatedFieldsAndRowIndexGroup getLazyRelatedFieldsAndRowIndexGroup() { return lazyRelatedFieldsAndRowIndexGroup; } public void destory() { if (lazyRelatedFieldsAndRowIndexGroup != null) { lazyRelatedFieldsAndRowIndexGroup.destory(); } } }
9240bd4f65c2cccc16fe7c7265030a811b369654
922
java
Java
app/src/main/java/com/nicolaslagamma/gammagram/Post.java
LaGamma/GammaGram
bc4e4df0b1a78cd60506a68fade33273138457eb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/nicolaslagamma/gammagram/Post.java
LaGamma/GammaGram
bc4e4df0b1a78cd60506a68fade33273138457eb
[ "Apache-2.0" ]
1
2020-10-24T08:09:10.000Z
2020-10-31T11:12:41.000Z
app/src/main/java/com/nicolaslagamma/gammagram/Post.java
LaGamma/GammaGram
bc4e4df0b1a78cd60506a68fade33273138457eb
[ "Apache-2.0" ]
null
null
null
23.641026
63
0.691974
1,001,645
package com.nicolaslagamma.gammagram; import com.parse.ParseClassName; import com.parse.ParseFile; import com.parse.ParseObject; import com.parse.ParseUser; import java.util.Date; @ParseClassName("Post") public class Post extends ParseObject { public static final String KEY_DESCRIPTION = "description"; public static final String KEY_IMAGE = "image"; public static final String KEY_USER = "user"; public String getDescription() { return getString(KEY_DESCRIPTION); } public void setDescription(String description) { put(KEY_DESCRIPTION, description); } public ParseFile getImage() { return getParseFile(KEY_IMAGE); } public void setImage(ParseFile file) { put(KEY_IMAGE, file); } public ParseUser getUser() { return getParseUser(KEY_USER); } public void setUser(ParseUser user) { put(KEY_USER, user); } }
9240bdd82cf4f7a240a6d44dfd06513ba4d432fc
4,642
java
Java
src/main/java/org/jas/dnd/Jdk6u10TransparencyManager.java
josdem/jmetadata
ca64635f248a9fae59627d1dd5d93429286d40f1
[ "Apache-2.0" ]
5
2015-01-22T14:36:41.000Z
2021-03-21T17:58:56.000Z
src/main/java/org/jas/dnd/Jdk6u10TransparencyManager.java
josdem/jmetadata
ca64635f248a9fae59627d1dd5d93429286d40f1
[ "Apache-2.0" ]
9
2018-08-26T11:48:09.000Z
2020-06-15T23:53:28.000Z
src/main/java/org/jas/dnd/Jdk6u10TransparencyManager.java
josdem/jmetadata
ca64635f248a9fae59627d1dd5d93429286d40f1
[ "Apache-2.0" ]
null
null
null
32.531469
99
0.767627
1,001,646
/* Copyright 2013 Jose Luis De la Cruz Morales [email protected] 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.jas.dnd; import java.awt.Shape; import java.awt.Window; import java.awt.Component; import java.awt.Container; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import javax.swing.JComponent; import org.jas.util.MethodWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Jdk6u10TransparencyManager implements TransparencyManager { private MethodWrapper<Void> setWindowShapeMethod; private MethodWrapper<Void> setWindowOpacityMethod; private MethodWrapper<Void> setWindowOpaqueMethod; private MethodWrapper<Boolean> isTranslucencyCapableMethod; private MethodWrapper<Boolean> isTranslucencySupportedMethod; private static final Logger log = LoggerFactory.getLogger(Jdk6u10TransparencyManager.class); public Jdk6u10TransparencyManager() { Class<?> translucencyClass = MethodWrapper.getClass("com.sun.awt.AWTUtilities$Translucency"); isTranslucencySupportedMethod = MethodWrapper .forClass("com.sun.awt.AWTUtilities") .method("isTranslucencySupported") .withParameters(translucencyClass) .andReturnType(boolean.class); isTranslucencyCapableMethod = MethodWrapper .forClass("com.sun.awt.AWTUtilities") .method("isTranslucencyCapable") .withParameters(GraphicsConfiguration.class) .andReturnType(boolean.class); setWindowShapeMethod = MethodWrapper .forClass("com.sun.awt.AWTUtilities") .method("setWindowShape") .withParameters(Window.class, Shape.class) .andReturnType(null); setWindowOpacityMethod = MethodWrapper .forClass("com.sun.awt.AWTUtilities") .method("setWindowOpacity") .withParameters(Window.class, float.class) .andReturnType(null); setWindowOpaqueMethod = MethodWrapper .forClass("com.sun.awt.AWTUtilities") .method("setWindowOpaque") .withParameters(Window.class, boolean.class) .andReturnType(null); } @Override public boolean isTranslucencySupported(Object kind) { return isTranslucencySupportedMethod.invoke(kind); } @Override public boolean isTranslucencyCapable(GraphicsConfiguration gc) { return isTranslucencyCapableMethod.invoke(gc); } @Override public void setWindowShape(Window window, Shape shape) { setWindowShapeMethod.invoke(window, shape); } @Override public void setWindowOpacity(Window window, float opacity) { setWindowOpacityMethod.invoke(window, opacity); } @Override public void setWindowOpaque(Window window, boolean opaque) { setWindowOpaqueMethod.invoke(window, opaque); doTheDoubleBuffer(window); } private void doTheDoubleBuffer(Component c) { if (c instanceof JComponent) { JComponent comp = (JComponent) c; comp.setDoubleBuffered(false); } if (c instanceof Container) { Container container = (Container) c; for (Component c2 : container.getComponents()) { doTheDoubleBuffer(c2); } } } @Override public GraphicsConfiguration getTranslucencyCapableGC() { GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice defaultScreenDevice = localGraphicsEnvironment.getDefaultScreenDevice(); GraphicsConfiguration translucencyCapableGC = defaultScreenDevice.getDefaultConfiguration(); if (!isTranslucencyCapable(translucencyCapableGC)) { translucencyCapableGC = null; log.info("Default graphics configuration does not support translucency"); GraphicsEnvironment env = localGraphicsEnvironment; GraphicsDevice[] devices = env.getScreenDevices(); for (int i = 0; i < devices.length && translucencyCapableGC == null; i++) { GraphicsConfiguration[] configs = devices[i].getConfigurations(); for (int j = 0; j < configs.length && translucencyCapableGC == null; j++) { if (isTranslucencyCapable(configs[j])) { translucencyCapableGC = configs[j]; } } } } if (translucencyCapableGC == null) { log.warn("Translucency capable graphics configuration not found"); } return translucencyCapableGC; } }
9240be7b1f7612a16348bbd2b1048e104713450a
5,559
java
Java
jqm-all/jqm-admin/src/main/java/com/enioka/api/admin/JobDefDto.java
iherasymenko/jqm
2139a341e47e8add1113d46dd9c41068478b0d94
[ "Apache-2.0" ]
79
2015-02-01T11:11:22.000Z
2021-11-29T08:15:34.000Z
jqm-all/jqm-admin/src/main/java/com/enioka/api/admin/JobDefDto.java
iherasymenko/jqm
2139a341e47e8add1113d46dd9c41068478b0d94
[ "Apache-2.0" ]
296
2015-01-06T16:04:04.000Z
2022-03-31T13:57:21.000Z
jqm-all/jqm-admin/src/main/java/com/enioka/api/admin/JobDefDto.java
iherasymenko/jqm
2139a341e47e8add1113d46dd9c41068478b0d94
[ "Apache-2.0" ]
34
2016-01-16T07:45:44.000Z
2021-09-09T07:09:57.000Z
21.63035
140
0.659111
1,001,647
/** * Copyright © 2013 enioka. 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.enioka.api.admin; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; /** * A job definition is the template of the job instances (the actual launches). It fully defines what to run (the class to load, the default * job instance parameters...) and how to run it (the execution context). * */ @XmlRootElement public class JobDefDto implements Serializable { private static final long serialVersionUID = 4934352148555212325L; private Integer id; private String description; private boolean canBeRestarted = true; private String javaClassName; private Integer queueId; private String applicationName; private String application; private String module; private String keyword1; private String keyword2; private String keyword3; private boolean highlander, enabled; private String jarPath; private String pathType; private Integer reasonableRuntimeLimitMinute; private Integer classLoaderId; @XmlElementWrapper(name = "parameters") @XmlElement(name = "parameter") private Map<String, String> parameters = new HashMap<String, String>(); private List<ScheduledJob> schedules = new ArrayList<ScheduledJob>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isCanBeRestarted() { return canBeRestarted; } public void setCanBeRestarted(boolean canBeRestarted) { this.canBeRestarted = canBeRestarted; } public String getJavaClassName() { return javaClassName; } public void setJavaClassName(String javaClassName) { this.javaClassName = javaClassName; } public Integer getQueueId() { return queueId; } public void setQueueId(Integer queueId) { this.queueId = queueId; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getApplication() { return application; } public void setApplication(String application) { this.application = application; } public String getModule() { return module; } public void setModule(String module) { this.module = module; } public String getKeyword1() { return keyword1; } public void setKeyword1(String keyword1) { this.keyword1 = keyword1; } public String getKeyword2() { return keyword2; } public void setKeyword2(String keyword2) { this.keyword2 = keyword2; } public String getKeyword3() { return keyword3; } public void setKeyword3(String keyword3) { this.keyword3 = keyword3; } public boolean isHighlander() { return highlander; } public void setHighlander(boolean highlander) { this.highlander = highlander; } public String getJarPath() { return jarPath; } public void setJarPath(String jarPath) { this.jarPath = jarPath; } public String getPathType() { return pathType; } public void setPathType(String pathType) { this.pathType = pathType; } public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Integer getReasonableRuntimeLimitMinute() { return reasonableRuntimeLimitMinute; } public void setReasonableRuntimeLimitMinute(Integer reasonableRuntimeLimitMinute) { this.reasonableRuntimeLimitMinute = reasonableRuntimeLimitMinute; } public Integer getClassLoaderId() { return this.classLoaderId; } public List<ScheduledJob> getSchedules() { return schedules; } public void setSchedules(List<ScheduledJob> schedules) { this.schedules = schedules; } public void setClassLoaderId(Integer classLoaderId) { this.classLoaderId = classLoaderId; } public JobDefDto addSchedule(ScheduledJob sj) { this.schedules.add(sj); return this; } }
9240beb6cc60768798a0d2bf89d5d67bab84405c
465
java
Java
MyPractice/src/MaximumSubarray.java
anilabha/Java-DS-Algo
860e888ab4bb37d76339227238e6d6c78e2c1f46
[ "MIT" ]
null
null
null
MyPractice/src/MaximumSubarray.java
anilabha/Java-DS-Algo
860e888ab4bb37d76339227238e6d6c78e2c1f46
[ "MIT" ]
null
null
null
MyPractice/src/MaximumSubarray.java
anilabha/Java-DS-Algo
860e888ab4bb37d76339227238e6d6c78e2c1f46
[ "MIT" ]
null
null
null
20.217391
47
0.595699
1,001,648
public class MaximumSubarray { public static void main(String[] args) { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; System.out.println(maxSubArraySum(a)); } // for -ve and +ve element static int maxSubArraySum(int a[]) { int size = a.length; int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = Math.max(a[i], curr_max + a[i]); max_so_far = Math.max(max_so_far, curr_max); } return max_so_far; } }
9240bf73ac0300bd4749864f75e2f5c146ab9d1e
1,669
java
Java
sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/ApplicationGatewayRequestRoutingRuleType.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
3
2021-09-15T16:25:19.000Z
2021-12-17T05:41:00.000Z
sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/ApplicationGatewayRequestRoutingRuleType.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
12
2019-07-17T16:18:54.000Z
2019-07-17T21:30:02.000Z
sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/ApplicationGatewayRequestRoutingRuleType.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1
2022-01-31T19:22:33.000Z
2022-01-31T19:22:33.000Z
39.738095
132
0.788496
1,001,649
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_06_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for ApplicationGatewayRequestRoutingRuleType. */ public final class ApplicationGatewayRequestRoutingRuleType extends ExpandableStringEnum<ApplicationGatewayRequestRoutingRuleType> { /** Static value Basic for ApplicationGatewayRequestRoutingRuleType. */ public static final ApplicationGatewayRequestRoutingRuleType BASIC = fromString("Basic"); /** Static value PathBasedRouting for ApplicationGatewayRequestRoutingRuleType. */ public static final ApplicationGatewayRequestRoutingRuleType PATH_BASED_ROUTING = fromString("PathBasedRouting"); /** * Creates or finds a ApplicationGatewayRequestRoutingRuleType from its string representation. * @param name a name to look for * @return the corresponding ApplicationGatewayRequestRoutingRuleType */ @JsonCreator public static ApplicationGatewayRequestRoutingRuleType fromString(String name) { return fromString(name, ApplicationGatewayRequestRoutingRuleType.class); } /** * @return known ApplicationGatewayRequestRoutingRuleType values */ public static Collection<ApplicationGatewayRequestRoutingRuleType> values() { return values(ApplicationGatewayRequestRoutingRuleType.class); } }
9240bf86d169975953178b314520cbb98c526ef7
786
java
Java
logiweb-service/src/main/java/com/alekseytyan/logiweb/config/security/handler/CustomLogoutHandler.java
tuanalexeu/logiweb-microservices
cd38c03862a7767dc6c847db66585e32f166c98e
[ "MIT" ]
1
2021-04-19T15:20:57.000Z
2021-04-19T15:20:57.000Z
logiweb-service/src/main/java/com/alekseytyan/logiweb/config/security/handler/CustomLogoutHandler.java
tuanalexeu/logiweb-microservices
cd38c03862a7767dc6c847db66585e32f166c98e
[ "MIT" ]
1
2021-04-17T12:30:23.000Z
2021-04-18T08:48:18.000Z
logiweb-service/src/main/java/com/alekseytyan/logiweb/config/security/handler/CustomLogoutHandler.java
tuanalexeu/logiweb-microservices
cd38c03862a7767dc6c847db66585e32f166c98e
[ "MIT" ]
null
null
null
31.44
92
0.760814
1,001,650
package com.alekseytyan.logiweb.config.security.handler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CustomLogoutHandler implements LogoutHandler { private static final Logger logger = LoggerFactory.getLogger(CustomLogoutHandler.class); @Override public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) { logger.info("User [" + authentication.getName() + "] just logged out"); } }
9240c026f9c5ea64d0c83e3091222d46dd1339f1
62,832
java
Java
aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/BurninDestinationSettings.java
pgoranss/aws-sdk-java
041ffc4197309c98c4be534b43ca2bda146e4f7c
[ "Apache-2.0" ]
1
2019-04-21T21:56:44.000Z
2019-04-21T21:56:44.000Z
aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/BurninDestinationSettings.java
pgoranss/aws-sdk-java
041ffc4197309c98c4be534b43ca2bda146e4f7c
[ "Apache-2.0" ]
110
2019-11-11T19:37:58.000Z
2021-07-16T18:23:58.000Z
aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/BurninDestinationSettings.java
pgoranss/aws-sdk-java
041ffc4197309c98c4be534b43ca2bda146e4f7c
[ "Apache-2.0" ]
1
2020-02-12T01:46:54.000Z
2020-02-12T01:46:54.000Z
51.841584
145
0.685367
1,001,651
/* * Copyright 2014-2019 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.mediaconvert.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * Burn-In Destination Settings. * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mediaconvert-2017-08-29/BurninDestinationSettings" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class BurninDestinationSettings implements Serializable, Cloneable, StructuredPojo { /** * If no explicit x_position or y_position is provided, setting alignment to centered will place the captions at the * bottom center of the output. Similarly, setting a left alignment will align captions to the bottom left of the * output. If x and y positions are given in conjunction with the alignment parameter, the font will be justified * (either left or centered) relative to those coordinates. This option is not valid for source captions that are * STL, 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. */ private String alignment; /** * Specifies the color of the rectangle behind the captions. All burn-in and DVB-Sub font settings must match. */ private String backgroundColor; /** * Specifies the opacity of the background rectangle. 255 is opaque; 0 is transparent. Leaving this parameter blank * is equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. */ private Integer backgroundOpacity; /** * Specifies the color of the burned-in captions. This option is not valid for source captions that are STL, * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in and * DVB-Sub font settings must match. */ private String fontColor; /** * Specifies the opacity of the burned-in captions. 255 is opaque; 0 is transparent. All burn-in and DVB-Sub font * settings must match. */ private Integer fontOpacity; /** * Font resolution in DPI (dots per inch); default is 96 dpi. All burn-in and DVB-Sub font settings must match. */ private Integer fontResolution; /** * Provide the font script, using an ISO 15924 script code, if the LanguageCode is not sufficient for determining * the script type. Where LanguageCode or CustomLanguageCode is sufficient, use "AUTOMATIC" or leave unset. This is * used to help determine the appropriate font for rendering burn-in captions. */ private String fontScript; /** * A positive integer indicates the exact font size in points. Set to 0 for automatic font size selection. All * burn-in and DVB-Sub font settings must match. */ private Integer fontSize; /** * Specifies font outline color. This option is not valid for source captions that are either 608/embedded or * teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font * settings must match. */ private String outlineColor; /** * Specifies font outline size in pixels. This option is not valid for source captions that are either 608/embedded * or teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font * settings must match. */ private Integer outlineSize; /** * Specifies the color of the shadow cast by the captions. All burn-in and DVB-Sub font settings must match. */ private String shadowColor; /** * Specifies the opacity of the shadow. 255 is opaque; 0 is transparent. Leaving this parameter blank is equivalent * to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. */ private Integer shadowOpacity; /** * Specifies the horizontal offset of the shadow relative to the captions in pixels. A value of -2 would result in a * shadow offset 2 pixels to the left. All burn-in and DVB-Sub font settings must match. */ private Integer shadowXOffset; /** * Specifies the vertical offset of the shadow relative to the captions in pixels. A value of -2 would result in a * shadow offset 2 pixels above the text. All burn-in and DVB-Sub font settings must match. */ private Integer shadowYOffset; /** * Only applies to jobs with input captions in Teletext or STL formats. Specify whether the spacing between letters * in your captions is set by the captions grid or varies depending on letter width. Choose fixed grid to conform to * the spacing specified in the captions file more accurately. Choose proportional to make the text easier to read if * the captions are closed caption. */ private String teletextSpacing; /** * Specifies the horizontal position of the caption relative to the left side of the output in pixels. A value of 10 * would result in the captions starting 10 pixels from the left of the output. If no explicit x_position is * provided, the horizontal caption position will be determined by the alignment parameter. This option is not valid * for source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by the * caption stream. All burn-in and DVB-Sub font settings must match. */ private Integer xPosition; /** * Specifies the vertical position of the caption relative to the top of the output in pixels. A value of 10 would * result in the captions starting 10 pixels from the top of the output. If no explicit y_position is provided, the * caption will be positioned towards the bottom of the output. This option is not valid for source captions that are * STL, 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. */ private Integer yPosition; /** * If no explicit x_position or y_position is provided, setting alignment to centered will place the captions at the * bottom center of the output. Similarly, setting a left alignment will align captions to the bottom left of the * output. If x and y positions are given in conjunction with the alignment parameter, the font will be justified * (either left or centered) relative to those coordinates. This option is not valid for source captions that are * STL, 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * * @param alignment * If no explicit x_position or y_position is provided, setting alignment to centered will place the captions * at the bottom center of the output. Similarly, setting a left alignment will align captions to the bottom * left of the output. If x and y positions are given in conjunction with the alignment parameter, the font * will be justified (either left or centered) relative to those coordinates. This option is not valid for * source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by * the caption stream. All burn-in and DVB-Sub font settings must match. * @see BurninSubtitleAlignment */ public void setAlignment(String alignment) { this.alignment = alignment; } /** * If no explicit x_position or y_position is provided, setting alignment to centered will place the captions at the * bottom center of the output. Similarly, setting a left alignment will align captions to the bottom left of the * output. If x and y positions are given in conjunction with the alignment parameter, the font will be justified * (either left or centered) relative to those coordinates. This option is not valid for source captions that are * STL, 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * * @return If no explicit x_position or y_position is provided, setting alignment to centered will place the * captions at the bottom center of the output. Similarly, setting a left alignment will align captions to * the bottom left of the output. If x and y positions are given in conjunction with the alignment * parameter, the font will be justified (either left or centered) relative to those coordinates. This * option is not valid for source captions that are STL, 608/embedded or teletext. These source settings are * already pre-defined by the caption stream. All burn-in and DVB-Sub font settings must match. * @see BurninSubtitleAlignment */ public String getAlignment() { return this.alignment; } /** * If no explicit x_position or y_position is provided, setting alignment to centered will place the captions at the * bottom center of the output. Similarly, setting a left alignment will align captions to the bottom left of the * output. If x and y positions are given in conjunction with the alignment parameter, the font will be justified * (either left or centered) relative to those coordinates. This option is not valid for source captions that are * STL, 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * * @param alignment * If no explicit x_position or y_position is provided, setting alignment to centered will place the captions * at the bottom center of the output. Similarly, setting a left alignment will align captions to the bottom * left of the output. If x and y positions are given in conjunction with the alignment parameter, the font * will be justified (either left or centered) relative to those coordinates. This option is not valid for * source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by * the caption stream. All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleAlignment */ public BurninDestinationSettings withAlignment(String alignment) { setAlignment(alignment); return this; } /** * If no explicit x_position or y_position is provided, setting alignment to centered will place the captions at the * bottom center of the output. Similarly, setting a left alignment will align captions to the bottom left of the * output. If x and y positions are given in conjunction with the alignment parameter, the font will be justified * (either left or centered) relative to those coordinates. This option is not valid for source captions that are * STL, 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * * @param alignment * If no explicit x_position or y_position is provided, setting alignment to centered will place the captions * at the bottom center of the output. Similarly, setting a left alignment will align captions to the bottom * left of the output. If x and y positions are given in conjunction with the alignment parameter, the font * will be justified (either left or centered) relative to those coordinates. This option is not valid for * source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by * the caption stream. All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleAlignment */ public BurninDestinationSettings withAlignment(BurninSubtitleAlignment alignment) { this.alignment = alignment.toString(); return this; } /** * Specifies the color of the rectangle behind the captions. All burn-in and DVB-Sub font settings must match. * * @param backgroundColor * Specifies the color of the rectangle behind the captions. All burn-in and DVB-Sub font settings must * match. * @see BurninSubtitleBackgroundColor */ public void setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; } /** * Specifies the color of the rectangle behind the captions. All burn-in and DVB-Sub font settings must match. * * @return Specifies the color of the rectangle behind the captions. All burn-in and DVB-Sub font settings must * match. * @see BurninSubtitleBackgroundColor */ public String getBackgroundColor() { return this.backgroundColor; } /** * Specifies the color of the rectangle behind the captions. All burn-in and DVB-Sub font settings must match. * * @param backgroundColor * Specifies the color of the rectangle behind the captions. All burn-in and DVB-Sub font settings must * match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleBackgroundColor */ public BurninDestinationSettings withBackgroundColor(String backgroundColor) { setBackgroundColor(backgroundColor); return this; } /** * Specifies the color of the rectangle behind the captions. All burn-in and DVB-Sub font settings must match. * * @param backgroundColor * Specifies the color of the rectangle behind the captions. All burn-in and DVB-Sub font settings must * match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleBackgroundColor */ public BurninDestinationSettings withBackgroundColor(BurninSubtitleBackgroundColor backgroundColor) { this.backgroundColor = backgroundColor.toString(); return this; } /** * Specifies the opacity of the background rectangle. 255 is opaque; 0 is transparent. Leaving this parameter blank * is equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. * * @param backgroundOpacity * Specifies the opacity of the background rectangle. 255 is opaque; 0 is transparent. Leaving this parameter * blank is equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. */ public void setBackgroundOpacity(Integer backgroundOpacity) { this.backgroundOpacity = backgroundOpacity; } /** * Specifies the opacity of the background rectangle. 255 is opaque; 0 is transparent. Leaving this parameter blank * is equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. * * @return Specifies the opacity of the background rectangle. 255 is opaque; 0 is transparent. Leaving this * parameter blank is equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings * must match. */ public Integer getBackgroundOpacity() { return this.backgroundOpacity; } /** * Specifies the opacity of the background rectangle. 255 is opaque; 0 is transparent. Leaving this parameter blank * is equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. * * @param backgroundOpacity * Specifies the opacity of the background rectangle. 255 is opaque; 0 is transparent. Leaving this parameter * blank is equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withBackgroundOpacity(Integer backgroundOpacity) { setBackgroundOpacity(backgroundOpacity); return this; } /** * Specifies the color of the burned-in captions. This option is not valid for source captions that are STL, * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in and * DVB-Sub font settings must match. * * @param fontColor * Specifies the color of the burned-in captions. This option is not valid for source captions that are STL, * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * @see BurninSubtitleFontColor */ public void setFontColor(String fontColor) { this.fontColor = fontColor; } /** * Specifies the color of the burned-in captions. This option is not valid for source captions that are STL, * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in and * DVB-Sub font settings must match. * * @return Specifies the color of the burned-in captions. This option is not valid for source captions that are STL, * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All * burn-in and DVB-Sub font settings must match. * @see BurninSubtitleFontColor */ public String getFontColor() { return this.fontColor; } /** * Specifies the color of the burned-in captions. This option is not valid for source captions that are STL, * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in and * DVB-Sub font settings must match. * * @param fontColor * Specifies the color of the burned-in captions. This option is not valid for source captions that are STL, * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleFontColor */ public BurninDestinationSettings withFontColor(String fontColor) { setFontColor(fontColor); return this; } /** * Specifies the color of the burned-in captions. This option is not valid for source captions that are STL, * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in and * DVB-Sub font settings must match. * * @param fontColor * Specifies the color of the burned-in captions. This option is not valid for source captions that are STL, * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleFontColor */ public BurninDestinationSettings withFontColor(BurninSubtitleFontColor fontColor) { this.fontColor = fontColor.toString(); return this; } /** * Specifies the opacity of the burned-in captions. 255 is opaque; 0 is transparent. All burn-in and DVB-Sub font * settings must match. * * @param fontOpacity * Specifies the opacity of the burned-in captions. 255 is opaque; 0 is transparent. All burn-in and DVB-Sub * font settings must match. */ public void setFontOpacity(Integer fontOpacity) { this.fontOpacity = fontOpacity; } /** * Specifies the opacity of the burned-in captions. 255 is opaque; 0 is transparent. All burn-in and DVB-Sub font * settings must match. * * @return Specifies the opacity of the burned-in captions. 255 is opaque; 0 is transparent. All burn-in and DVB-Sub * font settings must match. */ public Integer getFontOpacity() { return this.fontOpacity; } /** * Specifies the opacity of the burned-in captions. 255 is opaque; 0 is transparent. All burn-in and DVB-Sub font * settings must match. * * @param fontOpacity * Specifies the opacity of the burned-in captions. 255 is opaque; 0 is transparent. All burn-in and DVB-Sub * font settings must match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withFontOpacity(Integer fontOpacity) { setFontOpacity(fontOpacity); return this; } /** * Font resolution in DPI (dots per inch); default is 96 dpi. All burn-in and DVB-Sub font settings must match. * * @param fontResolution * Font resolution in DPI (dots per inch); default is 96 dpi. All burn-in and DVB-Sub font settings must * match. */ public void setFontResolution(Integer fontResolution) { this.fontResolution = fontResolution; } /** * Font resolution in DPI (dots per inch); default is 96 dpi. All burn-in and DVB-Sub font settings must match. * * @return Font resolution in DPI (dots per inch); default is 96 dpi. All burn-in and DVB-Sub font settings must * match. */ public Integer getFontResolution() { return this.fontResolution; } /** * Font resolution in DPI (dots per inch); default is 96 dpi. All burn-in and DVB-Sub font settings must match. * * @param fontResolution * Font resolution in DPI (dots per inch); default is 96 dpi. All burn-in and DVB-Sub font settings must * match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withFontResolution(Integer fontResolution) { setFontResolution(fontResolution); return this; } /** * Provide the font script, using an ISO 15924 script code, if the LanguageCode is not sufficient for determining * the script type. Where LanguageCode or CustomLanguageCode is sufficient, use "AUTOMATIC" or leave unset. This is * used to help determine the appropriate font for rendering burn-in captions. * * @param fontScript * Provide the font script, using an ISO 15924 script code, if the LanguageCode is not sufficient for * determining the script type. Where LanguageCode or CustomLanguageCode is sufficient, use "AUTOMATIC" or * leave unset. This is used to help determine the appropriate font for rendering burn-in captions. * @see FontScript */ public void setFontScript(String fontScript) { this.fontScript = fontScript; } /** * Provide the font script, using an ISO 15924 script code, if the LanguageCode is not sufficient for determining * the script type. Where LanguageCode or CustomLanguageCode is sufficient, use "AUTOMATIC" or leave unset. This is * used to help determine the appropriate font for rendering burn-in captions. * * @return Provide the font script, using an ISO 15924 script code, if the LanguageCode is not sufficient for * determining the script type. Where LanguageCode or CustomLanguageCode is sufficient, use "AUTOMATIC" or * leave unset. This is used to help determine the appropriate font for rendering burn-in captions. * @see FontScript */ public String getFontScript() { return this.fontScript; } /** * Provide the font script, using an ISO 15924 script code, if the LanguageCode is not sufficient for determining * the script type. Where LanguageCode or CustomLanguageCode is sufficient, use "AUTOMATIC" or leave unset. This is * used to help determine the appropriate font for rendering burn-in captions. * * @param fontScript * Provide the font script, using an ISO 15924 script code, if the LanguageCode is not sufficient for * determining the script type. Where LanguageCode or CustomLanguageCode is sufficient, use "AUTOMATIC" or * leave unset. This is used to help determine the appropriate font for rendering burn-in captions. * @return Returns a reference to this object so that method calls can be chained together. * @see FontScript */ public BurninDestinationSettings withFontScript(String fontScript) { setFontScript(fontScript); return this; } /** * Provide the font script, using an ISO 15924 script code, if the LanguageCode is not sufficient for determining * the script type. Where LanguageCode or CustomLanguageCode is sufficient, use "AUTOMATIC" or leave unset. This is * used to help determine the appropriate font for rendering burn-in captions. * * @param fontScript * Provide the font script, using an ISO 15924 script code, if the LanguageCode is not sufficient for * determining the script type. Where LanguageCode or CustomLanguageCode is sufficient, use "AUTOMATIC" or * leave unset. This is used to help determine the appropriate font for rendering burn-in captions. * @return Returns a reference to this object so that method calls can be chained together. * @see FontScript */ public BurninDestinationSettings withFontScript(FontScript fontScript) { this.fontScript = fontScript.toString(); return this; } /** * A positive integer indicates the exact font size in points. Set to 0 for automatic font size selection. All * burn-in and DVB-Sub font settings must match. * * @param fontSize * A positive integer indicates the exact font size in points. Set to 0 for automatic font size selection. * All burn-in and DVB-Sub font settings must match. */ public void setFontSize(Integer fontSize) { this.fontSize = fontSize; } /** * A positive integer indicates the exact font size in points. Set to 0 for automatic font size selection. All * burn-in and DVB-Sub font settings must match. * * @return A positive integer indicates the exact font size in points. Set to 0 for automatic font size selection. * All burn-in and DVB-Sub font settings must match. */ public Integer getFontSize() { return this.fontSize; } /** * A positive integer indicates the exact font size in points. Set to 0 for automatic font size selection. All * burn-in and DVB-Sub font settings must match. * * @param fontSize * A positive integer indicates the exact font size in points. Set to 0 for automatic font size selection. * All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withFontSize(Integer fontSize) { setFontSize(fontSize); return this; } /** * Specifies font outline color. This option is not valid for source captions that are either 608/embedded or * teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font * settings must match. * * @param outlineColor * Specifies font outline color. This option is not valid for source captions that are either 608/embedded or * teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub * font settings must match. * @see BurninSubtitleOutlineColor */ public void setOutlineColor(String outlineColor) { this.outlineColor = outlineColor; } /** * Specifies font outline color. This option is not valid for source captions that are either 608/embedded or * teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font * settings must match. * * @return Specifies font outline color. This option is not valid for source captions that are either 608/embedded * or teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub * font settings must match. * @see BurninSubtitleOutlineColor */ public String getOutlineColor() { return this.outlineColor; } /** * Specifies font outline color. This option is not valid for source captions that are either 608/embedded or * teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font * settings must match. * * @param outlineColor * Specifies font outline color. This option is not valid for source captions that are either 608/embedded or * teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub * font settings must match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleOutlineColor */ public BurninDestinationSettings withOutlineColor(String outlineColor) { setOutlineColor(outlineColor); return this; } /** * Specifies font outline color. This option is not valid for source captions that are either 608/embedded or * teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font * settings must match. * * @param outlineColor * Specifies font outline color. This option is not valid for source captions that are either 608/embedded or * teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub * font settings must match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleOutlineColor */ public BurninDestinationSettings withOutlineColor(BurninSubtitleOutlineColor outlineColor) { this.outlineColor = outlineColor.toString(); return this; } /** * Specifies font outline size in pixels. This option is not valid for source captions that are either 608/embedded * or teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font * settings must match. * * @param outlineSize * Specifies font outline size in pixels. This option is not valid for source captions that are either * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. */ public void setOutlineSize(Integer outlineSize) { this.outlineSize = outlineSize; } /** * Specifies font outline size in pixels. This option is not valid for source captions that are either 608/embedded * or teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font * settings must match. * * @return Specifies font outline size in pixels. This option is not valid for source captions that are either * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All * burn-in and DVB-Sub font settings must match. */ public Integer getOutlineSize() { return this.outlineSize; } /** * Specifies font outline size in pixels. This option is not valid for source captions that are either 608/embedded * or teletext. These source settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font * settings must match. * * @param outlineSize * Specifies font outline size in pixels. This option is not valid for source captions that are either * 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withOutlineSize(Integer outlineSize) { setOutlineSize(outlineSize); return this; } /** * Specifies the color of the shadow cast by the captions. All burn-in and DVB-Sub font settings must match. * * @param shadowColor * Specifies the color of the shadow cast by the captions. All burn-in and DVB-Sub font settings must match. * @see BurninSubtitleShadowColor */ public void setShadowColor(String shadowColor) { this.shadowColor = shadowColor; } /** * Specifies the color of the shadow cast by the captions. All burn-in and DVB-Sub font settings must match. * * @return Specifies the color of the shadow cast by the captions. All burn-in and DVB-Sub font settings must match. * @see BurninSubtitleShadowColor */ public String getShadowColor() { return this.shadowColor; } /** * Specifies the color of the shadow cast by the captions. All burn-in and DVB-Sub font settings must match. * * @param shadowColor * Specifies the color of the shadow cast by the captions. All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleShadowColor */ public BurninDestinationSettings withShadowColor(String shadowColor) { setShadowColor(shadowColor); return this; } /** * Specifies the color of the shadow cast by the captions. All burn-in and DVB-Sub font settings must match. * * @param shadowColor * Specifies the color of the shadow cast by the captions. All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleShadowColor */ public BurninDestinationSettings withShadowColor(BurninSubtitleShadowColor shadowColor) { this.shadowColor = shadowColor.toString(); return this; } /** * Specifies the opacity of the shadow. 255 is opaque; 0 is transparent. Leaving this parameter blank is equivalent * to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. * * @param shadowOpacity * Specifies the opacity of the shadow. 255 is opaque; 0 is transparent. Leaving this parameter blank is * equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. */ public void setShadowOpacity(Integer shadowOpacity) { this.shadowOpacity = shadowOpacity; } /** * Specifies the opacity of the shadow. 255 is opaque; 0 is transparent. Leaving this parameter blank is equivalent * to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. * * @return Specifies the opacity of the shadow. 255 is opaque; 0 is transparent. Leaving this parameter blank is * equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. */ public Integer getShadowOpacity() { return this.shadowOpacity; } /** * Specifies the opacity of the shadow. 255 is opaque; 0 is transparent. Leaving this parameter blank is equivalent * to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. * * @param shadowOpacity * Specifies the opacity of the shadow. 255 is opaque; 0 is transparent. Leaving this parameter blank is * equivalent to setting it to 0 (transparent). All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withShadowOpacity(Integer shadowOpacity) { setShadowOpacity(shadowOpacity); return this; } /** * Specifies the horizontal offset of the shadow relative to the captions in pixels. A value of -2 would result in a * shadow offset 2 pixels to the left. All burn-in and DVB-Sub font settings must match. * * @param shadowXOffset * Specifies the horizontal offset of the shadow relative to the captions in pixels. A value of -2 would * result in a shadow offset 2 pixels to the left. All burn-in and DVB-Sub font settings must match. */ public void setShadowXOffset(Integer shadowXOffset) { this.shadowXOffset = shadowXOffset; } /** * Specifies the horizontal offset of the shadow relative to the captions in pixels. A value of -2 would result in a * shadow offset 2 pixels to the left. All burn-in and DVB-Sub font settings must match. * * @return Specifies the horizontal offset of the shadow relative to the captions in pixels. A value of -2 would * result in a shadow offset 2 pixels to the left. All burn-in and DVB-Sub font settings must match. */ public Integer getShadowXOffset() { return this.shadowXOffset; } /** * Specifies the horizontal offset of the shadow relative to the captions in pixels. A value of -2 would result in a * shadow offset 2 pixels to the left. All burn-in and DVB-Sub font settings must match. * * @param shadowXOffset * Specifies the horizontal offset of the shadow relative to the captions in pixels. A value of -2 would * result in a shadow offset 2 pixels to the left. All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withShadowXOffset(Integer shadowXOffset) { setShadowXOffset(shadowXOffset); return this; } /** * Specifies the vertical offset of the shadow relative to the captions in pixels. A value of -2 would result in a * shadow offset 2 pixels above the text. All burn-in and DVB-Sub font settings must match. * * @param shadowYOffset * Specifies the vertical offset of the shadow relative to the captions in pixels. A value of -2 would result * in a shadow offset 2 pixels above the text. All burn-in and DVB-Sub font settings must match. */ public void setShadowYOffset(Integer shadowYOffset) { this.shadowYOffset = shadowYOffset; } /** * Specifies the vertical offset of the shadow relative to the captions in pixels. A value of -2 would result in a * shadow offset 2 pixels above the text. All burn-in and DVB-Sub font settings must match. * * @return Specifies the vertical offset of the shadow relative to the captions in pixels. A value of -2 would * result in a shadow offset 2 pixels above the text. All burn-in and DVB-Sub font settings must match. */ public Integer getShadowYOffset() { return this.shadowYOffset; } /** * Specifies the vertical offset of the shadow relative to the captions in pixels. A value of -2 would result in a * shadow offset 2 pixels above the text. All burn-in and DVB-Sub font settings must match. * * @param shadowYOffset * Specifies the vertical offset of the shadow relative to the captions in pixels. A value of -2 would result * in a shadow offset 2 pixels above the text. All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withShadowYOffset(Integer shadowYOffset) { setShadowYOffset(shadowYOffset); return this; } /** * Only applies to jobs with input captions in Teletext or STL formats. Specify whether the spacing between letters * in your captions is set by the captions grid or varies depending on letter width. Choose fixed grid to conform to * the spacing specified in the captions file more accurately. Choose proportional to make the text easier to read if * the captions are closed caption. * * @param teletextSpacing * Only applies to jobs with input captions in Teletext or STL formats. Specify whether the spacing between * letters in your captions is set by the captions grid or varies depending on letter width. Choose fixed * grid to conform to the spacing specified in the captions file more accurately. Choose proportional to make * the text easier to read if the captions are closed caption. * @see BurninSubtitleTeletextSpacing */ public void setTeletextSpacing(String teletextSpacing) { this.teletextSpacing = teletextSpacing; } /** * Only applies to jobs with input captions in Teletext or STL formats. Specify whether the spacing between letters * in your captions is set by the captions grid or varies depending on letter width. Choose fixed grid to conform to * the spacing specified in the captions file more accurately. Choose proportional to make the text easier to read if * the captions are closed caption. * * @return Only applies to jobs with input captions in Teletext or STL formats. Specify whether the spacing between * letters in your captions is set by the captions grid or varies depending on letter width. Choose fixed * grid to conform to the spacing specified in the captions file more accurately. Choose proportional to * make the text easier to read if the captions are closed caption. * @see BurninSubtitleTeletextSpacing */ public String getTeletextSpacing() { return this.teletextSpacing; } /** * Only applies to jobs with input captions in Teletext or STL formats. Specify whether the spacing between letters * in your captions is set by the captions grid or varies depending on letter width. Choose fixed grid to conform to * the spacing specified in the captions file more accurately. Choose proportional to make the text easier to read if * the captions are closed caption. * * @param teletextSpacing * Only applies to jobs with input captions in Teletext or STL formats. Specify whether the spacing between * letters in your captions is set by the captions grid or varies depending on letter width. Choose fixed * grid to conform to the spacing specified in the captions file more accurately. Choose proportional to make * the text easier to read if the captions are closed caption. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleTeletextSpacing */ public BurninDestinationSettings withTeletextSpacing(String teletextSpacing) { setTeletextSpacing(teletextSpacing); return this; } /** * Only applies to jobs with input captions in Teletext or STL formats. Specify whether the spacing between letters * in your captions is set by the captions grid or varies depending on letter width. Choose fixed grid to conform to * the spacing specified in the captions file more accurately. Choose proportional to make the text easier to read if * the captions are closed caption. * * @param teletextSpacing * Only applies to jobs with input captions in Teletext or STL formats. Specify whether the spacing between * letters in your captions is set by the captions grid or varies depending on letter width. Choose fixed * grid to conform to the spacing specified in the captions file more accurately. Choose proportional to make * the text easier to read if the captions are closed caption. * @return Returns a reference to this object so that method calls can be chained together. * @see BurninSubtitleTeletextSpacing */ public BurninDestinationSettings withTeletextSpacing(BurninSubtitleTeletextSpacing teletextSpacing) { this.teletextSpacing = teletextSpacing.toString(); return this; } /** * Specifies the horizontal position of the caption relative to the left side of the output in pixels. A value of 10 * would result in the captions starting 10 pixels from the left of the output. If no explicit x_position is * provided, the horizontal caption position will be determined by the alignment parameter. This option is not valid * for source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by the * caption stream. All burn-in and DVB-Sub font settings must match. * * @param xPosition * Specifies the horizontal position of the caption relative to the left side of the output in pixels. A * value of 10 would result in the captions starting 10 pixels from the left of the output. If no explicit * x_position is provided, the horizontal caption position will be determined by the alignment parameter. * This option is not valid for source captions that are STL, 608/embedded or teletext. These source settings * are already pre-defined by the caption stream. All burn-in and DVB-Sub font settings must match. */ public void setXPosition(Integer xPosition) { this.xPosition = xPosition; } /** * Specifies the horizontal position of the caption relative to the left side of the output in pixels. A value of 10 * would result in the captions starting 10 pixels from the left of the output. If no explicit x_position is * provided, the horizontal caption position will be determined by the alignment parameter. This option is not valid * for source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by the * caption stream. All burn-in and DVB-Sub font settings must match. * * @return Specifies the horizontal position of the caption relative to the left side of the output in pixels. A * value of 10 would result in the captions starting 10 pixels from the left of the output. If no explicit * x_position is provided, the horizontal caption position will be determined by the alignment parameter. * This option is not valid for source captions that are STL, 608/embedded or teletext. These source * settings are already pre-defined by the caption stream. All burn-in and DVB-Sub font settings must match. */ public Integer getXPosition() { return this.xPosition; } /** * Specifies the horizontal position of the caption relative to the left side of the output in pixels. A value of 10 * would result in the captions starting 10 pixels from the left of the output. If no explicit x_position is * provided, the horizontal caption position will be determined by the alignment parameter. This option is not valid * for source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by the * caption stream. All burn-in and DVB-Sub font settings must match. * * @param xPosition * Specifies the horizontal position of the caption relative to the left side of the output in pixels. A * value of 10 would result in the captions starting 10 pixels from the left of the output. If no explicit * x_position is provided, the horizontal caption position will be determined by the alignment parameter. * This option is not valid for source captions that are STL, 608/embedded or teletext. These source settings * are already pre-defined by the caption stream. All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withXPosition(Integer xPosition) { setXPosition(xPosition); return this; } /** * Specifies the vertical position of the caption relative to the top of the output in pixels. A value of 10 would * result in the captions starting 10 pixels from the top of the output. If no explicit y_position is provided, the * caption will be positioned towards the bottom of the output. This option is not valid for source captions that are * STL, 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * * @param yPosition * Specifies the vertical position of the caption relative to the top of the output in pixels. A value of 10 * would result in the captions starting 10 pixels from the top of the output. If no explicit y_position is * provided, the caption will be positioned towards the bottom of the output. This option is not valid for * source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by * the caption stream. All burn-in and DVB-Sub font settings must match. */ public void setYPosition(Integer yPosition) { this.yPosition = yPosition; } /** * Specifies the vertical position of the caption relative to the top of the output in pixels. A value of 10 would * result in the captions starting 10 pixels from the top of the output. If no explicit y_position is provided, the * caption will be positioned towards the bottom of the output. This option is not valid for source captions that are * STL, 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * * @return Specifies the vertical position of the caption relative to the top of the output in pixels. A value of 10 * would result in the captions starting 10 pixels from the top of the output. If no explicit y_position is * provided, the caption will be positioned towards the bottom of the output. This option is not valid for * source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by * the caption stream. All burn-in and DVB-Sub font settings must match. */ public Integer getYPosition() { return this.yPosition; } /** * Specifies the vertical position of the caption relative to the top of the output in pixels. A value of 10 would * result in the captions starting 10 pixels from the top of the output. If no explicit y_position is provided, the * caption will be positioned towards the bottom of the output. This option is not valid for source captions that are * STL, 608/embedded or teletext. These source settings are already pre-defined by the caption stream. All burn-in * and DVB-Sub font settings must match. * * @param yPosition * Specifies the vertical position of the caption relative to the top of the output in pixels. A value of 10 * would result in the captions starting 10 pixels from the top of the output. If no explicit y_position is * provided, the caption will be positioned towards the bottom of the output. This option is not valid for * source captions that are STL, 608/embedded or teletext. These source settings are already pre-defined by * the caption stream. All burn-in and DVB-Sub font settings must match. * @return Returns a reference to this object so that method calls can be chained together. */ public BurninDestinationSettings withYPosition(Integer yPosition) { setYPosition(yPosition); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAlignment() != null) sb.append("Alignment: ").append(getAlignment()).append(","); if (getBackgroundColor() != null) sb.append("BackgroundColor: ").append(getBackgroundColor()).append(","); if (getBackgroundOpacity() != null) sb.append("BackgroundOpacity: ").append(getBackgroundOpacity()).append(","); if (getFontColor() != null) sb.append("FontColor: ").append(getFontColor()).append(","); if (getFontOpacity() != null) sb.append("FontOpacity: ").append(getFontOpacity()).append(","); if (getFontResolution() != null) sb.append("FontResolution: ").append(getFontResolution()).append(","); if (getFontScript() != null) sb.append("FontScript: ").append(getFontScript()).append(","); if (getFontSize() != null) sb.append("FontSize: ").append(getFontSize()).append(","); if (getOutlineColor() != null) sb.append("OutlineColor: ").append(getOutlineColor()).append(","); if (getOutlineSize() != null) sb.append("OutlineSize: ").append(getOutlineSize()).append(","); if (getShadowColor() != null) sb.append("ShadowColor: ").append(getShadowColor()).append(","); if (getShadowOpacity() != null) sb.append("ShadowOpacity: ").append(getShadowOpacity()).append(","); if (getShadowXOffset() != null) sb.append("ShadowXOffset: ").append(getShadowXOffset()).append(","); if (getShadowYOffset() != null) sb.append("ShadowYOffset: ").append(getShadowYOffset()).append(","); if (getTeletextSpacing() != null) sb.append("TeletextSpacing: ").append(getTeletextSpacing()).append(","); if (getXPosition() != null) sb.append("XPosition: ").append(getXPosition()).append(","); if (getYPosition() != null) sb.append("YPosition: ").append(getYPosition()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof BurninDestinationSettings == false) return false; BurninDestinationSettings other = (BurninDestinationSettings) obj; if (other.getAlignment() == null ^ this.getAlignment() == null) return false; if (other.getAlignment() != null && other.getAlignment().equals(this.getAlignment()) == false) return false; if (other.getBackgroundColor() == null ^ this.getBackgroundColor() == null) return false; if (other.getBackgroundColor() != null && other.getBackgroundColor().equals(this.getBackgroundColor()) == false) return false; if (other.getBackgroundOpacity() == null ^ this.getBackgroundOpacity() == null) return false; if (other.getBackgroundOpacity() != null && other.getBackgroundOpacity().equals(this.getBackgroundOpacity()) == false) return false; if (other.getFontColor() == null ^ this.getFontColor() == null) return false; if (other.getFontColor() != null && other.getFontColor().equals(this.getFontColor()) == false) return false; if (other.getFontOpacity() == null ^ this.getFontOpacity() == null) return false; if (other.getFontOpacity() != null && other.getFontOpacity().equals(this.getFontOpacity()) == false) return false; if (other.getFontResolution() == null ^ this.getFontResolution() == null) return false; if (other.getFontResolution() != null && other.getFontResolution().equals(this.getFontResolution()) == false) return false; if (other.getFontScript() == null ^ this.getFontScript() == null) return false; if (other.getFontScript() != null && other.getFontScript().equals(this.getFontScript()) == false) return false; if (other.getFontSize() == null ^ this.getFontSize() == null) return false; if (other.getFontSize() != null && other.getFontSize().equals(this.getFontSize()) == false) return false; if (other.getOutlineColor() == null ^ this.getOutlineColor() == null) return false; if (other.getOutlineColor() != null && other.getOutlineColor().equals(this.getOutlineColor()) == false) return false; if (other.getOutlineSize() == null ^ this.getOutlineSize() == null) return false; if (other.getOutlineSize() != null && other.getOutlineSize().equals(this.getOutlineSize()) == false) return false; if (other.getShadowColor() == null ^ this.getShadowColor() == null) return false; if (other.getShadowColor() != null && other.getShadowColor().equals(this.getShadowColor()) == false) return false; if (other.getShadowOpacity() == null ^ this.getShadowOpacity() == null) return false; if (other.getShadowOpacity() != null && other.getShadowOpacity().equals(this.getShadowOpacity()) == false) return false; if (other.getShadowXOffset() == null ^ this.getShadowXOffset() == null) return false; if (other.getShadowXOffset() != null && other.getShadowXOffset().equals(this.getShadowXOffset()) == false) return false; if (other.getShadowYOffset() == null ^ this.getShadowYOffset() == null) return false; if (other.getShadowYOffset() != null && other.getShadowYOffset().equals(this.getShadowYOffset()) == false) return false; if (other.getTeletextSpacing() == null ^ this.getTeletextSpacing() == null) return false; if (other.getTeletextSpacing() != null && other.getTeletextSpacing().equals(this.getTeletextSpacing()) == false) return false; if (other.getXPosition() == null ^ this.getXPosition() == null) return false; if (other.getXPosition() != null && other.getXPosition().equals(this.getXPosition()) == false) return false; if (other.getYPosition() == null ^ this.getYPosition() == null) return false; if (other.getYPosition() != null && other.getYPosition().equals(this.getYPosition()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAlignment() == null) ? 0 : getAlignment().hashCode()); hashCode = prime * hashCode + ((getBackgroundColor() == null) ? 0 : getBackgroundColor().hashCode()); hashCode = prime * hashCode + ((getBackgroundOpacity() == null) ? 0 : getBackgroundOpacity().hashCode()); hashCode = prime * hashCode + ((getFontColor() == null) ? 0 : getFontColor().hashCode()); hashCode = prime * hashCode + ((getFontOpacity() == null) ? 0 : getFontOpacity().hashCode()); hashCode = prime * hashCode + ((getFontResolution() == null) ? 0 : getFontResolution().hashCode()); hashCode = prime * hashCode + ((getFontScript() == null) ? 0 : getFontScript().hashCode()); hashCode = prime * hashCode + ((getFontSize() == null) ? 0 : getFontSize().hashCode()); hashCode = prime * hashCode + ((getOutlineColor() == null) ? 0 : getOutlineColor().hashCode()); hashCode = prime * hashCode + ((getOutlineSize() == null) ? 0 : getOutlineSize().hashCode()); hashCode = prime * hashCode + ((getShadowColor() == null) ? 0 : getShadowColor().hashCode()); hashCode = prime * hashCode + ((getShadowOpacity() == null) ? 0 : getShadowOpacity().hashCode()); hashCode = prime * hashCode + ((getShadowXOffset() == null) ? 0 : getShadowXOffset().hashCode()); hashCode = prime * hashCode + ((getShadowYOffset() == null) ? 0 : getShadowYOffset().hashCode()); hashCode = prime * hashCode + ((getTeletextSpacing() == null) ? 0 : getTeletextSpacing().hashCode()); hashCode = prime * hashCode + ((getXPosition() == null) ? 0 : getXPosition().hashCode()); hashCode = prime * hashCode + ((getYPosition() == null) ? 0 : getYPosition().hashCode()); return hashCode; } @Override public BurninDestinationSettings clone() { try { return (BurninDestinationSettings) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.mediaconvert.model.transform.BurninDestinationSettingsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
9240c09587da39f63331d354780d2c91ef38bb71
1,866
java
Java
tricks/src/main/java/com/georgecurington/functionalstudymod/concurrent/trieber/TrieberStack.java
sidhartha11/InterviewTricks
57f3228629c92ae9beea8538796c8122c77472cb
[ "Apache-2.0" ]
null
null
null
tricks/src/main/java/com/georgecurington/functionalstudymod/concurrent/trieber/TrieberStack.java
sidhartha11/InterviewTricks
57f3228629c92ae9beea8538796c8122c77472cb
[ "Apache-2.0" ]
null
null
null
tricks/src/main/java/com/georgecurington/functionalstudymod/concurrent/trieber/TrieberStack.java
sidhartha11/InterviewTricks
57f3228629c92ae9beea8538796c8122c77472cb
[ "Apache-2.0" ]
null
null
null
28.707692
78
0.61522
1,001,652
package com.georgecurington.functionalstudymod.concurrent.trieber; import java.util.concurrent.atomic.AtomicReference; import com.georgecurington.functionalstudymod.concurrent.threads.ThreadSafe; /** * <pre> * This code was taken from JDK source to demonstrate the use of a thread safe * stack that uses CAS to prevent multiple threads from causing issues when * processing the stack. * Note the use of AtomicReference<Node<E>> top; Used to always point to * the top of the stack. AtomicReference items can be updated atomically. * </pre> * @since Dec 25 2017 * @version 1.0 * * @see https://en.wikipedia.org/wiki/Treiber_Stack * @param <E> */ @ThreadSafe public class TrieberStack <E> { AtomicReference<Node<E>> top = new AtomicReference<Node<E>>(); public void push(E item) { Node<E> newHead = new Node<E>(item); Node<E> oldHead; do { oldHead = top.get(); newHead.next = oldHead; } while (!top.compareAndSet(oldHead, newHead)); } public E pop() { Node<E> oldHead; Node<E> newHead; do { oldHead = top.get(); if (oldHead == null) return null; newHead = oldHead.next; } while (!top.compareAndSet(oldHead, newHead)); return oldHead.item; } /** * <pre> * Generic Node class that is used as an element in the * ThreadSafe Treiber Stack implementation. This is an immutable * class that can only be constructed via its Constructor. Note * that the E item is final. The Node<E> next field is used to point down * into the stack. * </pre> * * @param <E> */ private static class Node <E> { public final E item; public Node<E> next; public Node(E item) { this.item = item; } } }
9240c0fa789f93466a86fa9ecf2a476c6de75ce5
2,763
java
Java
src/main/java/com/byteperceptions/require/strategy/scenario/purchasestocks/PurchaseScenarioHaveFourStockMajorityLead.java
rylitalo/RequireOne
fb9d9883b1a916b41477b8ce7ad1e430772ee78d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/byteperceptions/require/strategy/scenario/purchasestocks/PurchaseScenarioHaveFourStockMajorityLead.java
rylitalo/RequireOne
fb9d9883b1a916b41477b8ce7ad1e430772ee78d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/byteperceptions/require/strategy/scenario/purchasestocks/PurchaseScenarioHaveFourStockMajorityLead.java
rylitalo/RequireOne
fb9d9883b1a916b41477b8ce7ad1e430772ee78d
[ "Apache-2.0" ]
null
null
null
34.974684
131
0.750271
1,001,653
/** Copyright Ryan Ylitalo and BytePerceptions LLC. * * 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.byteperceptions.require.strategy.scenario.purchasestocks; import com.byteperceptions.require.model.HotelChain; import com.byteperceptions.require.model.Player; import com.byteperceptions.require.registry.PlayerRegistry; /** * @author Ryan Ylitalo * */ public class PurchaseScenarioHaveFourStockMajorityLead implements PurchaseScenario { @Override public int calculateValue(Player player, HotelChain hotelChain, int sharesLeftToPurchaseThisTurn) { if (isPlayerInScenario(player, hotelChain, sharesLeftToPurchaseThisTurn)) { return -5; } return 0; } @Override public boolean isPlayerInScenario(Player player, HotelChain hotelChain, int sharesLeftToPurchaseThisTurn) { //Returns true if there is one player or less who is closer than 4 stocks on the count. IE: Determines the lead //for both minority and majority. int countOfPlayersCloserThan4Stocks = 0; if(!hotelChain.getMajorityStockHolders().contains(player) || hotelChain.getMajorityStockHolders().size() > 1){ return false; } for(Player gamePlayer: PlayerRegistry.getInstance().getAllPlayers()){ if(gamePlayer.equals(player)){ continue; } if(gamePlayer.getStockRegistry().getNumberOfShares(hotelChain) > (player.getStockRegistry().getNumberOfShares(hotelChain) - 4)){ countOfPlayersCloserThan4Stocks++; } } return countOfPlayersCloserThan4Stocks <= 1; } // private boolean has4StockLeadForMajority(Player player, HotelChain hotelChain){ // return hotelChain.getMajorityStockHolders().contains(player) && hotelChain.getMajorityStockHolders().size() == 1 && // hotelChain.getNumberOfStocksForMinority() < (player.getStockRegistry().getNumberOfShares(hotelChain) - 3); // } // // private boolean has4StockLeadForMinority(Player player, HotelChain hotelChain){ // return hotelChain.getMinorityStockHolders().contains(player) && hotelChain.getMajorityStockHolders().size() == 1 && // hotelChain.getMinorityStockHolders().size() == 1 && // hotelChain.getNumberOfStocksForMinority() < (player.getStockRegistry().getNumberOfShares(hotelChain) - 3); // } }
9240c347e628019c900634ccdd281d6d5a756fdc
2,541
java
Java
algorithm-study/src/main/java/org/woodwhale/code/chapter_9_others/Problem_22_CandyProblem.java
woodwhales/woodwhales-study
73aac22431fc1271a69bf5bd61b976c4e1cb628e
[ "WTFPL" ]
1
2019-05-09T07:59:45.000Z
2019-05-09T07:59:45.000Z
algorithm-study/src/main/java/org/woodwhale/code/chapter_9_others/Problem_22_CandyProblem.java
woodwhales/woodwhales-study
73aac22431fc1271a69bf5bd61b976c4e1cb628e
[ "WTFPL" ]
3
2021-12-14T22:00:28.000Z
2022-01-04T16:55:52.000Z
algorithm-study/src/main/java/org/woodwhale/code/chapter_9_others/Problem_22_CandyProblem.java
woodwhales/woodwhales-study
73aac22431fc1271a69bf5bd61b976c4e1cb628e
[ "WTFPL" ]
3
2019-05-09T07:59:46.000Z
2020-03-29T11:49:32.000Z
22.095652
72
0.532074
1,001,655
package org.woodwhale.code.chapter_9_others; public class Problem_22_CandyProblem { public static int candy1(int[] arr) { if (arr == null || arr.length == 0) { return 0; } int index = nextMinIndex1(arr, 0); int res = rightCands(arr, 0, index++); int lbase = 1; int next = 0; int rcands = 0; int rbase = 0; while (index != arr.length) { if (arr[index] > arr[index - 1]) { res += ++lbase; index++; } else if (arr[index] < arr[index - 1]) { next = nextMinIndex1(arr, index - 1); rcands = rightCands(arr, index - 1, next++); rbase = next - index + 1; res += rcands + (rbase > lbase ? -lbase : -rbase); lbase = 1; index = next; } else { res += 1; lbase = 1; index++; } } return res; } public static int nextMinIndex1(int[] arr, int start) { for (int i = start; i != arr.length - 1; i++) { if (arr[i] <= arr[i + 1]) { return i; } } return arr.length - 1; } public static int rightCands(int[] arr, int left, int right) { int n = right - left + 1; return n + n * (n - 1) / 2; } public static int candy2(int[] arr) { if (arr == null || arr.length == 0) { return 0; } int index = nextMinIndex2(arr, 0); int[] data = rightCandsAndBase(arr, 0, index++); int res = data[0]; int lbase = 1; int same = 1; int next = 0; while (index != arr.length) { if (arr[index] > arr[index - 1]) { res += ++lbase; same = 1; index++; } else if (arr[index] < arr[index - 1]) { next = nextMinIndex2(arr, index - 1); data = rightCandsAndBase(arr, index - 1, next++); if (data[1] <= lbase) { res += data[0] - data[1]; } else { res += -lbase * same + data[0] - data[1] + data[1] * same; } index = next; lbase = 1; same = 1; } else { res += lbase; same++; index++; } } return res; } public static int nextMinIndex2(int[] arr, int start) { for (int i = start; i != arr.length - 1; i++) { if (arr[i] < arr[i + 1]) { return i; } } return arr.length - 1; } public static int[] rightCandsAndBase(int[] arr, int left, int right) { int base = 1; int cands = 1; for (int i = right - 1; i >= left; i--) { if (arr[i] == arr[i + 1]) { cands += base; } else { cands += ++base; } } return new int[] { cands, base }; } public static void main(String[] args) { int[] test1 = { 3, 0, 5, 5, 4, 4, 0 }; System.out.println(candy1(test1)); int[] test2 = { 3, 0, 5, 5, 4, 4, 0 }; System.out.println(candy2(test2)); } }
9240c3d25dd8b4f148a79415aa055548bbe60bd3
734
java
Java
kedamall-product/src/main/java/com/example/kedamall/product/vo/SkuItemVo.java
AaronXu296/kedamall
2aac84721de8d64b530caec91bc589ba64910faf
[ "Apache-2.0" ]
null
null
null
kedamall-product/src/main/java/com/example/kedamall/product/vo/SkuItemVo.java
AaronXu296/kedamall
2aac84721de8d64b530caec91bc589ba64910faf
[ "Apache-2.0" ]
2
2021-04-22T17:12:18.000Z
2021-06-04T03:02:46.000Z
kedamall-product/src/main/java/com/example/kedamall/product/vo/SkuItemVo.java
AaronXu296/kedamall
2aac84721de8d64b530caec91bc589ba64910faf
[ "Apache-2.0" ]
null
null
null
22.9375
61
0.758856
1,001,656
package com.example.kedamall.product.vo; import com.example.kedamall.product.entity.SkuImagesEntity; import com.example.kedamall.product.entity.SkuInfoEntity; import com.example.kedamall.product.entity.SpuInfoDescEntity; import lombok.Data; import java.util.List; @Data public class SkuItemVo { //1、sku基本信息的获取 pms_sku_info private SkuInfoEntity info; private boolean hasStock = true; //2、sku的图片信息 pms_sku_images private List<SkuImagesEntity> images; //3、获取spu的销售属性组合 private List<SkuItemSaleAttrVo> saleAttr; //4、获取spu的介绍 private SpuInfoDescEntity desc; //5、获取spu的规格参数信息 private List<SpuItemAttrGroupVo> groupAttrs; //6、秒杀商品的优惠信息 private SeckillInfoVo seckillInfoVo; }
9240c5680305eae2609fdbd93a214313b9c8cad5
22,068
java
Java
namba-core/src/main/java/io/namba/arrays/DateTimeArray.java
ernest-kiwele/namba
f171a54aa52d2b1f912f0f09836a33a78a8b2def
[ "Apache-2.0" ]
null
null
null
namba-core/src/main/java/io/namba/arrays/DateTimeArray.java
ernest-kiwele/namba
f171a54aa52d2b1f912f0f09836a33a78a8b2def
[ "Apache-2.0" ]
null
null
null
namba-core/src/main/java/io/namba/arrays/DateTimeArray.java
ernest-kiwele/namba
f171a54aa52d2b1f912f0f09836a33a78a8b2def
[ "Apache-2.0" ]
null
null
null
30.522822
116
0.701921
1,001,657
/** * Copyright 2018 eussence.com and contributors * 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 io.namba.arrays; import java.time.DayOfWeek; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.Period; import java.time.Year; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.commons.lang3.StringUtils; import io.namba.arrays.data.tuple.Two; /** * * @author Ernest Kiwele * */ public class DateTimeArray extends DataList<LocalDateTime> { private static final DateTimeFormatter DAY_NAME_FORMATTER = DateTimeFormatter.ofPattern("EEEE"); private static final DateTimeFormatter SHORT_DAY_NAME_FORMATTER = DateTimeFormatter.ofPattern("EEEE"); private static final Map<Integer, DateTimeFormatter> FORMATTERS = Map.of(4, DateTimeFormatter.ofPattern("yyyy"), 6, DateTimeFormatter.ofPattern("yyyyMM"), 8, DateTimeFormatter.ofPattern("yyyyMMdd"), 10, DateTimeFormatter.ofPattern("yyyyMMddHH"), 12, DateTimeFormatter.ofPattern("yyyyMMddHHmm"), 14, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")); private DateTimeArray(List<LocalDateTime> is) { super(DataType.DATETIME, is); } private DateTimeArray(DataList<LocalDateTime> is) { super(DataType.DATETIME, is.value); } public static DateTimeArray of(List<LocalDateTime> dt) { return new DateTimeArray(dt); } public static DateTimeArray of(LocalDateTime... dt) { return new DateTimeArray(Arrays.asList(dt)); } public static DateTimeArray daysBetween(LocalDateTime from, LocalDateTime to) { return between(from, to, ChronoUnit.DAYS); } public static DateTimeArray hoursBetween(LocalDateTime from, LocalDateTime to) { return between(from, to, ChronoUnit.HOURS); } public static DateTimeArray minutesBetween(LocalDateTime from, LocalDateTime to) { return between(from, to, ChronoUnit.MINUTES); } public static DateTimeArray secondsBetween(LocalDateTime from, LocalDateTime to) { return between(from, to, ChronoUnit.SECONDS); } public static DateTimeArray millisecondsBetween(LocalDateTime from, LocalDateTime to) { return between(from, to, ChronoUnit.MILLIS); } public static DateTimeArray weeksBetween(LocalDateTime from, LocalDateTime to) { return between(from, to, ChronoUnit.WEEKS); } public static DateTimeArray monthsBetween(LocalDateTime from, LocalDateTime to) { return between(from, to, ChronoUnit.MONTHS); } public static DateTimeArray yearsBetween(LocalDateTime from, LocalDateTime to) { return between(from, to, ChronoUnit.YEARS); } public static DateTimeArray between(LocalDateTime from, LocalDateTime to, ChronoUnit unit) { List<LocalDateTime> dt = new ArrayList<>(); LocalDateTime start = Objects.requireNonNull(from, "from date is null"); LocalDateTime end = Objects.requireNonNull(to, "to date is null"); if (start.isBefore(end)) { while (start.isBefore(end)) { dt.add(start); start = start.plus(1, unit); } } else { while (start.isAfter(end)) { dt.add(start); start = start.minus(1, unit); } } return new DateTimeArray(dt); } public static DateTimeArray daysSeries(LocalDateTime from, int count, long interval) { return series(from, count, interval, ChronoUnit.DAYS); } public static DateTimeArray hoursSeries(LocalDateTime from, int count, long interval) { return series(from, count, interval, ChronoUnit.HOURS); } public static DateTimeArray minutesSeries(LocalDateTime from, int count, long interval) { return series(from, count, interval, ChronoUnit.MINUTES); } public static DateTimeArray secondsSeries(LocalDateTime from, int count, long interval) { return series(from, count, interval, ChronoUnit.SECONDS); } public static DateTimeArray millisecondsSeries(LocalDateTime from, int count, long interval) { return series(from, count, interval, ChronoUnit.MILLIS); } public static DateTimeArray monthsSeries(LocalDateTime from, int count, long interval) { return series(from, count, interval, ChronoUnit.MONTHS); } public static DateTimeArray weeksSeries(LocalDateTime from, int count, long interval) { return series(from, count, interval, ChronoUnit.WEEKS); } public static DateTimeArray yearsSeries(LocalDateTime from, int count, long interval) { return series(from, count, interval, ChronoUnit.YEARS); } public static DateTimeArray series(LocalDateTime from, int count, long interval, ChronoUnit unit) { LocalDateTime start = Objects.requireNonNull(from, "from date may not be null"); if (count < 1) { throw new IllegalArgumentException("count must be greater than 0"); } if (interval == 0) { throw new IllegalArgumentException("step may not be 0"); } List<LocalDateTime> dt = new ArrayList<>(); for (int i = 0; i < count; i++) { dt.add(start); start = start.plus(interval, unit); } return new DateTimeArray(dt); } public static DateTimeArray linearFit(LocalDateTime from, LocalDateTime to, long ticks) { List<LocalDateTime> dt = new ArrayList<>(); LocalDateTime start = Objects.requireNonNull(from, "from date is null"); LocalDateTime end = Objects.requireNonNull(to, "to date is null"); if (ticks < 1) { throw new IllegalArgumentException("ticks must be >= 1"); } long nanos = Math.abs((long) (ChronoUnit.NANOS.between(from, to) / (double) ticks)); if (start.isBefore(end)) { while (start.isBefore(end)) { dt.add(start); start = start.plusNanos(nanos); } } else { while (start.isAfter(end)) { dt.add(start); start = start.minusNanos(nanos); } } return new DateTimeArray(dt); } public static DateTimeArray parse(StringList dates, String pattern) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); return new DateTimeArray( dates.stream().map(s -> LocalDateTime.parse(s, formatter)).collect(Collectors.toList())); } public DataList<LocalDate> date() { List<LocalDate> dates = new ArrayList<>(); for (LocalDateTime ldt : this.value) { dates.add(null == ldt ? null : ldt.toLocalDate()); } return new DataList<>(DataType.DATE, dates); } public DataList<LocalTime> time() { List<LocalTime> dates = new ArrayList<>(); for (LocalDateTime ldt : this.value) { dates.add(null == ldt ? null : ldt.toLocalTime()); } return new DataList<>(DataType.TIME, dates); } public IntList year() { return IntList.of(this.value.stream().mapToInt(LocalDateTime::getYear).toArray()); } public IntList month() { return IntList.of(this.value.stream().mapToInt(LocalDateTime::getMonthValue).toArray()); } public IntList day() { return IntList.of(this.value.stream().mapToInt(LocalDateTime::getDayOfMonth).toArray()); } public StringList dayName() { return StringList.of(this.stream().map(dt -> null == dt ? null : dt.format(DAY_NAME_FORMATTER)) .collect(Collectors.toList())); } public StringList dayName(String langTag) { return StringList.of(this.stream() .map(dt -> null == dt ? null : dt.format(DateTimeFormatter.ofPattern("EEEE", Locale.forLanguageTag(langTag)))) .collect(Collectors.toList())); } public StringList shortDayName() { return StringList.of(this.stream().map(dt -> null == dt ? null : dt.format(SHORT_DAY_NAME_FORMATTER)) .collect(Collectors.toList())); } public StringList shortDayName(String langTag) { return StringList.of(this.stream().map( dt -> null == dt ? null : dt.format(DateTimeFormatter.ofPattern("E", Locale.forLanguageTag(langTag)))) .collect(Collectors.toList())); } public IntList hour() { return IntList.of(this.value.stream().mapToInt(LocalDateTime::getHour).toArray()); } public IntList minute() { return IntList.of(this.value.stream().mapToInt(LocalDateTime::getMinute).toArray()); } public IntList second() { return IntList.of(this.value.stream().mapToInt(LocalDateTime::getSecond).toArray()); } public IntList nanosecond() { return IntList.of(this.value.stream().mapToInt(LocalDateTime::getNano).toArray()); } public IntList dayOfWeek() { return IntList.of(this.value.stream().mapToInt(d -> d.getDayOfWeek().getValue()).toArray()); } public DataList<DayOfWeek> dayOfWeekName() { return new DataList<>(DataType.OBJECT, this.value.stream().map(LocalDateTime::getDayOfWeek).collect(Collectors.toList())); } public IntList weekDay() { return this.dayOfWeek(); } public IntList dayOfYear() { return IntList.of(this.value.stream().mapToInt(LocalDateTime::getDayOfYear).toArray()); } public IntList quarter() { return IntList.of(this.value.stream().mapToInt(LocalDateTime::getMonthValue).map(i -> 1 + i / 4).toArray()); } public Mask isLeapYear() { boolean[] a = new boolean[this.value.size()]; for (int i = 0; i < this.value.size(); i++) { if (null == this.value.get(i)) continue; a[i] = Year.isLeap(this.value.get(i).getYear()); } return Mask.of(a); } // TODO: Implement // public DateTimeArray ceilTo(String precision) { // return this.ceilTo( // ChronoUnit.valueOf(Objects.requireNonNull(precision, "precision cannot be // null").toUpperCase())); // } // public DateTimeArray ceilTo(ChronoUnit precision) { // } public DateTimeArray truncateTo(String precision) { return this.truncateTo( ChronoUnit.valueOf(Objects.requireNonNull(precision, "precision cannot be null").toUpperCase())); } public DateTimeArray truncateTo(ChronoUnit precision) { List<LocalDateTime> res = new ArrayList<>(); for (LocalDateTime ldt : this.value) { res.add(null == ldt ? null : ldt.truncatedTo(precision)); } return new DateTimeArray(res); } public Mask slice(LocalDateTime dateTime, ChronoUnit precision) { LocalDateTime comp = Objects.requireNonNull(dateTime, "date may not be blank").truncatedTo(precision); return Mask .of(this.value.stream().map(dt -> dt == null ? Boolean.FALSE : comp.equals(dt.truncatedTo(precision))) .toArray(i -> new Boolean[i])); } public Mask slice(String dt) { String date = dt.replaceAll("[^0-9]", ""); DateTimeFormatter formatter = FORMATTERS.get(date.length()); if (null == formatter) { throw new IllegalArgumentException("Unsupported slicing pattern: '" + dt + "'"); } return Mask.of(this.value.stream().map(ldt -> ldt == null ? Boolean.FALSE : date.equals(ldt.format(formatter))) .toArray(i -> new Boolean[i])); } public Mask slice(LocalDateTime from, LocalDateTime to) { Objects.requireNonNull(from); Objects.requireNonNull(to); return Mask.of(this.value.stream() .map(ldt -> ldt == null ? Boolean.FALSE : (from.isBefore(ldt) || from.equals(ldt)) && (to.isAfter(ldt) || to.equals(ldt))) .toArray(i -> new Boolean[i])); } public Mask slice(LocalDate dt) { Objects.requireNonNull(dt); return Mask.of(this.value.stream().map(ldt -> ldt == null ? Boolean.FALSE : (dt.equals(ldt.toLocalDate()))) .toArray(i -> new Boolean[i])); } public Mask slice(LocalDate dt, ChronoUnit precision) { return this.slice(LocalDateTime.of(dt, LocalTime.MIDNIGHT), precision); } public DateTimeArray plus(int days) { List<LocalDateTime> res = new ArrayList<>(); for (LocalDateTime ldt : this.value) { res.add(null == ldt ? null : ldt.plusDays(days)); } return new DateTimeArray(res); } public DateTimeArray plus(IntList days) { if (this.size() != days.size()) { throw new IllegalArgumentException("arrays are of different sizes"); } List<LocalDateTime> res = new ArrayList<>(); for (int i = 0; i < this.size(); i++) { res.add(null == this.value.get(i) ? null : this.value.get(i).plusDays(days.getAt(i))); } return new DateTimeArray(res); } public DateTimeArray plus(Duration d) { List<LocalDateTime> res = new ArrayList<>(); for (LocalDateTime ldt : this.value) { res.add(null == ldt ? null : ldt.plus(d)); } return new DateTimeArray(res); } public DateTimeArray plus(DataList<Duration> d) { if (this.size() != d.size()) { throw new IllegalArgumentException("arrays are of different sizes"); } List<LocalDateTime> res = new ArrayList<>(); for (int i = 0; i < this.size(); i++) { res.add(null == this.value.get(i) ? null : this.value.get(i).plus(d.getAt(i))); } return new DateTimeArray(res); } public DateTimeArray plus(Period p) { List<LocalDateTime> res = new ArrayList<>(); for (LocalDateTime ldt : this.value) { res.add(null == ldt ? null : ldt.plus(p)); } return new DateTimeArray(res); } public DateTimeArray minus(int days) { return this.plus(-days); } public DateTimeArray minus(IntList days) { if (this.size() != days.size()) { throw new IllegalArgumentException("arrays are of different sizes"); } List<LocalDateTime> res = new ArrayList<>(); for (int i = 0; i < this.size(); i++) { res.add(null == this.value.get(i) ? null : this.value.get(i).minusDays(days.getAt(i))); } return new DateTimeArray(res); } public DateTimeArray minus(Duration d) { List<LocalDateTime> res = new ArrayList<>(); for (LocalDateTime ldt : this.value) { res.add(null == ldt ? null : ldt.minus(d)); } return new DateTimeArray(res); } public DateTimeArray minus(Period p) { List<LocalDateTime> res = new ArrayList<>(); for (LocalDateTime ldt : this.value) { res.add(null == ldt ? null : ldt.minus(p)); } return new DateTimeArray(res); } public DateTimeArray minus(DataList<Duration> d) { if (this.size() != d.size()) { throw new IllegalArgumentException("arrays are of different sizes"); } List<LocalDateTime> res = new ArrayList<>(); for (int i = 0; i < this.size(); i++) { res.add(null == this.value.get(i) ? null : this.value.get(i).minus(d.getAt(i))); } return new DateTimeArray(res); } public IntList minus(LocalDateTime date) { // TODO: use long array for this and remove cast return IntList.of(this.value.stream().mapToInt(v -> (int) ChronoUnit.DAYS.between(v, date)).toArray()); } public IntList minus(DateTimeArray date) { if (this.size() != date.size()) { throw new IllegalArgumentException("arrays are of different sizes"); } // TODO: use long array for this and remove cast return IntList.of(IntStream.range(0, this.value.size()) .map(i -> (int) ChronoUnit.DAYS.between(this.value.get(i), date.value.get(i))).toArray()); } public IntList minus(LocalDateTime date, ChronoUnit unit) { // TODO: use long array for this and remove cast return IntList.of(this.value.stream().mapToInt(v -> (int) unit.between(v, date)).toArray()); } public IntList minus(DateTimeArray date, ChronoUnit unit) { if (this.size() != date.size()) { throw new IllegalArgumentException("arrays are of different sizes"); } // TODO: use long array for this and remove cast return IntList.of(IntStream.range(0, this.value.size()) .map(i -> (int) unit.between(this.value.get(i), date.value.get(i))).toArray()); } public IntList minus(LocalDateTime date, String unit) { return this.minus(date, ChronoUnit.valueOf(StringUtils.upperCase(unit))); } public IntList minus(DateTimeArray date, String unit) { return this.minus(date, ChronoUnit.valueOf(StringUtils.upperCase(unit))); } public StringList toIsoDate() { return StringList.of(this.map(DateTimeFormatter.ISO_DATE::format).value); } public StringList toIsoTime() { return StringList.of(this.map(DateTimeFormatter.ISO_TIME::format).value); } public StringList toIsoDateTime() { return StringList.of(this.map(DateTimeFormatter.ISO_DATE_TIME::format).value); } public StringList format() { return this.toIsoDateTime(); } public StringList format(String pattern) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); return StringList.of(this.map(formatter::format).value); } /* * Return a Dataframe of the components of the Timedeltas (a DF with columns * like days hours minutes seconds milliseconds microseconds nanoseconds). */ // TODO: implement // public Table components() { // // } public IntList daysInMonth() { int[] v = new int[size()]; for (int i = 0; i < v.length; i++) { LocalDateTime ldt = this.getAt(i); v[i] = null == ldt ? -1 : ldt.getMonth().length(Year.isLeap(ldt.getYear())); } return IntList.of(v); } public Mask isMonthEnd() { boolean[] v = new boolean[size()]; for (int i = 0; i < v.length; i++) { LocalDateTime ldt = this.getAt(i); v[i] = null != ldt && ldt.getDayOfMonth() == ldt.getMonth().length(Year.isLeap(ldt.getYear())); } return Mask.of(v); } public Mask isMonthStart() { boolean[] v = new boolean[size()]; for (int i = 0; i < v.length; i++) { LocalDateTime ldt = this.getAt(i); v[i] = null != ldt && ldt.getDayOfMonth() == 1; } return Mask.of(v); } public Mask isQuarterStart() { boolean[] v = new boolean[size()]; for (int i = 0; i < v.length; i++) { LocalDateTime ldt = this.getAt(i); v[i] = null != ldt && ldt.getMonth().firstMonthOfQuarter() == ldt.getMonth() && ldt.getDayOfMonth() == 1; } return Mask.of(v); } public Mask isQuarterEnd() { boolean[] v = new boolean[size()]; for (int i = 0; i < v.length; i++) { LocalDateTime ldt = this.getAt(i); v[i] = null != ldt && ldt.getMonth().firstMonthOfQuarter().getValue() + 2 == ldt.getMonth().getValue() && ldt.getDayOfMonth() == ldt.getMonth().length(Year.isLeap(ldt.getYear())); } return Mask.of(v); } public Mask isYearStart() { boolean[] v = new boolean[size()]; for (int i = 0; i < v.length; i++) { LocalDateTime ldt = this.getAt(i); v[i] = null != ldt && ldt.getMonth() == Month.JANUARY && 1 == ldt.getDayOfMonth(); } return Mask.of(v); } public Mask isYearEnd() { boolean[] v = new boolean[size()]; for (int i = 0; i < v.length; i++) { LocalDateTime ldt = this.getAt(i); v[i] = null != ldt && ldt.getMonth() == Month.DECEMBER && 31 == ldt.getDayOfMonth(); } return Mask.of(v); } // Agg public LocalDateTime min() { return this.stream().filter(Objects::nonNull).min(Comparator.naturalOrder()).orElse(null); } public LocalDateTime max() { return this.stream().filter(Objects::nonNull).max(Comparator.naturalOrder()).orElse(null); } // public Map<LocalDateTime, int[]> groupBy(ChronoUnit frequency, LocalDateTime offset) { return this.groupBy(frequency.getDuration(), offset); } public Map<LocalDateTime, int[]> groupBy(ChronoUnit frequency) { return this.groupBy(frequency, this.min()); } public Map<LocalDateTime, int[]> groupBy(Duration duration, LocalDateTime offset) { return IntStream.range(0, this.size()).mapToObj(i -> Two.of(this.groupKey(offset, this.getAt(i), duration), i)) .collect(Collectors.groupingBy(Two::a, Collectors.mapping(Two::b, Collectors .collectingAndThen(Collectors.toList(), l -> l.stream().mapToInt(v -> v).toArray())))); } public Map<LocalDateTime, int[]> groupBy(Duration duration) { return this.groupBy(duration, this.min()); } public Map<LocalDateTime, List<LocalDateTime>> groupValuesBy(ChronoUnit frequency, LocalDateTime offset) { return stream().collect(Collectors.groupingBy(e -> this.groupKey(offset, e, frequency), Collectors.toList())); } public Map<LocalDateTime, List<LocalDateTime>> groupValuesBy(ChronoUnit frequency) { return this.groupValuesBy(frequency, this.min()); } public Map<LocalDateTime, List<LocalDateTime>> groupValuesBy(Duration duration, LocalDateTime offset) { return stream().collect(Collectors.groupingBy(e -> this.groupKey(offset, e, duration), Collectors.toList())); } public Map<LocalDateTime, List<LocalDateTime>> groupValuesBy(Duration duration) { return this.groupValuesBy(duration, this.min()); } private LocalDateTime groupKey(LocalDateTime base, LocalDateTime dt, Duration d) { return dt.minus(ChronoUnit.NANOS.between(base, dt) % d.toNanos(), ChronoUnit.NANOS); } private LocalDateTime groupKey(LocalDateTime base, LocalDateTime dt, ChronoUnit unit) { // this is based on the flooring of the diff returned by unit.between. return base.plus(unit.between(base, dt), unit); } /** * difference between previous row and current row. * * @param unit * @return */ public LongList diff(ChronoUnit unit) { DataList<LocalDateTime> oneOff = this.shift(); DataList<Long> lst = this.zipTo(oneOff, unit::between); return lst.asLong(); } public LongList diff(String unit) { return this.diff(ChronoUnit.valueOf(unit)); } /* * Select final periods of time series data based on a date offset. * * When having a DataFrame with dates as index, this function can select the * last few rows based on a date offset. */ // TODO: evaluate and/or implement // public DateTimeArray last(LocalDateTime offset) { // // } // public DateTimeArray shift(ChronoUnit unit, long value) { // // } // public DateTimeArray shift(ChronoUnit unit) { // return this.shift(unit, 1L); // } public static void main(String[] args) { DateTimeArray dta = DateTimeArray.linearFit(LocalDateTime.of(LocalDate.of(2016, 10, 12), LocalTime.MIDNIGHT), LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MIDNIGHT), 8).plus(Duration.ofDays(5)); System.out.println(dta); System.out.println(); System.out.println( dta.groupValuesBy(ChronoUnit.YEARS, LocalDateTime.of(LocalDate.of(2016, 1, 1), LocalTime.MIDNIGHT))); } }
9240c6f6468d7c2be89667ddd70f820b78c7e979
378
java
Java
pack-with-assembly-tomcat/src/main/java/main/MainClass.java
vindell/pack-with-assembly
bb77aa54a3fc8401d27580650f5403a462169dc7
[ "Apache-2.0" ]
null
null
null
pack-with-assembly-tomcat/src/main/java/main/MainClass.java
vindell/pack-with-assembly
bb77aa54a3fc8401d27580650f5403a462169dc7
[ "Apache-2.0" ]
null
null
null
pack-with-assembly-tomcat/src/main/java/main/MainClass.java
vindell/pack-with-assembly
bb77aa54a3fc8401d27580650f5403a462169dc7
[ "Apache-2.0" ]
null
null
null
16.434783
64
0.642857
1,001,658
package main; import service.FileLogger; /** * 程序主入口 * * @author mason * */ public class MainClass { public static void main(String[] args) { //日志输出到程序根目录(classpath) String workDir = FileLogger.class.getResource("/").getPath(); System.setProperty("WORKDIR", workDir); FileLogger logger = new FileLogger(); logger.logInfo2file(); } }
9240c6f752563fc87f2a527ff07c9857282f133b
732
java
Java
valda-json/src/main/java/at/yawk/valda/ir/json/DexJson.java
Valda-IR/Valda-IR
4b014997036782a9cf5919e22c1b5bad2be0296f
[ "Apache-2.0" ]
1
2018-11-14T06:13:25.000Z
2018-11-14T06:13:25.000Z
valda-json/src/main/java/at/yawk/valda/ir/json/DexJson.java
Valda-IR/Valda-IR
4b014997036782a9cf5919e22c1b5bad2be0296f
[ "Apache-2.0" ]
null
null
null
valda-json/src/main/java/at/yawk/valda/ir/json/DexJson.java
Valda-IR/Valda-IR
4b014997036782a9cf5919e22c1b5bad2be0296f
[ "Apache-2.0" ]
null
null
null
28.153846
95
0.73224
1,001,659
package at.yawk.valda.ir.json; import at.yawk.valda.ir.Classpath; import com.fasterxml.jackson.databind.DatabindContext; import lombok.NonNull; import lombok.experimental.UtilityClass; /** * @author yawkat */ @UtilityClass public final class DexJson { public static final Object CLASSPATH_ATTRIBUTE_KEY = new Object(); @NonNull public static Classpath getClasspath(DatabindContext ctx) { Object cp = ctx.getAttribute(CLASSPATH_ATTRIBUTE_KEY); if (cp == null) { throw new IllegalStateException("CLASSPATH_ATTRIBUTE_KEY not set"); } return (Classpath) cp; } public static void popMethodState(DatabindContext ctx) { ctx.setAttribute(TrySerializer.TryHolder.KEY, null); } }
9240c724d5f9f56d30744fadc40cd939cf985b1f
2,666
java
Java
src/main/java/com/runescape/game/content/global/miniquest/MiniquestController.java
openrsx/open667-server
c90e3dfcb0af3d42b392a931a69f7b8e753da878
[ "CC0-1.0" ]
1
2021-08-18T15:58:17.000Z
2021-08-18T15:58:17.000Z
src/main/java/com/runescape/game/content/global/miniquest/MiniquestController.java
openrsx/open667-server
c90e3dfcb0af3d42b392a931a69f7b8e753da878
[ "CC0-1.0" ]
null
null
null
src/main/java/com/runescape/game/content/global/miniquest/MiniquestController.java
openrsx/open667-server
c90e3dfcb0af3d42b392a931a69f7b8e753da878
[ "CC0-1.0" ]
1
2022-02-22T17:53:31.000Z
2022-02-22T17:53:31.000Z
21.691057
80
0.674663
1,001,660
package com.runescape.game.content.global.miniquest; import com.runescape.game.interaction.controllers.Controller; import com.runescape.game.world.WorldTile; import com.runescape.game.world.entity.masks.Animation; import com.runescape.game.world.region.RegionBuilder; import com.runescape.workers.game.core.CoresManager; import com.runescape.workers.tasks.WorldTask; import com.runescape.workers.tasks.WorldTasksManager; import java.util.concurrent.TimeUnit; /** * @author Tyluur<[email protected]> * @since May 17, 2015 */ public abstract class MiniquestController extends Controller { @Override public void magicTeleported(int type) { leave(false); } @Override public boolean login() { leave(true); return true; } @Override public boolean logout() { leave(true); return true; } @Override public void forceClose() { leave(false); } /** * Handling the removing of the dynamic region */ public void removeRegion() { CoresManager.schedule(() -> { try { RegionBuilder.destroyMap(boundChunks[0], boundChunks[1], 8, 8); } catch (Exception e) { e.printStackTrace(); } }, 1200, TimeUnit.MILLISECONDS); } @Override public boolean sendDeath() { player.getLockManagement().lockAll(7000); player.stopAll(); WorldTasksManager.schedule(new WorldTask() { int loop; @Override public void run() { if (loop == 0) { player.setNextAnimation(new Animation(836)); } else if (loop == 1) { player.getPackets().sendGameMessage("You have been defeated!"); } else if (loop == 3) { player.reset(); forceClose(); player.setNextAnimation(new Animation(-1)); } else if (loop == 4) { player.getPackets().sendMusicEffect(90); stop(); } loop++; } }, 0, 1); return false; } /** * What's done when the player leaves * * @param logout * If it is on logout */ public void leave(boolean logout) { if (logout) { player.setLocation(getLeaveTile()); } else { player.setNextWorldTile(getLeaveTile()); } removeRegion(); removeController(); } /** * Handling the creation of the dynamic region */ public abstract void createRegion(); /** * The tile that players are teleported to when they leave the miniquest */ public abstract WorldTile getLeaveTile(); /** * Gets the world tile inside the {@link #boundChunks} * * @param mapX * The x of the map * @param mapY * The y of the map */ protected WorldTile getWorldTile(int mapX, int mapY) { return new WorldTile(boundChunks[0] * 8 + mapX, boundChunks[1] * 8 + mapY, 0); } /** * The chunks for the region */ protected int[] boundChunks; }
9240c72bbe8d6250aa72f16553f431af366c2f39
1,224
java
Java
app/src/main/java/com/hhk/xyz/padc_mmnews/component/EmptyViewPod.java
htayhlaingkyaw/PADC-MMNews
c7615ae283fb5491eaadabcd0fb52730a64a05fc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/hhk/xyz/padc_mmnews/component/EmptyViewPod.java
htayhlaingkyaw/PADC-MMNews
c7615ae283fb5491eaadabcd0fb52730a64a05fc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/hhk/xyz/padc_mmnews/component/EmptyViewPod.java
htayhlaingkyaw/PADC-MMNews
c7615ae283fb5491eaadabcd0fb52730a64a05fc
[ "Apache-2.0" ]
null
null
null
22.666667
80
0.705882
1,001,661
package com.hhk.xyz.padc_mmnews.component; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.hhk.xyz.padc_mmnews.R; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by HHK on 11/25/2017. */ public class EmptyViewPod extends RelativeLayout { @BindView(R.id.iv_empty) ImageView ivEmpty; @BindView(R.id.tv_empty) TextView tvEmpty; public EmptyViewPod(Context context) { super(context); } public EmptyViewPod(Context context, AttributeSet attrs) { super(context, attrs); } public EmptyViewPod(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onFinishInflate() { super.onFinishInflate(); ButterKnife.bind(this,this); } public void setEmptyData(int emptyImageId,String emptyMsg) { ivEmpty.setImageResource(emptyImageId); tvEmpty.setText(emptyMsg); } //call method overloading public void setEmptyData(String emptyMsg) { tvEmpty.setText(emptyMsg); } }
9240c7703c2a6a76dfc07825d556177db782cfdc
160
java
Java
src/main/java/io/datakitchen/ide/editors/neweditors/palette/ComponentSource.java
Carlos-Descalzi/dkide
cc767ddb90b658ff82badb2d2c26c3ebe76c857d
[ "Apache-2.0" ]
null
null
null
src/main/java/io/datakitchen/ide/editors/neweditors/palette/ComponentSource.java
Carlos-Descalzi/dkide
cc767ddb90b658ff82badb2d2c26c3ebe76c857d
[ "Apache-2.0" ]
null
null
null
src/main/java/io/datakitchen/ide/editors/neweditors/palette/ComponentSource.java
Carlos-Descalzi/dkide
cc767ddb90b658ff82badb2d2c26c3ebe76c857d
[ "Apache-2.0" ]
null
null
null
17.777778
54
0.775
1,001,662
package io.datakitchen.ide.editors.neweditors.palette; import java.util.Map; public interface ComponentSource { Map<String, Object> getAllVariables(); }
9240c78dbf201181ce196f9479ab4e9d48974d66
1,657
java
Java
leetcode/medium/partition-labels/Solution.java
naddym/competitive-programming
8f75853aa411acb3f126387781a656e625879706
[ "Apache-2.0" ]
null
null
null
leetcode/medium/partition-labels/Solution.java
naddym/competitive-programming
8f75853aa411acb3f126387781a656e625879706
[ "Apache-2.0" ]
null
null
null
leetcode/medium/partition-labels/Solution.java
naddym/competitive-programming
8f75853aa411acb3f126387781a656e625879706
[ "Apache-2.0" ]
null
null
null
31.264151
230
0.530477
1,001,663
/** A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. Example 1: Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. Note: S will have length in range [1, 500]. S will consist of lowercase English letters ('a' to 'z') only. */ class Solution { public List<Integer> partitionLabels(String S) { List<Integer> partitions = new ArrayList<>(); if ( S == null || S.length() == 0) { return partitions; } Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < S.length(); i++) { map.put(S.charAt(i), i + 1); } int i = 0; while (i < S.length()) { char c = S.charAt(i); List<Character> charsSeen = new ArrayList<>(); charsSeen.add(c); int j = i + 1; int k = map.get(c); while (j < k) { char next = S.charAt(j); if (!charsSeen.contains(next)) { charsSeen.add(next); k = Math.max(k, map.get(next)); } j++; } partitions.add(k - i); i = k; } return partitions; } }
9240c86ab2fde97a192c2339cffaa4ff6a39c6ab
6,335
java
Java
client/src/main/java/sirs/client/SecurityLogic.java
jafonsoc/SIRS-Project
379858a4868dac12b696e25cabf7927c22442260
[ "MIT" ]
null
null
null
client/src/main/java/sirs/client/SecurityLogic.java
jafonsoc/SIRS-Project
379858a4868dac12b696e25cabf7927c22442260
[ "MIT" ]
null
null
null
client/src/main/java/sirs/client/SecurityLogic.java
jafonsoc/SIRS-Project
379858a4868dac12b696e25cabf7927c22442260
[ "MIT" ]
null
null
null
43.095238
198
0.729913
1,001,664
package sirs.client; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import javax.net.ssl.SSLException; import java.io.*; import java.math.BigInteger; import java.security.KeyPair; import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.security.GeneralSecurityException; import java.security.Signature; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.KeyPairGenerator; import java.security.KeyFactory; import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.sql.Date; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; public class SecurityLogic { public static void createKeystore(String username, char[] password, PrivateKey privKey, Certificate cert) throws IOException, FileNotFoundException, GeneralSecurityException, KeyStoreException { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setKeyEntry("auth", privKey, password, new Certificate[] {cert}); FileOutputStream fos = new FileOutputStream(username + ".ks"); keystore.store(fos, password); fos.close(); } public static Pair<PrivateKey, Certificate> generateCertificate() throws GeneralSecurityException, OperatorCreationException { String bc = BouncyCastleProvider.PROVIDER_NAME; Security.addProvider(new BouncyCastleProvider()); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", bc); keyPairGenerator.initialize(4096); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500Name dnName = new X500Name("CN=sirs"); BigInteger certSerialNumber = BigInteger.valueOf(System.currentTimeMillis()); String signatureAlgorithm = "SHA256WithRSA"; ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm) .build(keyPair.getPrivate()); Instant startDate = Instant.now(); Instant endDate = startDate.plus(2 * 365, ChronoUnit.DAYS); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, certSerialNumber, Date.from(startDate), Date.from(endDate), dnName, keyPair.getPublic()); Certificate certificate = new JcaX509CertificateConverter().setProvider(bc) .getCertificate(certBuilder.build(contentSigner)); return Pair.of(keyPair.getPrivate(), certificate); } // Generates AES key and stores in keystore public static Key generateAESKey(String username, char[] password, String alias) throws GeneralSecurityException, FileNotFoundException, IOException { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); Key key = keyGen.generateKey(); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream fis = new FileInputStream(username + ".ks"); keystore.load(fis, password); keystore.setKeyEntry(alias, key, password, null); fis.close(); FileOutputStream fos = new FileOutputStream(username + ".ks"); keystore.store(fos, password); fos.close(); return key; } // Reads key from keystore public static Key getKey(String username, char[] password, String alias) throws GeneralSecurityException, FileNotFoundException, IOException { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream fis = new FileInputStream(username + ".ks"); keystore.load(fis, password); fis.close(); Key key = keystore.getKey(alias, password); return key; } // Store key in keystore public static void saveKey(String username, char[] password, String alias, Key key) throws GeneralSecurityException, FileNotFoundException, IOException { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream fis = new FileInputStream(username + ".ks"); keystore.load(fis, password); keystore.setKeyEntry(alias, key, password, null); fis.close(); FileOutputStream fos = new FileOutputStream(username + ".ks"); keystore.store(fos, password); fos.close(); } // AES ecnrypt/decrypt function public static void transform(String inputFile, String outputFile, Key key, int mode, byte[] iv) throws GeneralSecurityException, FileNotFoundException, IOException { byte[] inputBytes = Files.readAllBytes(new File(inputFile).toPath()); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(mode, key, new IvParameterSpec(iv)); byte[] outputBytes = cipher.doFinal(inputBytes); Files.write(new File(outputFile).toPath(), outputBytes); } public static byte[] sign(String fileName, PrivateKey key) throws IOException, GeneralSecurityException { byte[] inputBytes = Files.readAllBytes(new File(fileName).toPath()); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(key); signature.update(inputBytes); return signature.sign(); } public static byte[] usernameToIV(String username) { String holder = new String(username); while (holder.length() < 16) holder = holder.concat(username); return holder.substring(0, 16).getBytes(); } }
9240c8742c6a06f9081eadc78b1259c48597ed85
4,086
java
Java
corelibrary/src/main/java/com/axway/ats/core/dbaccess/cassandra/DbConnCassandra.java
dslaveykov/ats-framework
6ab85f2b3897f184fde156451de7e1a0c0771599
[ "Apache-2.0" ]
33
2017-03-08T13:23:21.000Z
2021-12-01T08:29:15.000Z
corelibrary/src/main/java/com/axway/ats/core/dbaccess/cassandra/DbConnCassandra.java
dslaveykov/ats-framework
6ab85f2b3897f184fde156451de7e1a0c0771599
[ "Apache-2.0" ]
20
2017-04-04T11:23:54.000Z
2021-09-30T15:20:45.000Z
corelibrary/src/main/java/com/axway/ats/core/dbaccess/cassandra/DbConnCassandra.java
dslaveykov/ats-framework
6ab85f2b3897f184fde156451de7e1a0c0771599
[ "Apache-2.0" ]
61
2017-04-05T14:23:22.000Z
2021-09-28T14:33:36.000Z
28.375
105
0.607195
1,001,665
/* * Copyright 2017 Axway Software * * 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.axway.ats.core.dbaccess.cassandra; import java.sql.Driver; import java.util.Map; import javax.sql.DataSource; import org.apache.log4j.Logger; import com.axway.ats.common.dbaccess.CassandraKeys; import com.axway.ats.common.dbaccess.DbKeys; import com.axway.ats.core.dbaccess.DbConnection; /** * Connection descriptor for Cassandra databases */ public class DbConnCassandra extends DbConnection { private static Logger log = Logger.getLogger(DbConnCassandra.class); private boolean allowFiltering; /** * Default DB port */ public static final int DEFAULT_PORT = 9042; public static final String DATABASE_TYPE = "CASSANDRA"; /** * Constructor * * @param host host * @param db database name * @param user user name * @param password user password * @param customProperties map of custom properties */ public DbConnCassandra( String host, String db, String user, String password, Map<String, Object> customProperties ) { this(host, DEFAULT_PORT, db, user, password, customProperties); } /** * Constructor * * @param host host * @param port port * @param db database name * @param user user name * @param password user password * @param customProperties map of custom properties */ public DbConnCassandra( String host, int port, String db, String user, String password, Map<String, Object> customProperties ) { super(DATABASE_TYPE, host, port, db, user, password, customProperties); } public int getPort() { return this.port; } public boolean isAllowFiltering() { return this.allowFiltering; } @Override protected void initializeCustomProperties( Map<String, Object> customProperties ) { if (customProperties != null && !customProperties.isEmpty()) { //read the port if such is set Object portValue = customProperties.get(DbKeys.PORT_KEY); if (portValue != null) { if (this.port != -1 && this.port != DEFAULT_PORT) { log.warn("New port value found in custom properties. Old value will be overridden"); } this.port = (Integer) portValue; } Object allowFilteringValue = customProperties.get(CassandraKeys.ALLOW_FILTERING); if (allowFilteringValue != null) { this.allowFiltering = (Boolean) allowFilteringValue; } } if (this.port < 1) { this.port = DEFAULT_PORT; } } @Override public DataSource getDataSource() { return null; } @Override public Class<? extends Driver> getDriverClass() { return null; } @Override public String getURL() { return ":cassandra:" + host + ":" + port + "/" + db; } @Override public String getDescription() { StringBuilder description = new StringBuilder("Cassandra connection to "); description.append(host); description.append(":").append(port); description.append("/").append(db); return description.toString(); } @Override public void disconnect() { } }
9240ca6814d55c6571e3c0f2ed8c48a4734db080
832
java
Java
gmall-sms/src/main/java/com/atguigu/gmall/sms/entity/HomeSubjectEntity.java
zxc-cll/gmall
6f6bba68b199b46e33ce28044d76327b1a6945e7
[ "Apache-2.0" ]
null
null
null
gmall-sms/src/main/java/com/atguigu/gmall/sms/entity/HomeSubjectEntity.java
zxc-cll/gmall
6f6bba68b199b46e33ce28044d76327b1a6945e7
[ "Apache-2.0" ]
null
null
null
gmall-sms/src/main/java/com/atguigu/gmall/sms/entity/HomeSubjectEntity.java
zxc-cll/gmall
6f6bba68b199b46e33ce28044d76327b1a6945e7
[ "Apache-2.0" ]
null
null
null
14.561404
56
0.668675
1,001,666
package com.atguigu.gmall.sms.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 首页专题表【jd首页下面很多专题,每个专题链接新的页面,展示专题商品信息】 * * @author zxc * @email [email protected] * @date 2021-08-28 19:37:50 */ @Data @TableName("sms_home_subject") public class HomeSubjectEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId private Long id; /** * 专题名字 */ private String name; /** * 专题标题 */ private String title; /** * 专题副标题 */ private String subTitle; /** * 显示状态 */ private Integer status; /** * 详情连接 */ private String url; /** * 排序 */ private Integer sort; /** * 专题图片地址 */ private String img; }
9240caa9f1e778bfd7cca5262910f4aa8c6322fd
19,316
java
Java
src/main/java/org/apache/netbeans/nbm/AbstractNbmMojo.java
inceptive-tech/netbeans-mavenutils-nbm-maven-plugin
38cfba38913d48995a39c0f1687845b390545f38
[ "Apache-2.0" ]
11
2019-05-20T21:23:45.000Z
2021-09-20T09:42:31.000Z
src/main/java/org/apache/netbeans/nbm/AbstractNbmMojo.java
inceptive-tech/netbeans-mavenutils-nbm-maven-plugin
38cfba38913d48995a39c0f1687845b390545f38
[ "Apache-2.0" ]
16
2019-05-15T17:22:18.000Z
2022-03-30T20:02:35.000Z
src/main/java/org/apache/netbeans/nbm/AbstractNbmMojo.java
inceptive-tech/netbeans-mavenutils-nbm-maven-plugin
38cfba38913d48995a39c0f1687845b390545f38
[ "Apache-2.0" ]
21
2019-05-14T13:41:36.000Z
2022-03-12T17:22:49.000Z
37.361702
120
0.515945
1,001,667
package org.apache.netbeans.nbm; /* * 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. */ import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException; import org.apache.maven.shared.dependency.graph.DependencyNode; import org.apache.netbeans.nbm.model.Dependency; import org.apache.netbeans.nbm.model.NetBeansModule; import org.apache.netbeans.nbm.model.io.xpp3.NetBeansModuleXpp3Reader; import org.apache.netbeans.nbm.utils.AbstractNetbeansMojo; import org.apache.netbeans.nbm.utils.ExamineManifest; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.codehaus.plexus.util.IOUtil; public abstract class AbstractNbmMojo extends AbstractNetbeansMojo { static boolean matchesLibrary( Artifact artifact, List<String> libraries, ExamineManifest depExaminator, Log log, boolean useOsgiDependencies ) { String artId = artifact.getArtifactId(); String grId = artifact.getGroupId(); String id = grId + ":" + artId; boolean explicit = libraries.remove( id ); if ( explicit ) { log.debug( id + " included as module library, explicitly declared in module descriptor." ); return explicit; } if ( Artifact.SCOPE_PROVIDED.equals( artifact.getScope() ) || Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) ) { log.debug( id + " omitted as module library, has scope 'provided/system'" ); return false; } if ( "nbm".equals( artifact.getType() ) ) { return false; } if ( depExaminator.isNetBeansModule() || ( useOsgiDependencies && depExaminator.isOsgiBundle() ) ) { //TODO I can see how someone might want to include an osgi bundle as library, not dependency. // I guess it won't matter much in 6.9+, in older versions it could be a problem. return false; } log.debug( id + " included as module library, squeezed through all the filters." ); return true; } static Dependency resolveNetBeansDependency( Artifact artifact, List<Dependency> deps, ExamineManifest manifest, Log log ) { String artId = artifact.getArtifactId(); String grId = artifact.getGroupId(); String id = grId + ":" + artId; for ( Dependency dep : deps ) { if ( id.equals( dep.getId() ) ) { if ( manifest.isNetBeansModule() ) { return dep; } else { if ( dep.getExplicitValue() != null ) { return dep; } log.warn( id + " declared as module dependency in descriptor, but not a NetBeans module" ); return null; } } } if ( "nbm".equals( artifact.getType() ) ) { Dependency dep = new Dependency(); dep.setId( id ); dep.setType( "spec" ); log.debug( "Adding nbm module dependency - " + id ); return dep; } if ( manifest.isNetBeansModule() ) { Dependency dep = new Dependency(); dep.setId( id ); dep.setType( "spec" ); log.debug( "Adding direct NetBeans module dependency - " + id ); return dep; } return null; } protected final NetBeansModule readModuleDescriptor( File descriptor ) throws MojoExecutionException { if ( descriptor == null ) { throw new MojoExecutionException( "The module descriptor has to be configured." ); } if ( !descriptor.exists() ) { throw new MojoExecutionException( "The module descriptor is missing: '" + descriptor + "'." ); } Reader r = null; try { r = new FileReader( descriptor ); NetBeansModuleXpp3Reader reader = new NetBeansModuleXpp3Reader(); NetBeansModule module = reader.read( r ); return module; } catch ( IOException exc ) { throw new MojoExecutionException( "Error while reading module descriptor '" + descriptor + "'.", exc ); } catch ( XmlPullParserException xml ) { throw new MojoExecutionException( "Error while reading module descriptor '" + descriptor + "'.", xml ); } finally { IOUtil.close( r ); } } protected final NetBeansModule createDefaultDescriptor( MavenProject project, boolean log ) { if ( log ) { getLog().info( "No Module Descriptor defined, trying to fallback to generated values:" ); } NetBeansModule module = new NetBeansModule(); return module; } static List<Artifact> getLibraryArtifacts( DependencyNode treeRoot, NetBeansModule module, List<Artifact> runtimeArtifacts, Map<Artifact, ExamineManifest> examinerCache, Log log, boolean useOsgiDependencies ) throws MojoExecutionException { List<Artifact> include = new ArrayList<Artifact>(); if ( module != null ) { List<String> librList = new ArrayList<String>(); if ( module.getLibraries() != null ) { librList.addAll( module.getLibraries() ); } CollectLibrariesNodeVisitor visitor = new CollectLibrariesNodeVisitor( librList, runtimeArtifacts, examinerCache, log, treeRoot, useOsgiDependencies ); treeRoot.accept( visitor ); include.addAll( visitor.getArtifacts() ); } return include; } static List<ModuleWrapper> getModuleDependencyArtifacts( DependencyNode treeRoot, NetBeansModule module, Dependency[] customDependencies, MavenProject project, Map<Artifact, ExamineManifest> examinerCache, List<Artifact> libraryArtifacts, Log log, boolean useOsgiDependencies ) throws MojoExecutionException { List<Dependency> deps = new ArrayList<Dependency>(); if ( customDependencies != null ) { deps.addAll( Arrays.asList( customDependencies ) ); } if ( module != null && !module.getDependencies().isEmpty() ) { log.warn( "dependencies in module descriptor are deprecated, use the plugin's parameter moduleDependencies" ); //we need to make sure a dependency is not twice there, module deps override the config //(as is the case with other configurations) for ( Dependency d : module.getDependencies() ) { Dependency found = null; for ( Dependency d2 : deps ) { if ( d2.getId().equals( d.getId() ) ) { found = d2; break; } } if ( found != null ) { deps.remove( found ); } deps.add( d ); } } List<ModuleWrapper> include = new ArrayList<ModuleWrapper>(); @SuppressWarnings( "unchecked" ) List<Artifact> artifacts = project.getCompileArtifacts(); for ( Artifact artifact : artifacts ) { if ( libraryArtifacts.contains( artifact ) ) { continue; } ExamineManifest depExaminator = examinerCache.get( artifact ); if ( depExaminator == null ) { depExaminator = new ExamineManifest( log ); depExaminator.setArtifactFile( artifact.getFile() ); depExaminator.checkFile(); examinerCache.put( artifact, depExaminator ); } Dependency dep = resolveNetBeansDependency( artifact, deps, depExaminator, log ); if ( dep != null ) { ModuleWrapper wr = new ModuleWrapper(); wr.dependency = dep; wr.artifact = artifact; wr.transitive = false; //only direct deps matter to us.. if ( depExaminator.isNetBeansModule() && artifact.getDependencyTrail().size() > 2 ) { log.debug( artifact.getId() + " omitted as NetBeans module dependency, not a direct one. " + "Declare it in the pom for inclusion." ); wr.transitive = true; } include.add( wr ); } else { if ( useOsgiDependencies && depExaminator.isOsgiBundle() ) { ModuleWrapper wr = new ModuleWrapper(); wr.osgi = true; String id = artifact.getGroupId() + ":" + artifact.getArtifactId(); for ( Dependency depe : deps ) { if ( id.equals( depe.getId() ) ) { wr.dependency = depe; } } boolean print = false; if ( wr.dependency == null ) { Dependency depe = new Dependency(); depe.setId( id ); depe.setType( "spec" ); wr.dependency = depe; print = true; } wr.artifact = artifact; wr.transitive = false; //only direct deps matter to us.. if ( artifact.getDependencyTrail().size() > 2 ) { log.debug( artifact.getId() + " omitted as NetBeans module OSGi dependency, not a direct one. " + "Declare it in the pom for inclusion." ); wr.transitive = true; } else { if ( print ) { log.info( "Adding OSGi bundle dependency - " + id ); } } include.add( wr ); } } } return include; } static class ModuleWrapper { Dependency dependency; Artifact artifact; boolean transitive = true; boolean osgi = false; } //copied from dependency:tree mojo protected DependencyNode createDependencyTree( MavenProject project, DependencyGraphBuilder dependencyGraphBuilder, String scope ) throws MojoExecutionException { ArtifactFilter artifactFilter = createResolvingArtifactFilter( scope ); try { return dependencyGraphBuilder.buildDependencyGraph( project, artifactFilter ); } catch ( DependencyGraphBuilderException exception ) { throw new MojoExecutionException( "Cannot build project dependency tree", exception ); } } //copied from dependency:tree mojo /** * Gets the artifact filter to use when resolving the dependency tree. * * @return the artifact filter */ private ArtifactFilter createResolvingArtifactFilter( String scope ) { ArtifactFilter filter; // filter scope if ( scope != null ) { getLog().debug( "+ Resolving dependency tree for scope '" + scope + "'" ); filter = new ScopeArtifactFilter( scope ); } else { filter = null; } return filter; } protected final ArtifactResult turnJarToNbmFile( Artifact art, ArtifactFactory artifactFactory, ArtifactResolver artifactResolver, MavenProject project, ArtifactRepository localRepository ) throws MojoExecutionException { if ( "jar".equals( art.getType() ) || "nbm".equals( art.getType() ) ) { //TODO, it would be nice to have a check to see if the // "to-be-created" module nbm artifact is actually already in the // list of dependencies (as "nbm-file") or not.. // that would be a timesaver ExamineManifest mnf = new ExamineManifest( getLog() ); File jar = art.getFile(); if ( !jar.isFile() ) { //MNBMODULE-210 with recent CoS changes in netbeans (7.4) jar will be file as we link open projects in // the build via WorkspaceReader. // That's fine here, as all we need is to know if project is osgi or nbm module. // the nbm file has to be in local repository though. String path = localRepository.pathOf( art ); File jar2 = new File( localRepository.getBasedir(), path.replace( "/", File.separator ) ); File manifest = new File( jar, "META-INF/MANIFEST.MF" ); if ( !jar2.isFile() || !manifest.isFile() ) { getLog().warn( "MNBMODULE-131: need to at least run install phase on " + jar2 ); return new ArtifactResult( null, null ); } mnf.setManifestFile( manifest ); } else { mnf.setJarFile( jar ); } mnf.checkFile(); if ( mnf.isNetBeansModule() ) { Artifact nbmArt = artifactFactory.createDependencyArtifact( art.getGroupId(), art.getArtifactId(), art.getVersionRange(), "nbm-file", art.getClassifier(), art.getScope() ); try { artifactResolver.resolve( nbmArt, project.getRemoteArtifactRepositories(), localRepository ); } catch ( ArtifactResolutionException ex ) { //shall be check before actually resolving from repos? checkReactor( art, nbmArt ); if ( !nbmArt.isResolved() ) { throw new MojoExecutionException( "Failed to retrieve the nbm file from repository", ex ); } } catch ( ArtifactNotFoundException ex ) { //shall be check before actually resolving from repos? checkReactor( art, nbmArt ); if ( !nbmArt.isResolved() ) { throw new MojoExecutionException( "Failed to retrieve the nbm file from repository", ex ); } } return new ArtifactResult( nbmArt, mnf ); } if ( mnf.isOsgiBundle() ) { return new ArtifactResult( null, mnf ); } } return new ArtifactResult( null, null ); } protected static final class ArtifactResult { private final Artifact converted; private final ExamineManifest manifest; ArtifactResult( Artifact conv, ExamineManifest manifest ) { converted = conv; this.manifest = manifest; } boolean hasConvertedArtifact() { return converted != null; } Artifact getConvertedArtifact() { return converted; } public boolean isOSGiBundle() { return manifest != null && manifest.isOsgiBundle(); } public ExamineManifest getExaminedManifest() { return manifest; } } private void checkReactor( Artifact art, Artifact nbmArt ) { if ( art.getFile().getName().endsWith( ".jar" ) ) { String name = art.getFile().getName(); name = name.substring( 0, name.length() - ".jar".length() ) + ".nbm"; File fl = new File( art.getFile().getParentFile(), name ); if ( fl.exists() ) { nbmArt.setFile( fl ); nbmArt.setResolved( true ); } } } }
9240cc3fe16a911467685d278b0f8ba6bc816206
476
java
Java
src/main/java/global/module/Test.java
RWB0104/api.itcode.dev-oauth2
e313193ae0d29d9261925167099375767167d29b
[ "MIT" ]
null
null
null
src/main/java/global/module/Test.java
RWB0104/api.itcode.dev-oauth2
e313193ae0d29d9261925167099375767167d29b
[ "MIT" ]
null
null
null
src/main/java/global/module/Test.java
RWB0104/api.itcode.dev-oauth2
e313193ae0d29d9261925167099375767167d29b
[ "MIT" ]
null
null
null
23.8
70
0.745798
1,001,668
package global.module; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; public class Test { public static void main(String[] args) throws JsonProcessingException { HashMap<String, String> map = new HashMap<>(); map.put("key", "asdfklasjdfl"); map.put("aa", "Asdfkj3"); ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(map)); } }
9240cca0411c845a2a929cd8d02d7d01815e86bc
695
java
Java
src/bean/ItemOrder.java
QueebSkeleton/orderingsystem-shsfinalproject
f557573937279ed1042948f2e644b24800a61b46
[ "Apache-2.0" ]
null
null
null
src/bean/ItemOrder.java
QueebSkeleton/orderingsystem-shsfinalproject
f557573937279ed1042948f2e644b24800a61b46
[ "Apache-2.0" ]
1
2020-12-29T01:24:47.000Z
2020-12-29T01:24:47.000Z
src/bean/ItemOrder.java
QueebSkeleton/orderingsystem-shsfinalproject
f557573937279ed1042948f2e644b24800a61b46
[ "Apache-2.0" ]
null
null
null
13.365385
49
0.679137
1,001,669
package bean; import java.io.Serializable; public class ItemOrder implements Serializable { private static final long serialVersionUID = 1L; private long id; private Order _order; private Food food; private int quantity; public ItemOrder() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public Order getOrder() { return _order; } public void setOrder(Order order) { this._order = order; } public Food getFood() { return food; } public void setFood(Food food) { this.food = food; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } }
9240cd63295dc992ffc03681ee036b03eb87f74f
9,027
java
Java
src/main/java/com/sjhy/plugin/ui/GlobalConfigSettingPanel.java
ivyxjc/EasyCode
757442f67ce4c0b404b246ae78ee09276918be21
[ "MIT" ]
6
2019-08-30T06:47:01.000Z
2020-12-21T13:36:08.000Z
src/main/java/com/sjhy/plugin/ui/GlobalConfigSettingPanel.java
cai3231/EasyCode
f2db06ff810c85058df313efb9f3f70e83374e6b
[ "MIT" ]
null
null
null
src/main/java/com/sjhy/plugin/ui/GlobalConfigSettingPanel.java
cai3231/EasyCode
f2db06ff810c85058df313efb9f3f70e83374e6b
[ "MIT" ]
4
2019-01-09T01:49:55.000Z
2020-12-18T08:49:21.000Z
31.673684
156
0.593996
1,001,670
package com.sjhy.plugin.ui; import com.fasterxml.jackson.core.type.TypeReference; import com.intellij.ide.fileTemplates.impl.UrlUtil; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.util.ExceptionUtil; import com.sjhy.plugin.entity.GlobalConfig; import com.sjhy.plugin.entity.GlobalConfigGroup; import com.sjhy.plugin.tool.CloneUtils; import com.sjhy.plugin.config.Settings; import com.sjhy.plugin.ui.base.BaseGroupPanel; import com.sjhy.plugin.ui.base.BaseItemSelectPanel; import com.sjhy.plugin.ui.base.TemplateEditor; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 全局配置主面板 * * @author makejava * @version 1.0.0 * @since 2018/07/18 09:33 */ public class GlobalConfigSettingPanel implements Configurable { /** * 全局配置描述信息,说明文档 */ private static final String GLOBAL_CONFIG_DESCRIPTION_INFO; static { String descriptionInfo = ""; try { descriptionInfo = UrlUtil.loadText(TemplateSettingPanel.class.getResource("/description/globalConfigDescription.html")); } catch (IOException e) { ExceptionUtil.rethrow(e); } finally { GLOBAL_CONFIG_DESCRIPTION_INFO = descriptionInfo; } } /** * 配置信息 */ private Settings settings; /** * 编辑框面板 */ private TemplateEditor templateEditor; /** * 基本的分组面板 */ private BaseGroupPanel baseGroupPanel; /** * 基本的元素选择面板 */ private BaseItemSelectPanel<GlobalConfig> baseItemSelectPanel; /** * 当前分组 */ private Map<String, GlobalConfigGroup> group; /** * 当前选中分组 */ private String currGroupName; /** * 项目对象 */ private Project project; /** * 默认构造方法 */ GlobalConfigSettingPanel() { // 存在打开的项目则使用打开的项目,否则使用默认项目 ProjectManager projectManager = ProjectManager.getInstance(); Project[] openProjects = projectManager.getOpenProjects(); // 项目对象 this.project = openProjects.length > 0 ? openProjects[0] : projectManager.getDefaultProject(); // 配置服务实例化 this.settings = Settings.getInstance(); // 克隆对象 this.currGroupName = this.settings.getCurrGlobalConfigGroupName(); this.group = CloneUtils.cloneByJson(this.settings.getGlobalConfigGroupMap(), new TypeReference<Map<String, GlobalConfigGroup>>() {}); } /** * 获取设置显示的名称 * * @return 名称 */ @Nls @Override public String getDisplayName() { return "Global Config"; } /** * 获取主面板对象 * * @return 主面板对象 */ @Nullable @Override public JComponent createComponent() { // 创建主面板 JPanel mainPanel = new JPanel(new BorderLayout()); // 实例化分组面板 this.baseGroupPanel = new BaseGroupPanel(new ArrayList<>(group.keySet()), this.currGroupName) { @Override protected void createGroup(String name) { // 创建分组 GlobalConfigGroup globalConfigGroup = new GlobalConfigGroup(); globalConfigGroup.setName(name); globalConfigGroup.setElementList(new ArrayList<>()); group.put(name, globalConfigGroup); currGroupName = name; baseGroupPanel.reset(new ArrayList<>(group.keySet()), currGroupName); // 创建空白分组,需要清空输入框 templateEditor.reset("empty", ""); } @Override protected void deleteGroup(String name) { // 删除分组 group.remove(name); currGroupName = Settings.DEFAULT_NAME; baseGroupPanel.reset(new ArrayList<>(group.keySet()), currGroupName); } @Override protected void copyGroup(String name) { // 复制分组 GlobalConfigGroup globalConfigGroup = CloneUtils.cloneByJson(group.get(currGroupName)); globalConfigGroup.setName(name); currGroupName = name; group.put(name, globalConfigGroup); baseGroupPanel.reset(new ArrayList<>(group.keySet()), currGroupName); } @Override protected void changeGroup(String name) { currGroupName = name; if (baseItemSelectPanel == null) { return; } // 重置模板选择 baseItemSelectPanel.reset(group.get(currGroupName).getElementList(), 0); if (group.get(currGroupName).getElementList().isEmpty()) { // 没有元素时,需要清空编辑框 templateEditor.reset("empty", ""); } } }; // 创建元素选择面板 this.baseItemSelectPanel = new BaseItemSelectPanel<GlobalConfig>(group.get(currGroupName).getElementList()) { @Override protected void addItem(String name) { List<GlobalConfig> globalConfigList = group.get(currGroupName).getElementList(); // 新增模板 globalConfigList.add(new GlobalConfig(name, "")); baseItemSelectPanel.reset(globalConfigList, globalConfigList.size() - 1); } @Override protected void copyItem(String newName, GlobalConfig item) { // 复制模板 GlobalConfig globalConfig = CloneUtils.cloneByJson(item); globalConfig.setName(newName); List<GlobalConfig> globalConfigList = group.get(currGroupName).getElementList(); globalConfigList.add(globalConfig); baseItemSelectPanel.reset(globalConfigList, globalConfigList.size() - 1); } @Override protected void deleteItem(GlobalConfig item) { // 删除模板 group.get(currGroupName).getElementList().remove(item); baseItemSelectPanel.reset(group.get(currGroupName).getElementList(), 0); if (group.get(currGroupName).getElementList().isEmpty()) { // 没有元素时,需要清空编辑框 templateEditor.reset("empty", ""); } } @Override protected void selectedItem(GlobalConfig item) { // 如果编辑面板已经实例化,需要选释放后再初始化 if (templateEditor == null) { FileType velocityFileType = FileTypeManager.getInstance().getFileTypeByExtension("vm"); templateEditor = new TemplateEditor(project, item.getName() + ".vm", item.getValue(), GLOBAL_CONFIG_DESCRIPTION_INFO, velocityFileType); // 代码修改回调 templateEditor.setCallback(() -> onUpdate()); baseItemSelectPanel.getRightPanel().add(templateEditor.createComponent(), BorderLayout.CENTER); } else { // 更新代码 templateEditor.reset(item.getName(), item.getValue()); } } }; mainPanel.add(baseGroupPanel, BorderLayout.NORTH); mainPanel.add(baseItemSelectPanel.getComponent(), BorderLayout.CENTER); return mainPanel; } /** * 数据发生修改时调用 */ private void onUpdate() { // 同步修改的代码 GlobalConfig globalConfig = baseItemSelectPanel.getSelectedItem(); if (globalConfig != null) { globalConfig.setValue(templateEditor.getEditor().getDocument().getText()); } } /** * 配置是否修改过 * * @return 是否修改过 */ @Override public boolean isModified() { return !settings.getGlobalConfigGroupMap().equals(group) || !settings.getCurrGlobalConfigGroupName().equals(currGroupName); } /** * 保存方法 */ @Override public void apply() { settings.setGlobalConfigGroupMap(group); settings.setCurrGlobalConfigGroupName(currGroupName); } /** * 重置方法 */ @Override public void reset() { // 没修改过的清空下不需要重置 if (!isModified()) { return; } // 防止对象篡改,需要进行克隆 this.group = CloneUtils.cloneByJson(settings.getGlobalConfigGroupMap(), new TypeReference<Map<String, GlobalConfigGroup>>() {}); this.currGroupName = settings.getCurrGlobalConfigGroupName(); if (baseGroupPanel == null) { return; } // 重置元素选择面板 baseGroupPanel.reset(new ArrayList<>(group.keySet()), currGroupName); } /** * 关闭回调方法 */ @Override public void disposeUIResources() { // 释放编辑框 if (templateEditor != null) { templateEditor.onClose(); } } }
9240cdc648ab17f6d0cc6466acdabd82bc043b59
2,622
java
Java
origin/07/7.3/ShaderTest/app/src/main/java/org/crazyit/image/MainActivity.java
CreateChance/CrazyAndroidHandout
6fce872b30be4dcf478401a7d85a61c57a8ec85f
[ "Apache-2.0" ]
null
null
null
origin/07/7.3/ShaderTest/app/src/main/java/org/crazyit/image/MainActivity.java
CreateChance/CrazyAndroidHandout
6fce872b30be4dcf478401a7d85a61c57a8ec85f
[ "Apache-2.0" ]
null
null
null
origin/07/7.3/ShaderTest/app/src/main/java/org/crazyit/image/MainActivity.java
CreateChance/CrazyAndroidHandout
6fce872b30be4dcf478401a7d85a61c57a8ec85f
[ "Apache-2.0" ]
null
null
null
29.133333
62
0.707094
1,001,671
package org.crazyit.image; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Color; import android.graphics.ComposeShader; import android.graphics.LinearGradient; import android.graphics.PorterDuff; import android.graphics.RadialGradient; import android.graphics.Shader; import android.graphics.Shader.TileMode; import android.graphics.SweepGradient; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { // 声明位图渲染对象 private Shader[] shaders = new Shader[5]; // 声明颜色数组 private int[] colors; MyView myView; // 自定义视图类 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myView = (MyView)findViewById(R.id.my_view); // 获得Bitmap实例 Bitmap bm = BitmapFactory.decodeResource(getResources() , R.drawable.water); // 设置渐变的颜色组,也就是按红、绿、蓝的方式渐变 colors = new int[] { Color.RED, Color.GREEN, Color.BLUE }; // 实例化BitmapShader,x坐标方向重复图形,y坐标方向镜像图形 shaders[0] = new BitmapShader(bm, TileMode.REPEAT, TileMode.MIRROR); // 实例化LinearGradient shaders[1] = new LinearGradient(0, 0, 100, 100 , colors, null, TileMode.REPEAT); // 实例化RadialGradient shaders[2] = new RadialGradient(100, 100, 80, colors, null, TileMode.REPEAT); // 实例化SweepGradient shaders[3] = new SweepGradient(160, 160, colors, null); // 实例化ComposeShader shaders[4] = new ComposeShader(shaders[1], shaders[2], PorterDuff.Mode.DARKEN); Button bn1 = (Button)findViewById(R.id.bn1); Button bn2 = (Button)findViewById(R.id.bn2); Button bn3 = (Button)findViewById(R.id.bn3); Button bn4 = (Button)findViewById(R.id.bn4); Button bn5 = (Button)findViewById(R.id.bn5); bn1.setOnClickListener(this); bn2.setOnClickListener(this); bn3.setOnClickListener(this); bn4.setOnClickListener(this); bn5.setOnClickListener(this); } @Override public void onClick(View source) { switch(source.getId()) { case R.id.bn1: myView.paint.setShader(shaders[0]); break; case R.id.bn2: myView.paint.setShader(shaders[1]); break; case R.id.bn3: myView.paint.setShader(shaders[2]); break; case R.id.bn4: myView.paint.setShader(shaders[3]); break; case R.id.bn5: myView.paint.setShader(shaders[4]); break; } // 重绘界面 myView.invalidate(); } }
9240ce4c31ff2480aed0468fec6825ac399eb4ba
3,145
java
Java
auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java
onap/aaf-authz
5836e4a53d87b1792486aa6b0b1ddb2e71d91bb9
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java
onap/aaf-authz
5836e4a53d87b1792486aa6b0b1ddb2e71d91bb9
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java
onap/aaf-authz
5836e4a53d87b1792486aa6b0b1ddb2e71d91bb9
[ "Apache-2.0", "CC-BY-4.0" ]
2
2020-08-13T17:05:41.000Z
2021-04-20T07:44:08.000Z
39.3125
121
0.540859
1,001,672
/******************************************************************************* * ============LICENSE_START==================================================== * * org.onap.aaf * * =========================================================================== * * Copyright © 2017 AT&T Intellectual Property. 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. * * ============LICENSE_END==================================================== * * * * ******************************************************************************/ package org.onap.aaf.auth.gui; import java.io.IOException; import java.security.Principal; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.onap.aaf.auth.env.AuthzTrans; import org.onap.aaf.auth.org.OrganizationException; import org.onap.aaf.auth.org.Organization.Identity; import org.onap.aaf.auth.rserv.TransFilter; import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.principal.TaggedPrincipal; public class OrgLookupFilter implements Filter { @Override public void init(FilterConfig arg0) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { final AuthzTrans trans = (AuthzTrans) req.getAttribute(TransFilter.TRANS_TAG); if (req instanceof HttpServletRequest) { Principal p = ((HttpServletRequest)req).getUserPrincipal(); if (p instanceof TaggedPrincipal) { ((TaggedPrincipal)p).setTagLookup(new TaggedPrincipal.TagLookup() { @Override public String lookup() throws CadiException { Identity id; try { id = trans.org().getIdentity(trans, p.getName()); if (id!=null && id.isFound()) { return id.firstName(); } } catch (OrganizationException e) { throw new CadiException(e); } return p.getName(); } }); } fc.doFilter(req, resp); } } @Override public void destroy() { } }