blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
f15cc4ba82a002a72ca77cfe96db46ff8dd1e118
Java
ProjectEmbers/Object-Oriented-Programming
/CSE148 L-07 Problem Set 3 Review/src/deepandShallowCopies/Person.java
UTF-8
1,265
3.640625
4
[]
no_license
package deepandShallowCopies; public class Person { @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", id=" + id + "]"; } private String name; // instance variables private int age; private String id; // Static variables: They are shared by all objects of the class. private static int idNumber = 0; public Person(String name, int age) { this.name = name; this.age = age; id = String.valueOf(idNumber++); } public Person(Person person) { this.name = person.name; this.age = person.age; id = String.valueOf(idNumber++); } public String getId() { return id; } public void setId(String id) { this.id = id; } public static int getIdNumber() { return idNumber; } public static void setIdNumber(int idNumber) { Person.idNumber = idNumber; } // Instance methods public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person shallowCopy() { return this; } public Person deepCopy() { return new Person(this.name, this.age); } }
true
cc1ab236445bb83753313925d7620cd4c084cc50
Java
essar/SkiData
/src/uk/co/essarsoftware/ski/android/ui/TrackListActivity.java
UTF-8
6,295
2.5625
3
[]
no_license
package uk.co.essarsoftware.ski.android.ui; import java.util.ArrayList; import java.util.Date; import uk.co.essarsoftware.ski.data.SkiData; import uk.co.essarsoftware.ski.data.Track; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.TextView; /** * <p>Android Activity that displays a list of all tracks within the data.</p> * * @author Steve Roberts <steve.roberts@essarsoftware.co.uk> * @version 1.0 (01 Feb 2012) * */ public class TrackListActivity extends SkiDataActivity { private SkiData data; /* (non-Javadoc) * @see uk.co.essarsoftware.ski.ui.SkiDataActivity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Retrieve loaded data data = AppData.getAppData().data; if(data != null) { /*// Build track info ArrayList<String> tracks = new ArrayList<String>(); for(TrackElement key : data.getTrackKeys()) { Track t = data.getTrackFrom(key); Date d = key.getTimeAsDate(); switch(key.getMode()) { case STOP: tracks.add(String.format(" STOP (%d mins, %d secs)", t.size() / 60, t.size() % 60)); break; case LIFT: tracks.add(String.format("[%k:%M] LIFT (+%dm; %d mins, %d secs)", d, d, t.getDeltaAltitude(), t.size() / 60, t.size() % 60)); break; case SKI: tracks.add(String.format(" SKI (%,dm; %.1f kph; %d mins, %d secs)", Math.round(t.getDistance()), t.getAverageSpeed(), t.size() / 60, t.size() % 60)); break; } }*/ ExpandableListView elv = new ExpandableListView(this); elv.setAdapter(new TrackListAdapter()); elv.setClickable(false); setContentView(elv); } else { Log.w(getLocalClassName(), "Data is null, tracks not loaded"); } Log.d(getLocalClassName(), "TrackListActivity created"); } class TrackListAdapter extends BaseExpandableListAdapter { private ArrayList<Track> groups; public TrackListAdapter() { groups = data.getBlockKeys(); } private TextView getGenericView() { // Layout parameters for the ExpandableListView AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 64); TextView textView = new TextView(TrackListActivity.this); textView.setLayoutParams(lp); textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); return textView; } public Object getChild(int groupPosition, int childPosition) { // Get group element Track t = (Track) getGroup(groupPosition); if(t != null) { // Build list of tracks in block ArrayList<Track> children = new ArrayList<Track>(data.getBlock(t).values()); // Return child, ignoring first element return (childPosition < children.size() ? children.get(childPosition + 1) : null); } return null; } public long getChildId(int groupPosition, int childPosition) { // Get child element Track t = (Track) getChild(groupPosition, childPosition); // Return start time as ID return (t == null ? 0 : t.getStartTime()); } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { TextView tv = getGenericView(); Track t = (Track) getChild(groupPosition, childPosition); if(t != null) { switch(t.getFirst().getMode()) { case SKI: tv.setPadding(75, 5, 5, 5); tv.setTextColor(0xFFFF0000); tv.setText(String.format("SKI (%,dm; %.1f kph; %d mins, %d secs)", Math.round(t.getDistance()), t.getAverageSpeed(), t.size() / 60, t.size() % 60)); break; case STOP: tv.setPadding(60, 5, 5, 5); tv.setTextColor(0xFFFFFFFF); tv.setText(String.format("STOP (%d mins, %d secs)", t.size() / 60, t.size() % 60)); } } return tv; } public int getChildrenCount(int groupPosition) { // Get group element Track t = (Track) getGroup(groupPosition); // Get block size (minus 1 as don't display the first element) return (t == null ? 0 : data.getBlock(t).size() - 1); } public Object getGroup(int groupPosition) { return (groupPosition < groups.size() ? groups.get(groupPosition) : null); } public int getGroupCount() { return groups.size(); } public long getGroupId(int groupPosition) { // Get group element Track t = (Track) getGroup(groupPosition); // Return start time as ID return (t == null ? 0 : t.getStartTime()); } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { TextView tv = getGenericView(); Track t = (Track) getGroup(groupPosition); if(t != null) { Date d = t.getFirst().getTimeAsDate(); tv.setPadding(50, 5, 5, 5); switch(t.getFirst().getMode()) { case LIFT: tv.setTextColor(0xFF0000FF); tv.setText(String.format("[%tk:%tM] LIFT (%+dm; %d mins, %d secs)", d, d, t.getDeltaAltitude(), t.size() / 60, t.size() % 60)); break; case SKI: tv.setTextColor(0xFFFF0000); tv.setText(String.format("[%tk:%tM] SKI (%,dm; %.1f kph; %d mins, %d secs)", d, d, Math.round(t.getDistance()), t.getAverageSpeed(), t.size() / 60, t.size() % 60)); break; case STOP: tv.setTextColor(0xFFFFFFFF); tv.setText(String.format("[%tk:%tM] STOP (%d mins, %d secs)", d, d, t.size() / 60, t.size() % 60)); break; } } return tv; } public boolean hasStableIds() { return true; } public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } } }
true
6c3fa66adbdc520ab61d258b3fb08690360d8c5f
Java
misterlizhaopeng/springproject
/spring-ioc/src/main/java/cn/com/config/MyImportBeanDefinitionRegistrar.java
UTF-8
715
2.15625
2
[]
no_license
package cn.com.config; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.type.AnnotationMetadata; import cn.com.bean.Cat; import cn.com.bean.Dog; public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Dog.class); registry.registerBeanDefinition("Dog",rootBeanDefinition); } }
true
6d42efb8dc33739eaa7acec86577ea2c1756fad9
Java
mfredenberg/UnoGame_master
/app/src/main/java/edu/up/cs301/Uno/UnoHumanPlayer.java
UTF-8
557
2.109375
2
[]
no_license
package edu.up.cs301.Uno; import android.view.View; import edu.up.cs301.game.GameHumanPlayer; import edu.up.cs301.game.GameMainActivity; import edu.up.cs301.game.infoMsg.GameInfo; /** * Created by fredenbe20 on 3/27/2018. */ public class UnoHumanPlayer extends GameHumanPlayer { public UnoHumanPlayer(String name){ super(name); } public void setAsGui(GameMainActivity activity) { } @Override public View getTopView() { return null; } @Override public void receiveInfo(GameInfo info) { } }
true
3135ee3e19a39ae691f382c43dd6336fdb82899c
Java
prudhvi1/MyAppServices
/myAccount_Lib/src/main/java/com/tracfone/generic/myaccountlibrary/restpojos/ResponseCheckLinkStatus.java
UTF-8
3,344
2.265625
2
[]
no_license
/*************************************************************************** * TracFone Wireless, Inc. * Engineering Department * * CLASS DESCRIPTION: * * This class defines the POJO for a Check link status responses * It corresponds to the restful services: * CheckLinkAccount * * TracFone Engineering Confidential Proprietary * Copyright (c) 2014, All Rights Reserved * * * ****************************************************************************/ package com.tracfone.generic.myaccountlibrary.restpojos; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.tracfone.generic.myaccountlibrary.MyAccountServiceException; @JsonIgnoreProperties(ignoreUnknown = true) public class ResponseCheckLinkStatus { public static class CheckLinkStatusResponse{ @JsonProperty("token_type") private String token_type; @JsonProperty("access_token") private String access_token; @JsonProperty("expires_in") private String expires_in; @JsonProperty("scope") private String scope; @JsonProperty("brandName") private String brandName; @JsonProperty("sourceSystem") private String sourceSystem; @JsonProperty("account_id") private String account_id; public String getToken_type() { return token_type; } public void setToken_type(String token_type) { this.token_type = token_type; } public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getExpires_in() { return expires_in; } public void setExpires_in(String expires_in) { this.expires_in = expires_in; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getSourceSystem() { return sourceSystem; } public void setSourceSystem(String sourceSystem) { this.sourceSystem = sourceSystem; } public String getAccount_id() { return account_id; } public void setAccount_id(String account_id) { this.account_id = account_id; } } @JsonProperty("status") private ResponseStatus status; @JsonProperty("response") private CheckLinkStatusResponse checkLinkStatusResponse; public ResponseStatus getCommon() { return status; } public void setCommon(ResponseStatus s) { status = s; } public CheckLinkStatusResponse getResponse() { return checkLinkStatusResponse; } public void setResponse(CheckLinkStatusResponse s) { checkLinkStatusResponse = s; } /** * This method verifies all data returned from service is valid * * @return true if all request data is valid */ public boolean validateCheckLinkStatusData(){ boolean valid; valid = ((checkLinkStatusResponse.getAccess_token() != null) && (checkLinkStatusResponse.getAccount_id() != null) && (checkLinkStatusResponse.getBrandName() != null) && (checkLinkStatusResponse.getExpires_in() != null) && (checkLinkStatusResponse.getScope() != null) && (checkLinkStatusResponse.getToken_type() != null) && (checkLinkStatusResponse.getSourceSystem() != null)); return valid; } }
true
b869cb9d41562ea8f2f170b40260cb80ce0a654a
Java
selvin270/sistema-restaurante-backend
/src/main/java/com/example/democrud/controller/TiendaController.java
UTF-8
1,415
2.09375
2
[]
no_license
package com.example.democrud.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.example.democrud.model.tienda; import com.example.democrud.service.api.TiendaServiceAPI; @Controller @RequestMapping public class TiendaController { @Autowired private TiendaServiceAPI tiendaServiceAPI; @RequestMapping("tiendas") public String index(Model model) { model.addAttribute("list", tiendaServiceAPI.getAll()); return "mostrar_tiendas"; } @GetMapping("/editar_tienda/{id}") public String showSave(@PathVariable("id") Long id , Model model) { if(id != null && id != 0) { model.addAttribute("tienda", tiendaServiceAPI.get(id)); }else { model.addAttribute("tienda", new tienda()); } return "nueva_tienda"; } @PostMapping("/nueva_tienda") public String save(tienda tienda, Model model) { tiendaServiceAPI.save(tienda); return "redirect:/tiendas"; } @GetMapping("/borrar_tienda/{id}") public String delete(@PathVariable Long id, Model model) { tiendaServiceAPI.delete(id); return "redirect:/tiendas"; } }
true
1a64c02a91ca8542da289c4fc60b60a7a7702ccb
Java
scott-m-king/Time-Journal
/src/main/ui/components/CategoryChartComponent.java
UTF-8
3,039
3.03125
3
[]
no_license
package ui.components; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.input.MouseEvent; import javafx.geometry.Side; import javafx.scene.chart.PieChart; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; import model.CategoryList; import ui.UserInterface; // https://docs.oracle.com/javafx/2/charts/pie-chart.htm // Represents a Category Pichart component for to display on the user's homescreen public class CategoryChartComponent { private final UserInterface userInterface; public CategoryChartComponent(UserInterface userInterface) { this.userInterface = userInterface; } // REQUIRES: valid UserInterface object // EFFECTS: generates category piechart based on durations from CategoryList object public PieChart generate() { CategoryList categoryList = userInterface.getCurrentSession().getCategoryList(); ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(); for (int i = 0; i < categoryList.getSize(); i++) { pieChartData.add(new PieChart.Data(categoryList.get(i).getName(), categoryList.get(i).getDuration())); } PieChart chart = new PieChart(pieChartData); setPieChartPosition(chart); return chart; } // REQUIRES: a valid piechart // MODIFIES: this // EFFECTS: anchors piechart on screen such that it fills an empty Screen private void setPieChartPosition(PieChart chart) { chart.setLegendSide(Side.RIGHT); AnchorPane.setLeftAnchor(chart, 230.0); AnchorPane.setRightAnchor(chart, 30.0); AnchorPane.setTopAnchor(chart, 95.0); AnchorPane.setBottomAnchor(chart, 30.0); } // MODIFIES: this // EFFECTS: sets a hover event listener on each slice of the piechart public Label setHoverEffects(PieChart chart) { final Label caption = new Label(""); caption.setStyle("-fx-font-size: 22; -fx-text-fill: #383838 "); for (final PieChart.Data data : chart.getData()) { data.getNode().addEventHandler(MouseEvent.MOUSE_ENTERED, event -> setHoverLabel(caption, data)); } return caption; } // REQUIRES: at least one category in the CategoryList // MODIFIES: this // EFFECTS: sets hover effects of each category to show % time spent and total duration of given category private void setHoverLabel(Label caption, PieChart.Data data) { int currentCategoryDuration = userInterface.getCurrentSession().getTotalCategoryDuration(); double percentage = Math.round(data.getPieValue() / currentCategoryDuration * 100); int resultDuration = (int) data.getPieValue(); int resultPercentage = (int) percentage; caption.setText( resultDuration + " minutes spent on " + data.getName() + ". " + resultPercentage + "% overall. " ); } }
true
9dd8ad7d9903346ce92f41df026e81d1529564e8
Java
AlexJPo/otus-java-2017-11-alexjpo
/Lecture-07/src/test/java/ru/otus/DepartmentTest.java
UTF-8
2,343
2.953125
3
[]
no_license
package ru.otus; import org.junit.Before; import org.junit.Test; import ru.otus.command.Atm; import ru.otus.command.Department; import static org.junit.Assert.*; public class DepartmentTest { private Department department; @Before public void init() { department = new Department(); } @Test public void atmHasInitialState() { for (int i = 1; i < 3; i++) { Atm atm = new Atm(); atm.setInitialBalance(i, 100); atm.deposit(i, 500); department.register(atm); } assertEquals(department.getAtms().size(), 2); } @Test //может инициировать событие – восстановить состояние всех ATM до начального public void resetAllAtmsToInitialState() { for (int i = 1; i < 4; i++) { Atm atm = new Atm(); atm.setInitialBalance(i, 300); atm.deposit(i, 500); department.register(atm); } assertEquals(department.getAtms().size(), 3); int atmsBalanceBefore = department.getBalanceSum(); assertEquals(atmsBalanceBefore, 4800); department.reset(); int atmsBalanceAfter = department.getBalanceSum(); assertEquals(atmsBalanceAfter, 1800); } @Test //Приложение может содержать несколько ATM public void shouldStoreDepartment() { for (int i = 1; i < 3; i++) { Atm atm = new Atm(); atm.deposit(i, 500); department.register(atm); } assertEquals(department.getAtms().size(), 2); } @Test //Может собирать сумму остатков со всех ATM public void shouldReceiveSumBalanceFromAtms() { for (int i = 1; i < 3; i++) { Atm atm = new Atm(); atm.deposit(i, 100); atm.deposit(i, 200); atm.deposit(i, 500); department.register(atm); } int balanceSumBefore = department.getBalanceSum(); assertEquals(balanceSumBefore, 2400); department.getAtms().get(0).getMoney(200); department.getAtms().get(1).getMoney(100); int balanceSumAfter = department.getBalanceSum(); assertEquals(balanceSumAfter, 2100); } }
true
c2949b8640a52cff2bd518604b2b2a936193a83e
Java
Dasha-And/Servlet-API-project
/src/main/java/home/work/web/AccountBalanceServlet.java
UTF-8
3,175
2.625
3
[]
no_license
package home.work.web; import com.fasterxml.jackson.databind.ObjectMapper; import home.work.domain.AccountRepository; import home.work.web.model.AccountDetails; import home.work.web.model.Transaction; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.StringWriter; import java.sql.SQLException; import java.util.List; //ToDo: make this class a servlet @WebServlet("/balance") public class AccountBalanceServlet extends HttpServlet { private AccountRepository accountRepository; private ObjectMapper objectMapper; private static final String JDBC_DRIVER = "org.h2.Driver"; // private static final String DB_URL = "jdbc:h2:~/test"; // private static final String USERNAME = "sa"; // private static final String PASSWORD = ""; //ToDo: initialize servlet's dependencies public void init() { try { Class.forName(JDBC_DRIVER); accountRepository = new AccountRepository(); accountRepository.init(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } objectMapper = new ObjectMapper(); } //ToDo: implement "get" method that will return all available user balances. // Check accountRepository to see what DB communication methods can be used public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } List<AccountDetails> list = null; try { //Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); list = accountRepository.getAllAccountDetails(); } catch (SQLException throwables) { throwables.printStackTrace(); } resp.getWriter().write("["); if (!list.isEmpty()) { for (int i = 0; i < list.size() - 1; i++) { StringWriter writer = new StringWriter(); objectMapper.writeValue(writer, list.get(i)); String result = writer.toString(); resp.getWriter().write(result + ",\n"); } StringWriter writer = new StringWriter(); objectMapper.writeValue(writer, list.get(list.size() - 1)); resp.getWriter().write(writer.toString()); } resp.getWriter().write("]"); } //ToDo: implement "post" method that will update account balance. // Check accountRepository to see what DB communication methods can be used public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { BufferedReader reader = req.getReader(); Transaction transaction = objectMapper.readValue(reader, Transaction.class); AccountDetails accountDetails; try { accountDetails = accountRepository.updateBalance(transaction); StringWriter writer = new StringWriter(); objectMapper.writeValue(writer, accountDetails); String result = writer.toString(); resp.getWriter().write(result + "\n"); } catch (SQLException throwables) { throwables.printStackTrace(); } } }
true
951099f5c289f841d4ccdf28d2edfacb4cc613bd
Java
FBL-Coder/ChuangKeYuan
/src/com/yitong/ChuangKeYuan/utils/UiUtils.java
UTF-8
2,822
2.53125
3
[ "Apache-2.0" ]
permissive
package com.yitong.ChuangKeYuan.utils; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.drawable.Drawable; import android.os.Handler; import android.view.View; import com.yitong.ChuangKeYuan.Application.MyApplication; /** * Created by Say GoBay on 2016/5/12. * ui操作处理的工具类 */ public class UiUtils { //获取context对象 public static Context getContext() { return MyApplication.getContext(); } //获取handler对象 public static Handler getMainThreadHandler() { return MyApplication.getHandler(); } //获取主线程的线程id public static int getMainThreadId() { return MyApplication.getMainThreadId(); } //获取字符串资源 public static String getString(int resId) { return getContext().getResources().getString(resId); } //获取字符串数组资源 public static String[] getStringArray(int resId) { return getContext().getResources().getStringArray(resId); } //获取drawable public static Drawable getDrawable(int resId) { return getContext().getResources().getDrawable(resId); } //获取color public static int getColor(int resId) { return getContext().getResources().getColor(resId); } //获取颜色的状态选择器 public static ColorStateList getColorStateList(int resId) { return getContext().getResources().getColorStateList(resId); } //获取dimen下的值 public static int getDimen(int resId) { return getContext().getResources().getDimensionPixelSize(resId); } // dp--px public static int dip2px(int dp) { float density = getContext().getResources().getDisplayMetrics().density;//获取屏幕密度 return (int) (dp*density + 0.5); } //px--dp public static int px2dip(int px) { float density = getContext().getResources().getDisplayMetrics().density;//获取屏幕密度 return (int) (px/density + 0.5); } //判断当前线程是否是主线程 public static boolean isRunOnUiThread() { //获取主线程的线程id int mainThreadId = getMainThreadId(); //获取当前线程的id int currentThreadId = android.os.Process.myTid(); return mainThreadId == currentThreadId; } //保证r一定运行在主线程中 public static void runOnUiThread(Runnable r) { if(isRunOnUiThread()) { //在主线程 r.run(); } else { //不在主线程 将r丢到主线程的消息队列里面 getMainThreadHandler().post(r); } } //加载布局 public static View inflateView(int resId) { return View.inflate(getContext(), resId, null); } }
true
d9599533c288a17ad8e2dbbe2d67c042dc8af2d3
Java
waldenwang7678/JavaDesignMode
/app/src/main/java/com/walden/javadesignmode/mode/commandmode/group/PageGroup.java
UTF-8
568
2.125
2
[]
no_license
package com.walden.javadesignmode.mode.commandmode.group; /** * Created by walden on 2017/7/12. */ public class PageGroup implements Group { @Override public String find() { return "找到美工组"; } @Override public String add() { return "增加页面"; } @Override public String delete() { return "删除页面"; } @Override public String change() { return "改变页面"; } @Override public String plan() { return "客户要求页面变更计划..."; } }
true
af336db759baae972240aa03c398edabc6ebcbf6
Java
JohnMendozaC/AndroidCitaMedicaAll
/CitaMedica2/app/src/main/java/com/compilado/johnm/citamedica2/ui/injection/Injection.java
UTF-8
2,246
2.09375
2
[]
no_license
package com.compilado.johnm.citamedica2.ui.injection; import android.content.Context; import com.compilado.johnm.citamedica2.persistence.DataBaseCita; import com.compilado.johnm.citamedica2.persistence.localdatasource.HistorialPacienteDataSource; import com.compilado.johnm.citamedica2.persistence.localdatasource.MedicoDataSource; import com.compilado.johnm.citamedica2.persistence.localdatasource.PacienteDataSource; import com.compilado.johnm.citamedica2.persistence.vo.HistorialPaciente; import com.compilado.johnm.citamedica2.ui.viewmodelfactory.HistorialPacienteVMFactory; import com.compilado.johnm.citamedica2.ui.viewmodelfactory.MedicoVMFactory; import com.compilado.johnm.citamedica2.ui.viewmodelfactory.PacienteVMFactory; public class Injection { //Injection Medico public static MedicoDataSource provideMedicoDataSource(Context context){ DataBaseCita dataBaseCita = DataBaseCita.getInstance(context); return new MedicoDataSource(dataBaseCita.medicoDao()); } public static MedicoVMFactory provideMedicoViewModelFactory(Context context){ MedicoDataSource dataSource = provideMedicoDataSource(context); return new MedicoVMFactory(dataSource); } //Injection Paciente public static PacienteDataSource providePacienteDataSource(Context context){ DataBaseCita dataBaseCita = DataBaseCita.getInstance(context); return new PacienteDataSource(dataBaseCita.pacienteDao()); } public static PacienteVMFactory providePacienteViewModelFactory(Context context){ PacienteDataSource dataSource = providePacienteDataSource(context); return new PacienteVMFactory(dataSource); } //Injection Historial Paciente public static HistorialPacienteDataSource provideHistorialPacienteDataSource(Context context){ DataBaseCita dataBaseCita = DataBaseCita.getInstance(context); return new HistorialPacienteDataSource(dataBaseCita.historialPacienteDao()); } public static HistorialPacienteVMFactory provideHistorialPacienteViewModelFactory(Context context){ HistorialPacienteDataSource dataSource = provideHistorialPacienteDataSource(context); return new HistorialPacienteVMFactory(dataSource); } }
true
8423bd3b0bdf22085e3f1582578a8e8bf84cc4cf
Java
DennisD2/vxiclient
/test/src/test/java/de/spurtikus/vxi/connectors/GPIBSerialConnectorBaseTest.java
UTF-8
1,830
2.34375
2
[]
no_license
package de.spurtikus.vxi.connectors; import static org.junit.Assert.assertNotNull; import java.util.stream.Stream; import org.junit.Before; import org.junit.Test; import de.spurtikus.vxi.Constants; import de.spurtikus.vxi.connectors.serial.GPIBSerialConnectorConfig; import de.spurtikus.vxi.service.Configuration; public class GPIBSerialConnectorBaseTest { static final String TEST_DEVICE_NAME = "hp1301"; GPIBSerialConnectorConfig config = null; VXIConnector vxiConnector = null; String deviceId = null; @Before public void before() throws Exception { // Get connection config for Adapter with Id==1 (serial connector) Configuration.load(); Stream<ConnectorConfig> ccc = Configuration.getEnabledConfigs().stream().filter(c->c.getId()==Constants.SERIAL_CONFIG); config = (GPIBSerialConnectorConfig) ccc.findAny().get(); assertNotNull(config); // Get connector for that configuration vxiConnector = VXIConnectorFactory.getConnector(config); } @Test public void serialConnector_getDeviceIdByName() throws Exception { System.out.println("Start..."); String deviceId = config.getDeviceIdByName(TEST_DEVICE_NAME); assertNotNull(deviceId); System.out.println(TEST_DEVICE_NAME + " --> " + deviceId); System.out.println("...done"); } @Test public void serialConnector_SimpleTest() throws Exception { System.out.println("Start..."); // Get deviceId for the device to use in test deviceId = Configuration.getDeviceIdByName(config.getId(), TEST_DEVICE_NAME); DeviceLink theLid = vxiConnector.initialize(config, deviceId); String cmd = "*IDN?"; System.out.println("Command: " + cmd); vxiConnector.send(theLid, cmd); // Receive answer String answer = vxiConnector.receive(theLid); System.out.println("Answer: " + answer); System.out.println("...done"); } }
true
bb6c9f0aabd858bfd4fc57545a2d19331f04f1fe
Java
zhongyuanwumingwansheng/demo
/src/main/java/com/example/demo/util/NumberUtil.java
UTF-8
1,738
2.703125
3
[]
no_license
package com.example.demo.util; import org.apache.commons.lang3.StringUtils; import org.apache.mahout.cf.taste.impl.model.MemoryIDMigrator; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class NumberUtil { public static Long characterToLong(String srcText){ if(!StringUtils.isBlank(srcText)){ } MemoryIDMigrator thing2long = new MemoryIDMigrator(); Long longText = thing2long.toLongID(srcText); return longText; } public static void testDivision(){ String str = " 12 3 "; System.out.println(str); System.out.println(str.trim()); List<Character> chars = new ArrayList<>(); Math.pow(10,2); int i = 122/(int)Math.pow(10,2); System.out.println(i); } public static void testConvertNumber(){ //String str = "-2147483649"; String str = "99999999999999999"; BigInteger bigInteger = new BigInteger(str); BigInteger intMax = new BigInteger(String.valueOf(Integer.MAX_VALUE)); BigInteger intMin = new BigInteger(String.valueOf(Integer.MIN_VALUE)); str.substring(1); //int i = Integer.parseInt(str); System.out.println(bigInteger.intValue()); if(bigInteger.compareTo(intMax)>0){ System.out.println(Integer.MAX_VALUE); } if(bigInteger.compareTo(intMin)<0){ System.out.println(Integer.MIN_VALUE); } int i = Integer.valueOf('0'+""); System.out.println(i); int[] height = new int[]{4,3,2,1,4}; System.out.println(height.length); } public static void main(String[] args){ NumberUtil.testConvertNumber(); } }
true
646691a452abd5c2a2c0516de9b59783ab492fb5
Java
kryvokhyzha/examples-and-courses
/spark-training/spring/hashtag-to-mysql/src/main/java/com/dimajix/training/hashtag2mysql/model/repo/HashtagEntry.java
UTF-8
480
2.109375
2
[ "MIT" ]
permissive
package com.dimajix.training.hashtag2mysql.model.repo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import java.time.ZonedDateTime; @Data @Entity @AllArgsConstructor @NoArgsConstructor @IdClass(HashtagId.class) public class HashtagEntry { @Id private ZonedDateTime ts; @Id private String topic; private long count; }
true
4fdd61a35488fbf85e170ea61c45b41e01820a89
Java
BranislavNovak/ChatAppCheckPoint3
/app/src/main/java/com/example/branislavnovak/chatapplication/Contact.java
UTF-8
720
2.59375
3
[]
no_license
package com.example.branislavnovak.chatapplication; /** * Created by Branislav Novak on 20-Apr-18. */ public class Contact { private String mContactID; private String mUserName; private String mFirstName; private String mLastName; public Contact(String id, String userName, String firstName, String lastName){ mContactID = id; mUserName = userName; mFirstName = firstName; mLastName = lastName; } public String getmID() { return mContactID; } public String getmUserName() { return mUserName; } public String getmFirstName() { return mFirstName; } public String getmLastName() { return mLastName; } }
true
96b7129c2398294264e27bebddead524bbc81b7d
Java
heweidong1/itripbackend
/itripbiz/src/main/java/cn/kgc/itrip/biz/service/Impl/HotelServiceImpl.java
UTF-8
6,780
2.21875
2
[]
no_license
package cn.kgc.itrip.biz.service.Impl; import cn.kgc.itrip.beans.common.ResponseCode; import cn.kgc.itrip.beans.common.ServerResponse; import cn.kgc.itrip.beans.pojo.ItripAreaDic; import cn.kgc.itrip.beans.pojo.ItripHotel; import cn.kgc.itrip.beans.pojo.ItripLabelDic; import cn.kgc.itrip.beans.vo.*; import cn.kgc.itrip.biz.service.IHotelService; import cn.kgc.itrip.mapper.itripAreaDic.ItripAreaDicMapper; import cn.kgc.itrip.mapper.itripHotel.ItripHotelMapper; import cn.kgc.itrip.mapper.itripImage.ItripImageMapper; import cn.kgc.itrip.mapper.itripLabelDic.ItripLabelDicMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service @Slf4j public class HotelServiceImpl implements IHotelService { @Autowired private ItripAreaDicMapper itripAreaDicMapper; @Autowired private ItripImageMapper itripImageMapper; @Autowired private ItripHotelMapper itripHotelMapper; @Autowired private ItripLabelDicMapper itripLabelDicMapper; @Override public ServerResponse<List<ItripTradeAreaVO>> queryTradeList(Integer cityId) throws Exception { if(cityId==null||cityId==0) { return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getDesc()); } List<ItripTradeAreaVO> itripTradeAreaVOS = itripAreaDicMapper.queryTradeArea(cityId); return ServerResponse.createBySuccess(itripTradeAreaVOS); } @Override public ServerResponse<List<ItripHotelImageVO>> queryImageByTargerId(Long targetId, String type)throws Exception { if(StringUtils.isEmpty(type)) { type="0"; } List<ItripHotelImageVO> itripHotelImageVOS = itripImageMapper.queryHotelImage(targetId, type); return ServerResponse.createBySuccess(itripHotelImageVOS); } @Override public ServerResponse queryHotelByHotelId(Long hotelId) throws Exception { HotelVideoDescVO hotelVideoDescVO=new HotelVideoDescVO(); if(hotelId==null) { return ServerResponse.createByErrorMessage("酒店id不能为空"); } try { //获取特色 List<ItripAreaDic> itripAreaDics = itripAreaDicMapper.queryItripHotelFeatureByHotelId(hotelId); List<String> featureLsit = new ArrayList<>(); for(ItripAreaDic trade:itripAreaDics) { featureLsit.add(trade.getName()); } hotelVideoDescVO.setHotelFeatureList(featureLsit); //获取商圈 List<ItripTradeAreaVO> itripTradeAreaVOS1 = itripAreaDicMapper.queryTradeAreaByHotelId(hotelId); List<String> areaNameLsit = new ArrayList<>(); for(ItripTradeAreaVO trade:itripTradeAreaVOS1) { areaNameLsit.add(trade.getName()); } hotelVideoDescVO.setTradingAreaNameList(areaNameLsit); //h获取酒店名字 ItripHotel itripHotel = itripAreaDicMapper.queryItripHotelByHotelId(hotelId); hotelVideoDescVO.setHotelName(itripHotel.getHotelName()); return ServerResponse.createBySuccess(hotelVideoDescVO); }catch (Exception e) { e.printStackTrace(); return ServerResponse.createByErrorMessage("获取酒店信息失败"); } } @Override public ServerResponse queryHotelfacilitiesByHotelId(Long HotelId)throws Exception { ItripHotel itripHotel = itripHotelMapper.queryHotelfacilitiesByHotelId(HotelId); if(itripHotel==null) { return ServerResponse.createByErrorMessage("获取失败"); } return ServerResponse.createBySuccess(itripHotel.getFacilities()); } /** * 查询酒店特色 * @return * @throws Exception */ @Override public ServerResponse queryhotelfeature() throws Exception { Map<String,Object> param = new HashMap<>(); param.put("parentId",16); List<ItripLabelDic> itripLabelDicListByMap = itripLabelDicMapper.getItripLabelDicListByMap(param); return ServerResponse.createBySuccess(itripLabelDicListByMap); } @Override public ServerResponse queryhotcity(Integer type)throws Exception { Map<String,Object> param = new HashMap<>(); param.put("isChina",type); param.put("isHot",1); List<ItripAreaDic> itripAreaDicListByMap = itripAreaDicMapper.getItripAreaDicListByMap(param); if(itripAreaDicListByMap==null) { return ServerResponse.createByErrorMessage("获取失败"); } return ServerResponse.createBySuccess(itripAreaDicListByMap); } /** * 根据酒店id查询特色和介绍 */ @Override public ServerResponse queryhoteldetails(Long id)throws Exception { List<ItripAreaDic> itripAreaDics = itripAreaDicMapper.queryItripHotelFeatureByHotelId(id); List<ItripSearchDetailsHotelVO> ouput = new ArrayList<>(); //封装特色 for(ItripAreaDic itripAreaDic:itripAreaDics) { ItripSearchDetailsHotelVO itripSearchDetailsHotelVO=new ItripSearchDetailsHotelVO(); BeanUtils.copyProperties(itripAreaDic,itripSearchDetailsHotelVO); ouput.add(itripSearchDetailsHotelVO); } //封装介绍 ItripHotel itripHotelById = itripHotelMapper.getItripHotelById(id); ItripSearchDetailsHotelVO itripSearchDetailsHotelVO=new ItripSearchDetailsHotelVO(); itripSearchDetailsHotelVO.setName("酒店介绍"); itripSearchDetailsHotelVO.setDescription(itripHotelById.getDetails()); ouput.add(itripSearchDetailsHotelVO); return ServerResponse.createBySuccess(ouput); } /** * 根据酒店id查询酒店政策 */ @Override public ServerResponse queryhotelpolicy(Long id)throws Exception { if(id==null) { return ServerResponse.createByErrorMessage("酒店id不能为空"); } ItripHotel itripHotelById = itripHotelMapper.getItripHotelById(id); if(itripHotelById==null) { return ServerResponse.createByErrorMessage("获取失败"); } ItripSearchFacilitiesHotelVO itripSearchFacilitiesHotelVO=new ItripSearchFacilitiesHotelVO(); itripSearchFacilitiesHotelVO.setFacilities(itripHotelById.getHotelPolicy()); return ServerResponse.createBySuccess(itripSearchFacilitiesHotelVO); } }
true
e54f0b0b9fa07ddcbe7013b8fc66d4f3e47a3f0d
Java
ahmedGemez/BellManTask
/app/src/main/java/com/bahr/assessmenttask/MainActivity.java
UTF-8
6,491
1.75
2
[]
no_license
package com.bahr.assessmenttask; import android.os.Bundle; import com.bahr.assessmenttask.Utils.BellButtonAnimation; import com.bahr.assessmenttask.adapters.AttractionAdapter; import com.bahr.assessmenttask.adapters.EventsAdapter; import com.bahr.assessmenttask.adapters.HotSpotsAdapter; import com.bahr.assessmenttask.databinding.ActivityMainBinding; import com.bahr.assessmenttask.model.Data; import com.bahr.assessmenttask.model.Event; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.RelativeLayout; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements MainRepository.ListenToChangeConnection { private MainViewModel mainViewModel; private HotSpotsAdapter hotSpotsAdapter; private EventsAdapter eventsAdapter; private AttractionAdapter attractionAdapter; private RelativeLayout progress; private RelativeLayout noConnection; private boolean fabFlag=false; Animation show_fab_1 ; Animation show_fab_2 ; Animation show_fab_3 ; Animation show_fab_4 ; Animation hide_fab_1 ; FrameLayout fab1 ; FrameLayout fab2 ; FrameLayout fab3 ; FrameLayout fab4 ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); progress = activityMainBinding.content.progress; noConnection = activityMainBinding.content.noConnection; // bind hotSpotsRecycle RecyclerView recyclerView = activityMainBinding.content.hotSpotsRecycle; LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); // bind EventsRecycle RecyclerView eventRecyclerView = activityMainBinding.content.eventsRecycle; LinearLayoutManager layoutManager1 = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); eventRecyclerView.setLayoutManager(layoutManager1); eventRecyclerView.setHasFixedSize(true); // bind AttractionRecycle RecyclerView attractionRecyclerView = activityMainBinding.content.attractionRecycle; LinearLayoutManager layoutManager2 = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); attractionRecyclerView.setLayoutManager(layoutManager2); attractionRecyclerView.setHasFixedSize(true); mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class); hotSpotsAdapter = new HotSpotsAdapter(); recyclerView.setAdapter(hotSpotsAdapter); eventsAdapter = new EventsAdapter(); eventRecyclerView.setAdapter(eventsAdapter); attractionAdapter = new AttractionAdapter(); attractionRecyclerView.setAdapter(attractionAdapter); progress.setVisibility(View.VISIBLE); mainViewModel.getData(this).observe(this, new Observer<Data>() { @Override public void onChanged(@Nullable Data data) { hotSpotsAdapter.setHotSpotList((data.getData().getHotSpots())); eventsAdapter.setEventsList((data.getData().getEvents())); attractionAdapter.setAttractionList((data.getData().getAttractions())); } }); show_fab_1 = AnimationUtils.loadAnimation(getApplication(), R.anim.fab1_show); show_fab_2 = AnimationUtils.loadAnimation(getApplication(), R.anim.fab2_show); show_fab_3 = AnimationUtils.loadAnimation(getApplication(), R.anim.fab3_show); show_fab_4 = AnimationUtils.loadAnimation(getApplication(), R.anim.fab4_show); hide_fab_1 = AnimationUtils.loadAnimation(getApplication(), R.anim.fab1_hide); FloatingActionButton fab = findViewById(R.id.fab); fab1 = findViewById(R.id.fab_1); fab2 = findViewById(R.id.fab_2); fab3 = findViewById(R.id.fab_3); fab4 = findViewById(R.id.fab_4); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(fabFlag) { BellButtonAnimation.onClickBellButton(fabFlag,fab1,fab2,fab3,fab4,show_fab_1,show_fab_2 ,show_fab_3,show_fab_4,hide_fab_1); fabFlag=!fabFlag; }else{ BellButtonAnimation.onClickBellButton(fabFlag,fab1,fab2,fab3,fab4,show_fab_1,show_fab_2 ,show_fab_3,show_fab_4,hide_fab_1); fabFlag=!fabFlag; } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void resultConnection(int status) { progress.setVisibility(View.GONE); if(status==Constants.Fail){ noConnection.setVisibility(View.VISIBLE); } } }
true
89202ad4d44f09b562e220d6882c97004f36815f
Java
axonasif/gearlock-termemu-wrapper
/term/src/main/java/com/termoneplus/utils/ThemeManager.java
UTF-8
3,533
1.960938
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2019-2020 Roumen Petrov. 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.termoneplus.utils; import android.content.Context; import android.content.SharedPreferences; import android.view.Gravity; import android.widget.Toast; import com.termoneplus.R; import java.io.File; import androidx.preference.PreferenceManager; public class ThemeManager { public static final String PREF_THEME_MODE = "thememode"; private static final String PREFERENCES_FILE = "file_selection"; /*obsolete*/ private static final String PREFERENCE_LIGHT_THEME = "light_theme"; /*obsolete*/ public static void migrateFileSelectionThemeMode(Context context) { SharedPreferences preferences = context.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE); if (!preferences.contains(PREFERENCE_LIGHT_THEME)) return; boolean light_theme = preferences.getBoolean(PREFERENCE_LIGHT_THEME, false); Toast toast = Toast.makeText(context.getApplicationContext(), "Migrate \"File Selection\" theme mode", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); preferences.edit().remove(PREFERENCE_LIGHT_THEME).commit(); // Note obsolete "FileSelection" preferences have only one item - light_theme! { File prefs_path = new File(context.getFilesDir().getParentFile(), "shared_prefs"); File[] list = prefs_path.listFiles((dir, name) -> name.startsWith(PREFERENCES_FILE)); if (list != null) for (File file : list) //noinspection ResultOfMethodCallIgnored file.delete(); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor prefs_editor = prefs.edit(); if (light_theme) prefs_editor.putString(PREF_THEME_MODE, "light"); else prefs_editor.putString(PREF_THEME_MODE, "dark"); prefs_editor.apply(); } public static int presetTheme(Context context, boolean actionbar, int resid) { final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); String mode = sharedPreferences.getString(PREF_THEME_MODE, ""); if (mode.equals("")) mode = context.getResources().getString(R.string.pref_thememode_default); switch (mode) { case "dark": resid = actionbar ? R.style.AppTheme : R.style.AppTheme_NoActionBar; break; case "light": resid = actionbar ? R.style.AppTheme_Light : R.style.AppTheme_Light_NoActionBar; break; case "system": resid = actionbar ? R.style.AppTheme_DayNight : R.style.AppTheme_DayNight_NoActionBar; break; } return resid; } }
true
14faeec689a8c39e5d2a038ac4c1900ddfef3362
Java
yamato3310/-
/2/Review01/src/Student.java
UTF-8
1,316
3.90625
4
[]
no_license
public class Student { private String id; //学籍番号 private String name; //氏名 private int bYear, bMonth, bDay; //誕生年・月・日 public Student(String id, String name, int bYear, int bMonth, int bDay) { this.id = id; //各フィールドに値を代入*4 this.name = name; this.bYear = bYear; this.bMonth = bMonth; this.bDay = bDay; } //学籍番号を返すメソッド(Getter) public String getId(){ return id; } //氏名を返すメソッド(Getter) public String getName(){ return name; } //氏名を変更するメソッド(Setter) public void setName(String name){ this.name = name; } //誕生日を整形した文字列で返すメソッド public String getBirthDayString(){ String buf; buf = bYear + "/"; buf = buf + bMonth + "/"; buf = buf + bDay; return buf; } //引数に渡された日付時点での年齢を計算して返すメソッド public int calcAge(int compYear, int compMonth, int compDay){ int age = compYear - bYear; //とりあえず誕生日後の年齢 if(compMonth*100+compDay < bMonth*100+bDay){ //誕生日前の場合 age--; //年齢を調整 } return age; } }
true
fc417d04164020fe1769c7db85760ed061f75f75
Java
10Duke/10duke-java-client
/openid/src/main/java/com/tenduke/client/openid/OpenIdAuthorizationCodeClient.java
UTF-8
3,310
2.28125
2
[ "MIT" ]
permissive
/* * Copyright (c) 2019 10Duke. All rights reserved. * * This work is licensed under the terms of the MIT license. * https://opensource.org/licenses/MIT * */ package com.tenduke.client.openid; import com.tenduke.client.json.DefaultJsonDeserializer; import com.tenduke.client.json.JsonDeserializer; import com.tenduke.client.jwt.DefaultJwtParserFactory; import com.tenduke.client.oauth.OAuthClient; import static com.tenduke.client.oauth.authorizationcode.AuthorizationCodeClient.DEFAULT_HTTP_CLIENT; import com.tenduke.client.oauth.exceptions.OAuthException; import java.net.http.HttpClient; /** * Client for OpenId Connect with Authorization Code flow. * * <p> * NOTE: Client automatically adds the {@code openid} scope to the request. * * <p> * NOTE: Client automatically adds {@code nonce} to the request, if none is provided. Caller can provide {@code nonce} * either by passing it as a parameter or using method {@link OpenIdAuthorizationCodeFlowBuilder#nonce(java.lang.String) }. * */ public class OpenIdAuthorizationCodeClient implements OAuthClient { /** Configuration. */ private final OpenIdAuthorizationCodeConfig config; /** ID-token validator. */ private final IdTokenValidator idTokenValidator; /** Creates token requests. */ private final OpenIdAuthorizationCodeTokenRequestFactory tokenRequestFactory; /** * Constructs new instance. * * @param config - */ public OpenIdAuthorizationCodeClient(final OpenIdAuthorizationCodeConfig config) { this( config, DEFAULT_HTTP_CLIENT, new IdTokenParser(DefaultJwtParserFactory.INSTANCE.create(config.getSignatureVerificationKey())), new IdTokenValidator(config.getClientId(), config.getIssuer()), DefaultJsonDeserializer.INSTANCE.get() ); } /** * Constructs new instance. * * @param config - * @param httpClient - * @param idtokenParser - * @param idTokenValidator - * @param jsonDeserializer - */ public OpenIdAuthorizationCodeClient( final OpenIdAuthorizationCodeConfig config, final HttpClient httpClient, final IdTokenParser idtokenParser, final IdTokenValidator idTokenValidator, final JsonDeserializer jsonDeserializer ) { this.config = config; this.idTokenValidator = idTokenValidator; this.tokenRequestFactory = new OpenIdAuthorizationCodeTokenRequestFactory(config, httpClient, jsonDeserializer, idtokenParser); } /** * {@inheritDoc} * */ @Override public OpenIdAuthorizationCodeFlowBuilder request() { return new OpenIdAuthorizationCodeFlowBuilder( config, idTokenValidator, tokenRequestFactory ); } /** * Refreshes the access token with refresh token. * * @param refreshToken - * @return - * @throws InterruptedException - * @throws OAuthException - */ public OpenIdAuthorizationCodeResponse refresh(final String refreshToken) throws InterruptedException, OAuthException { return tokenRequestFactory.refresh(refreshToken, "refresh-" + System.currentTimeMillis()).call(); } }
true
86615a52d7b6c62bb5c7d60b17d76180acf0cd34
Java
cckmit/Test1-1
/java/video-converter/trunk/video-converter/src/java/com/scopix/periscope/converter/ffmpeg/FFMPEGProcessBuilder.java
UTF-8
2,209
2.328125
2
[]
no_license
/* * * Copyright (C) 2007, SCOPIX. All rights reserved. * * This software and its documentation contains proprietary information and can * only be used under a license agreement containing restrictions on its use and * disclosure. It is protected by copyright, patent and other intellectual and * industrial property laws. Copy, reverse engineering, disassembly or * decompilation of all or part of it, except to the extent required to obtain * interoperability with other independently created software as specified by a * license agreement, is prohibited. * * * FFMPEGProcessBuilder.java * * Created on 03-07-2013, 10:52:00 AM * */ package com.scopix.periscope.converter.ffmpeg; import com.scopix.periscope.periscopefoundation.exception.ScopixException; import java.io.IOException; import org.apache.log4j.Logger; /** * Controlador encargado de la inicialización de los procesos de * conversión de videos * * @author carlos polo * @version 1.0.0 * @since 6.0 */ public class FFMPEGProcessBuilder { private String[] params; private static Logger log = Logger.getLogger(FFMPEGProcessBuilder.class); /** * Ejecuta comando de conversión de videos con sus correspondientes * parámetros * * @author carlos polo * @date 03-jul-2013 * @return Process proceso de conversión ejecutado * @throws ScopixException excepción durante la conversión */ public Process start() throws ScopixException { log.info("start"); Process process = null; try { ProcessBuilder builder = new ProcessBuilder(); builder.redirectErrorStream(true); builder.command(getParams()); //builder.directory(new File("/tmp")); process = builder.start(); } catch (IOException e) { throw new ScopixException(e.getMessage(), e); } log.info("end"); return process; } /** * @return the params */ public String[] getParams() { return params; } /** * @param params the params to set */ public void setParams(String[] params) { this.params = params; } }
true
73558a17d62233415cae5c8ceaddddaefde8e654
Java
Supernorwood/javaHardWay
/RudeQuestions.java
UTF-8
1,283
3.875
4
[]
no_license
import java.util.Scanner; public class RudeQuestions { public static void main( String[] args ) { String name, reside; int age; double weight, income; Scanner keyboard = new Scanner(System.in); System.out.print( "Hello. What is your name? " ); name = keyboard.next(); System.out.print( "Hi, " + name + "! How old are you? " ); age = keyboard.nextInt(); System.out.println( "So you're " + age + ",eh? That's not very old." ); System.out.print( "How much do you weigh, " + name + "? " ); weight = keyboard.nextDouble(); System.out.println( weight + "! Better keep that quiet!! " ); System.out.print( "Finally, what's your income, " + name + "? " ); income = keyboard.nextDouble(); System.out.print( "Hopefully that is " + income + " per hour " ); System.out.println( "and not per year! "); System.out.print( "Well, thanks for answering my rude questions, " ); System.out.println( name + ". " ); System.out.print( "Where do you want to reside " + name + "? " ); reside = keyboard.next(); //98.5 in age blew up the program. ln 15 set for int not double //no for numeric in string. I put number in name and no blow. //didn't blow up much, pretty resilient. } }
true
870d060e2201a8fab28cf6652ab01ab1cc27b693
Java
pain4508/INGBankPoo
/INGBank/src/presentacion/JIFraCuenta.java
UTF-8
23,628
1.992188
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package presentacion; import dao.ClienteDao; import dao.CuentaDao; import dao.MovimientoDao; import dao.TipoCuentaDao; import java.sql.SQLException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import logica.ClienteLogica; import logica.CuentaLogica; import logica.MovimientoLogica; import logica.NacionalidadLogica; import logica.TipoCuentaLogica; /** * * @author griselda */ public class JIFraCuenta extends javax.swing.JInternalFrame { /** * Creates new form JIFraCuenta */ public JIFraCuenta() { initComponents(); llenarCC(); llenarCTipoC(); habilitarBotones(true, false, false, false, false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTFIdCuenta = new javax.swing.JTextField(); jCboCliente = new javax.swing.JComboBox<>(); jCboTipoc = new javax.swing.JComboBox<>(); jScrollPane1 = new javax.swing.JScrollPane(); jTblCuenta = new javax.swing.JTable(); jBtnNuevo = new javax.swing.JButton(); jBtnGuardar = new javax.swing.JButton(); jBtnModificar = new javax.swing.JButton(); jBtnEliminar = new javax.swing.JButton(); jFTFSaldo = new javax.swing.JFormattedTextField(); jFTFFechaC = new javax.swing.JFormattedTextField(); setClosable(true); setIconifiable(true); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { formComponentShown(evt); } }); jPanel1.setBackground(new java.awt.Color(204, 204, 255)); jLabel6.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N jLabel6.setText("GESTIONAR CUENTA"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(241, 241, 241) .addComponent(jLabel6) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(jLabel6) .addContainerGap(19, Short.MAX_VALUE)) ); jPanel2.setBackground(new java.awt.Color(0, 153, 204)); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("IdCuenta"); jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Cliente Asociado"); jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Tipo Cuenta"); jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("Saldo "); jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Fecha Creacion"); jTblCuenta.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Numero Cuenta", "Cliente", "Tipo Cuenta", "Saldo Inicial", "Fecha de Creacion" } )); jTblCuenta.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jTblCuentaMousePressed(evt); } }); jScrollPane1.setViewportView(jTblCuenta); jBtnNuevo.setIcon(new javax.swing.ImageIcon("/Users/griselda/Documents/GitHub/INGBankPoo/INGBank/src/imagenes/new.png")); // NOI18N jBtnNuevo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnNuevoActionPerformed(evt); } }); jBtnGuardar.setIcon(new javax.swing.ImageIcon("/Users/griselda/Documents/GitHub/INGBankPoo/INGBank/src/imagenes/save.png")); // NOI18N jBtnGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnGuardarActionPerformed(evt); } }); jBtnModificar.setIcon(new javax.swing.ImageIcon("/Users/griselda/Documents/GitHub/INGBankPoo/INGBank/src/imagenes/edit.png")); // NOI18N jBtnModificar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnModificarActionPerformed(evt); } }); jBtnEliminar.setIcon(new javax.swing.ImageIcon("/Users/griselda/Documents/GitHub/INGBankPoo/INGBank/src/imagenes/delete.png")); // NOI18N jBtnEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnEliminarActionPerformed(evt); } }); jFTFSaldo.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00")))); try { jFTFFechaC.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####-##-##"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(288, 288, 288) .addComponent(jBtnNuevo) .addGap(18, 18, 18) .addComponent(jBtnGuardar) .addGap(18, 18, 18) .addComponent(jBtnModificar) .addGap(18, 18, 18) .addComponent(jBtnEliminar)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(26, 26, 26) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCboTipoc, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTFIdCuenta)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(48, 48, 48) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5) .addComponent(jLabel4)) .addGap(24, 24, 24) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jFTFSaldo, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE) .addComponent(jFTFFechaC)))) .addGap(0, 143, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel5) .addComponent(jTFIdCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jFTFFechaC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jCboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(jFTFSaldo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(13, 13, 13) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jCboTipoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(16, 16, 16) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jBtnModificar) .addComponent(jBtnGuardar) .addComponent(jBtnNuevo) .addComponent(jBtnEliminar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void limpiar() { jTFIdCuenta.setText(""); jFTFFechaC.setText(""); jFTFSaldo.setText(""); } private void guardarCuenta() { CuentaLogica c1 = new CuentaLogica(); c1.setIdCuenta(Integer.parseInt(this.jTFIdCuenta.getText())); c1.setIdCliente(this.jCboCliente.getSelectedIndex() + 1); c1.setIdTipoCuenta(this.jCboTipoc.getSelectedIndex() + 1); c1.setSaldo(Double.parseDouble(this.jFTFSaldo.getText())); c1.setFecha_de_Creacion(this.jFTFFechaC.getText()); try { CuentaDao dao = new CuentaDao(); dao.insertarCuenta(c1); JOptionPane.showMessageDialog(null, "Registro almacenado satisfactoriamente."); limpiar(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error al almacenar la Cuenta." + e); } } private void modificarCuenta() { CuentaLogica c1 = new CuentaLogica(); c1.setIdCuenta(Integer.parseInt(this.jTFIdCuenta.getText())); c1.setIdCliente(this.jCboCliente.getSelectedIndex() + 1); c1.setIdTipoCuenta(this.jCboTipoc.getSelectedIndex() + 1); c1.setFecha_de_Creacion(this.jFTFFechaC.getText()); c1.setSaldo(Double.parseDouble(this.jFTFSaldo.getText())); try { CuentaDao dao = new CuentaDao(); dao.modificarCuenta(c1); JOptionPane.showMessageDialog(null, "Registro modificado satisfactoriamente"); limpiar(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error al modificar Cliente" + e); } } private void eliminarCuenta() { CuentaLogica c1 = new CuentaLogica(); c1.setIdCuenta(Integer.parseInt(this.jTFIdCuenta.getText())); try { CuentaDao dao = new CuentaDao(); dao.eliminarCuenta(c1); JOptionPane.showMessageDialog(null, "Registro eliminado satisfactoriamente"); limpiar(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error al eliminar Cliente" + e); } } private void limpiarTabla() { DefaultTableModel temp = (DefaultTableModel) this.jTblCuenta.getModel(); // // Limpiar los datos de la tabla. while (temp.getRowCount() > 0) { temp.removeRow(0); } } private void llenarTCuenta() throws SQLException { limpiarTabla(); CuentaDao dao = new CuentaDao(); List<CuentaLogica> miLista = dao.getLista(); DefaultTableModel temp = (DefaultTableModel) this.jTblCuenta.getModel(); for (CuentaLogica c1 : miLista) { Object[] fila = new Object[5]; fila[0] = c1.getIdCuenta(); fila[1] = c1.getIdCliente(); fila[2] = c1.getIdTipoCuenta(); fila[3] = c1.getSaldo(); fila[4] = c1.getFecha_de_Creacion(); temp.addRow(fila); } } private void llenarCC() { try { TipoCuentaDao dao = new TipoCuentaDao(); jCboCliente.removeAllItems(); List<ClienteLogica> miComboCliente; miComboCliente = dao.getComboCliente(); for (int i = 0; i < miComboCliente.size(); i++) { jCboCliente.addItem(miComboCliente.get(i).getNombres()); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, e); } } private void llenarCTipoC() { try { TipoCuentaDao dao = new TipoCuentaDao(); jCboTipoc.removeAllItems(); List<TipoCuentaLogica> miComboTipoCuenta; miComboTipoCuenta = dao.getComboTipoC(); for (int i = 0; i < miComboTipoCuenta.size(); i++) { jCboTipoc.addItem(miComboTipoCuenta.get(i).getTipoCuenta()); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, e); } } private void investigarCorrelativo() throws SQLException { CuentaDao dao = new CuentaDao(); CuentaLogica c1 = new CuentaLogica(); c1.setIdCuenta(dao.autoIncrementar()); jTFIdCuenta.setText(String.valueOf(c1.getIdCuenta())); } private boolean verificarTextField() { boolean estado; if (jTFIdCuenta.getText().isEmpty() && jFTFFechaC.getText().isEmpty() && jFTFSaldo.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese los campos vacios"); jTFIdCuenta.requestFocus(); estado = false; }else if(jFTFFechaC.getText().isEmpty() && jFTFSaldo.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese los campos vacios"); jFTFFechaC.requestFocus(); estado = false; }else if (jFTFSaldo.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Ingrese los campos vacios"); jFTFSaldo.requestFocus(); estado = false; }else{ estado = true; } return estado; } private void habilitarBotones(boolean nuevo, boolean guardar, boolean modificar, boolean eliminar, boolean textField) { jTFIdCuenta.setEnabled(nuevo); jBtnGuardar.setEnabled(guardar); jBtnModificar.setEnabled(modificar); jBtnEliminar.setEnabled(eliminar); jTFIdCuenta.setEditable(textField); jCboCliente.setEditable(textField); jCboTipoc.setEditable(textField); jFTFFechaC.setEditable(textField); jFTFSaldo.setEditable(textField); } private void lineaSeleccionada() { if (this.jTblCuenta.getSelectedRow() != -1) { //Habilito los controles para que se pueda hacer una accion. if (this.jTblCuenta.isEnabled() == true) { this.jTFIdCuenta.setText(String.valueOf(this.jTblCuenta.getValueAt(jTblCuenta.getSelectedRow(), 0))); this.jFTFSaldo.setText(String.valueOf(this.jTblCuenta.getValueAt(jTblCuenta.getSelectedRow(), 3))); this.jFTFFechaC.setText(String.valueOf(this.jTblCuenta.getValueAt(jTblCuenta.getSelectedRow(), 4))); } } else { limpiar(); } } private void jBtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnGuardarActionPerformed if (verificarTextField() == true) { guardarCuenta(); habilitarBotones(true, false, false, false, false); try { llenarTCuenta(); } catch (SQLException ex) { Logger.getLogger(JIFraCliente.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jBtnGuardarActionPerformed private void jBtnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnNuevoActionPerformed limpiar(); habilitarBotones(false, true, false, false, true); try { investigarCorrelativo(); } catch (SQLException ex) { Logger.getLogger(JIFraCliente.class.getName()).log(Level.SEVERE, null, ex); } habilitarBotones(false, true, false, false, true); }//GEN-LAST:event_jBtnNuevoActionPerformed private void jTblCuentaMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTblCuentaMousePressed lineaSeleccionada(); habilitarBotones(false, false, true, true, false); }//GEN-LAST:event_jTblCuentaMousePressed private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown try { llenarTCuenta(); DefaultTableModel temp = (DefaultTableModel) this.jTblCuenta.getModel(); temp.fireTableDataChanged(); } catch (SQLException ex) { Logger.getLogger(JIFraCliente.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_formComponentShown private void jBtnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnModificarActionPerformed modificarCuenta(); try { llenarTCuenta(); } catch (SQLException ex) { Logger.getLogger(JIFraCliente.class.getName()).log(Level.SEVERE, null, ex); } habilitarBotones(true, false, false, false, false); }//GEN-LAST:event_jBtnModificarActionPerformed private void jBtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnEliminarActionPerformed if (JOptionPane.showConfirmDialog(null, "Esta seguro de eliminar el registro?", "Advertencia", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { eliminarCuenta(); try { llenarTCuenta(); } catch (SQLException ex) { Logger.getLogger(JIFraCliente.class.getName()).log(Level.SEVERE, null, ex); } habilitarBotones(true, false, false, false, false); } else { } }//GEN-LAST:event_jBtnEliminarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jBtnEliminar; private javax.swing.JButton jBtnGuardar; private javax.swing.JButton jBtnModificar; private javax.swing.JButton jBtnNuevo; private javax.swing.JComboBox<String> jCboCliente; private javax.swing.JComboBox<String> jCboTipoc; private javax.swing.JFormattedTextField jFTFFechaC; private javax.swing.JFormattedTextField jFTFSaldo; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField jTFIdCuenta; private javax.swing.JTable jTblCuenta; // End of variables declaration//GEN-END:variables }
true
edbbdf6ce0a558afc77618c1db806866d74af1ef
Java
pavel-borik/reactive-transaction-center
/server/tc-transactions/src/main/java/com/pb/tctransactions/repositories/ReactiveMongoConfig.java
UTF-8
1,165
1.96875
2
[]
no_license
package com.pb.tctransactions.repositories; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import lombok.AllArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration; import org.springframework.data.mongodb.core.ReactiveMongoTemplate; import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories; @Configuration @EnableReactiveMongoRepositories @AllArgsConstructor public class ReactiveMongoConfig extends AbstractReactiveMongoConfiguration { private Environment env; @Override public MongoClient reactiveMongoClient() { return MongoClients.create(); } @Override protected String getDatabaseName() { return env.getProperty("spring.data.mongodb.database"); } @Bean public ReactiveMongoTemplate reactiveMongoTemplate() { return new ReactiveMongoTemplate(reactiveMongoClient(), getDatabaseName()); } }
true
0675d2a48695e4b0ba6125cac5241811edeea446
Java
jcrane613/JonathanCrane
/DataStructures/project/stage2/src/test/java/edu/yu/cs/com1320/project/stage2/DocumentStoreImplTest.java
UTF-8
8,697
2.9375
3
[]
no_license
package edu.yu.cs.com1320.project.stage2.impl; import edu.yu.cs.com1320.project.Utils; import edu.yu.cs.com1320.project.stage2.DocumentStore; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.net.URI; import static org.junit.Assert.*; public class DocumentStoreImplTest { //variables to hold possible values for doc1 private URI uri1; private String txt1; private byte[] pdfData1; private String pdfTxt1; //variables to hold possible values for doc2 private URI uri2; private String txt2; private byte[] pdfData2; private String pdfTxt2; @Before public void init() throws Exception { //init possible values for doc1 this.uri1 = new URI("http://edu.yu.cs/com1320/project/doc1"); this.txt1 = "This is the text of doc1, in plain text. No fancy file format - just plain old String"; this.pdfTxt1 = "This is some PDF text for doc1, hat tip to Adobe."; this.pdfData1 = Utils.textToPdfData(this.pdfTxt1); //init possible values for doc2 this.uri2 = new URI("http://edu.yu.cs/com1320/project/doc2"); this.txt2 = "Text for doc2. A plain old String."; this.pdfTxt2 = "PDF content for doc2: PDF format was opened in 2008."; this.pdfData2 = Utils.textToPdfData(this.pdfTxt2); } @Test public void testPutPdfDocumentNoPreviousDocAtURI(){ DocumentStore store = new DocumentStoreImpl(); int returned = store.putDocument(new ByteArrayInputStream(this.pdfData1),this.uri1, DocumentStore.DocumentFormat.PDF); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue(returned == 0 || returned == this.pdfTxt1.hashCode()); } @Test public void testPutTxtDocumentNoPreviousDocAtURI(){ DocumentStore store = new DocumentStoreImpl(); int returned = store.putDocument(new ByteArrayInputStream(this.txt1.getBytes()),this.uri1, DocumentStore.DocumentFormat.TXT); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue(returned == 0 || returned == this.txt1.hashCode()); } @Test public void testPutDocumentWithNullArguments(){ DocumentStore store = new DocumentStoreImpl(); try { store.putDocument(new ByteArrayInputStream(this.txt1.getBytes()), null, DocumentStore.DocumentFormat.TXT); fail("null URI should've thrown IllegalArgumentException"); }catch(IllegalArgumentException e){} try { store.putDocument(new ByteArrayInputStream(this.txt1.getBytes()), this.uri1, null); fail("null format should've thrown IllegalArgumentException"); }catch(IllegalArgumentException e){} } @Test public void testPutNewVersionOfDocumentPdf(){ //put the first version DocumentStore store = new DocumentStoreImpl(); int returned = store.putDocument(new ByteArrayInputStream(this.pdfData1),this.uri1, DocumentStore.DocumentFormat.PDF); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue(returned == 0 || returned == this.pdfTxt1.hashCode()); assertEquals("failed to return correct pdf text",this.pdfTxt1,Utils.pdfDataToText(store.getDocumentAsPdf(this.uri1))); //put the second version, testing both return value of put and see if it gets the correct text returned = store.putDocument(new ByteArrayInputStream(this.pdfData2),this.uri1, DocumentStore.DocumentFormat.PDF); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue("should return hashcode of old text",this.pdfTxt1.hashCode() == returned || this.pdfTxt2.hashCode() == returned); assertEquals("failed to return correct pdf text", this.pdfTxt2,Utils.pdfDataToText(store.getDocumentAsPdf(this.uri1))); } @Test public void testPutNewVersionOfDocumentTxt(){ //put the first version DocumentStore store = new DocumentStoreImpl(); int returned = store.putDocument(new ByteArrayInputStream(this.txt1.getBytes()),this.uri1, DocumentStore.DocumentFormat.TXT); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue(returned == 0 || returned == this.txt1.hashCode()); assertEquals("failed to return correct text",this.txt1,store.getDocumentAsTxt(this.uri1)); //put the second version, testing both return value of put and see if it gets the correct text returned = store.putDocument(new ByteArrayInputStream(this.txt2.getBytes()),this.uri1, DocumentStore.DocumentFormat.TXT); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue("should return hashcode of old text",this.txt1.hashCode() == returned || this.txt2.hashCode() == returned); assertEquals("failed to return correct text",this.txt2,store.getDocumentAsTxt(this.uri1)); } @Test public void testGetTxtDocAsPdf(){ DocumentStore store = new DocumentStoreImpl(); int returned = store.putDocument(new ByteArrayInputStream(this.txt1.getBytes()),this.uri1, DocumentStore.DocumentFormat.TXT); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue(returned == 0 || returned == this.txt1.hashCode()); assertEquals("failed to return correct pdf text",this.txt1,Utils.pdfDataToText(store.getDocumentAsPdf(this.uri1))); } @Test public void testGetTxtDocAsTxt(){ DocumentStore store = new DocumentStoreImpl(); int returned = store.putDocument(new ByteArrayInputStream(this.txt1.getBytes()),this.uri1, DocumentStore.DocumentFormat.TXT); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue(returned == 0 || returned == this.txt1.hashCode()); assertEquals("failed to return correct text",this.txt1,store.getDocumentAsTxt(this.uri1)); } @Test public void testGetPdfDocAsPdf(){ DocumentStore store = new DocumentStoreImpl(); int returned = store.putDocument(new ByteArrayInputStream(this.pdfData1),this.uri1, DocumentStore.DocumentFormat.PDF); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue(returned == 0 || returned == this.pdfTxt1.hashCode()); assertEquals("failed to return correct pdf text",this.pdfTxt1,Utils.pdfDataToText(store.getDocumentAsPdf(this.uri1))); } @Test public void testGetPdfDocAsTxt(){ DocumentStore store = new DocumentStoreImpl(); int returned = store.putDocument(new ByteArrayInputStream(this.pdfData1),this.uri1, DocumentStore.DocumentFormat.PDF); //TODO allowing for student following old API comment. To be changed for stage 2 to insist on following new comment. assertTrue(returned == 0 || returned == this.pdfTxt1.hashCode()); assertEquals("failed to return correct text",this.pdfTxt1,store.getDocumentAsTxt(this.uri1)); } @Test public void testDeleteDoc(){ DocumentStore store = new DocumentStoreImpl(); store.putDocument(new ByteArrayInputStream(this.pdfData1),this.uri1, DocumentStore.DocumentFormat.PDF); store.deleteDocument(this.uri1); assertEquals("calling get on URI from which doc was deleted should've returned null", null, store.getDocumentAsPdf(this.uri1)); } @Test public void testDeleteDocReturnValue(){ DocumentStore store = new DocumentStoreImpl(); store.putDocument(new ByteArrayInputStream(this.pdfData1),this.uri1, DocumentStore.DocumentFormat.PDF); //should return true when deleting a document assertEquals("failed to return true when deleting a document",true,store.deleteDocument(this.uri1)); //should return false if I try to delete the same doc again assertEquals("failed to return false when trying to delete that which was already deleted",false,store.deleteDocument(this.uri1)); //should return false if I try to delete something that was never there to begin with assertEquals("failed to return false when trying to delete that which was never there to begin with",false,store.deleteDocument(this.uri2)); } }
true
56a2bdf48f444924071e5c210347ad0e32401d4e
Java
rushingpig/raistlic-lib-commons-core
/src/test/java/org/raistlic/common/configuration/ConfigurationTest.java
UTF-8
4,331
2.671875
3
[ "Apache-2.0" ]
permissive
package org.raistlic.common.configuration; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.raistlic.common.precondition.InvalidParameterException; import java.util.Arrays; import java.util.Collection; import static org.fest.assertions.Assertions.assertThat; /** * Unit test for {@link Configuration} interface contract. * * @author Lei.C (2015-05-01) */ @RunWith(Parameterized.class) public class ConfigurationTest { @Parameterized.Parameters public static Collection<Object[]> getTestParameters() { return Arrays.<Object[]>asList( new Object[] { new DefaultMutableConfiguration() } ); } private Configuration configuration; public ConfigurationTest(Configuration.Builder builder) { populateConfigurationBuilderWithFixtureValues(builder); configuration = builder.build(); } /** * Getting String value with configured key should return the configured value. */ @Test public void testGetString() { assertThat(configuration.getString("string.value")).isEqualTo(FIXTURE_STRING); } /** * Getting String with null key should cause a {@link org.raistlic.common.precondition.InvalidParameterException} . */ @Test(expected = InvalidParameterException.class) public void testGetStringWithNullKey() { configuration.getString(null); } /** * Getting String with not configured key should return null. */ @Test public void testGetStringNotConfigured() { String actual = configuration.getString("not.configured"); assertThat(actual).isNull(); } /** * Getting String with not configured key and a default value should return the default value. */ @Test public void testGetStringNotConfiguredWithDefaultValue() { String expected = "expectedDefaultValue"; String actual = configuration.getString("not.configured", expected); assertThat(actual).isEqualTo(expected); } /** * Getting boolean with correct key should return the configured value. */ @Test public void testGetBoolean() { assertThat(configuration.getBoolean("boolean.value", false)).isTrue(); } /** * Getting boolean value with null key should cause {@link InvalidParameterException} . */ @Test(expected = InvalidParameterException.class) public void testGetBooleanWithNullKey() { configuration.getBoolean(null, true); } /** * Getting boolean with not configured key should return the provided default value. */ @Test public void testGetBooleanNotConfigured() { boolean expected = false; boolean actual = configuration.getBoolean("not.configured", expected); assertThat(actual).isEqualTo(expected); } /** * Getting byte value with the correct key should return the configured value. */ @Test public void testGetByte() { assertThat(configuration.getByte("byte.value", (byte) 1)).isEqualTo(FIXTURE_BYTE); } /** * Getting byte with not configured key should return the provided default value. */ @Test public void testGetByteNotConfigured() { byte expected = (byte) 44; byte actual = configuration.getByte("not.configured", expected); assertThat(actual).isEqualTo(expected); } private static void populateConfigurationBuilderWithFixtureValues(Configuration.Builder builder) { builder.setByte("byte.value", FIXTURE_BYTE); builder.setChar("char.value", FIXTURE_CHAR); builder.setInt("int.value", FIXTURE_INT); builder.setShort("short.value", FIXTURE_SHORT); builder.setLong("long.value", FIXTURE_LONG); builder.setFloat("float.value", FIXTURE_FLOAT); builder.setDouble("double.value", FIXTURE_DOUBLE); builder.setBoolean("boolean.value", FIXTURE_BOOLEAN); builder.setString("string.value", FIXTURE_STRING); } private static final byte FIXTURE_BYTE = (byte) 12; private static final char FIXTURE_CHAR = 'c'; private static final short FIXTURE_SHORT = -325; private static final int FIXTURE_INT = 12345; private static final long FIXTURE_LONG = -234523458923234L; private static final float FIXTURE_FLOAT = 123.0F; private static final double FIXTURE_DOUBLE = 234.1; private static final boolean FIXTURE_BOOLEAN = true; private static final String FIXTURE_STRING = "8c41ad9c-efb7-11e4-90ec-1681e6b88ec1"; }
true
4c007cd0bc0380b0852ad0b6d8d44837a3269356
Java
zhao-qc/zstack
/header/src/main/java/org/zstack/header/volume/APIChangeVolumeStateMsg.java
UTF-8
2,305
2.140625
2
[ "Apache-2.0" ]
permissive
package org.zstack.header.volume; import org.springframework.http.HttpMethod; import org.zstack.header.identity.Action; import org.zstack.header.message.APIEvent; import org.zstack.header.message.APIMessage; import org.zstack.header.message.APIParam; import org.zstack.header.rest.RestRequest; /** * @api change data volume state * @cli * @httpMsg { * "org.zstack.header.volume.APIChangeVolumeStateMsg": { * "uuid": "f035366497994ef6bda20a45c4b3ee2e", * "stateEvent": "disable", * "session": { * "uuid": "832cff424d5647c6915ce258995720e1" * } * } * } * @msg { * "org.zstack.header.volume.APIChangeVolumeStateMsg": { * "uuid": "f035366497994ef6bda20a45c4b3ee2e", * "stateEvent": "disable", * "session": { * "uuid": "832cff424d5647c6915ce258995720e1" * }, * "timeout": 1800000, * "id": "49dd8cf1782a4ffd9e46d8bac5cee0a9", * "serviceId": "api.portal" * } * } * @result See :ref:`APICreateDataVolumeEvent` * @since 0.1.0 */ @Action(category = VolumeConstant.ACTION_CATEGORY) @RestRequest( path = "/volumes/{uuid}/actions", isAction = true, method = HttpMethod.PUT, responseClass = APIChangeVolumeStateEvent.class ) public class APIChangeVolumeStateMsg extends APIMessage implements VolumeMessage { /** * @desc data volume uuid */ @APIParam(resourceType = VolumeVO.class, checkAccount = true, operationTarget = true) private String uuid; /** * @desc - enable: enable data volume * - disable: disable data volume * <p> * for details of volume state, see state of :ref:`VolumeInventory` */ @APIParam(validValues = {"enable", "disable"}) private String stateEvent; @Override public String getVolumeUuid() { return getUuid(); } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getStateEvent() { return stateEvent; } public void setStateEvent(String stateEvent) { this.stateEvent = stateEvent; } public static APIChangeVolumeStateMsg __example__() { APIChangeVolumeStateMsg msg = new APIChangeVolumeStateMsg(); msg.setUuid(uuid()); msg.setStateEvent(VolumeStateEvent.enable.toString()); return msg; } }
true
651c4b0e78910bd8153a4269c506c7f524ff1e86
Java
bojanv55/hi-perf-java-persistence
/src/main/java/me/vukas/hiperfjavapersistence/repository/jpa/identifier/numerical/IdentityGeneratorRepository.java
UTF-8
383
1.578125
2
[]
no_license
package me.vukas.hiperfjavapersistence.repository.jpa.identifier.numerical; import me.vukas.hiperfjavapersistence.entity.identifier.numerical.IdentityGenerator; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface IdentityGeneratorRepository extends JpaRepository<IdentityGenerator, Long> { }
true
7aa717d097f4f1b0f70fc84ec42d50f6111c83ca
Java
wangbo15/rife
/rife_v1_remaining/src/framework/com/uwyn/rife/cmf/dam/contentstores/DatabaseContentStore.java
UTF-8
5,714
2.0625
2
[]
no_license
/* * Copyright 2001-2008 Geert Bevin <gbevin[remove] at uwyn dot com> * Licensed under the Apache License, Version 2.0 (the "License") * $Id: DatabaseContentStore.java 3918 2008-04-14 17:35:35Z gbevin $ */ package com.uwyn.rife.cmf.dam.contentstores; import com.uwyn.rife.database.*; import com.uwyn.rife.cmf.MimeType; import com.uwyn.rife.cmf.dam.ContentStore; import com.uwyn.rife.cmf.dam.contentstores.exceptions.DeleteContentDataErrorException; import com.uwyn.rife.cmf.dam.contentstores.exceptions.HasContentDataErrorException; import com.uwyn.rife.cmf.dam.contentstores.exceptions.InstallContentStoreErrorException; import com.uwyn.rife.cmf.dam.contentstores.exceptions.RemoveContentStoreErrorException; import com.uwyn.rife.cmf.dam.contentstores.exceptions.RetrieveSizeErrorException; import com.uwyn.rife.cmf.dam.exceptions.ContentManagerException; import com.uwyn.rife.database.exceptions.DatabaseException; import com.uwyn.rife.database.queries.CreateTable; import com.uwyn.rife.database.queries.Delete; import com.uwyn.rife.database.queries.DropTable; import com.uwyn.rife.database.queries.Select; import com.uwyn.rife.engine.ElementSupport; import com.uwyn.rife.tools.ExceptionUtils; import com.uwyn.rife.tools.exceptions.InnerClassException; import java.io.OutputStream; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.logging.Logger; import javax.servlet.http.HttpServletResponse; public abstract class DatabaseContentStore extends DbQueryManager implements ContentStore { private ArrayList<MimeType> mMimeTypes = new ArrayList<MimeType>(); public DatabaseContentStore(Datasource datasource) { super(datasource); } protected void addMimeType(MimeType mimeType) { mMimeTypes.add(mimeType); } public Collection<MimeType> getSupportedMimeTypes() { return mMimeTypes; } protected boolean _install(CreateTable createTableContentStore) throws ContentManagerException { assert createTableContentStore != null; try { executeUpdate(createTableContentStore); } catch (DatabaseException e) { throw new InstallContentStoreErrorException(e); } return true; } protected boolean _remove(DropTable dropTableContentStore) throws ContentManagerException { assert dropTableContentStore != null; try { executeUpdate(dropTableContentStore); } catch (DatabaseException e) { throw new RemoveContentStoreErrorException(e); } return true; } protected boolean _deleteContentData(final Delete deleteContentData, final int id) throws ContentManagerException { if (id < 0) throw new IllegalArgumentException("id must be positive"); assert deleteContentData != null; Boolean result = null; try { result = inTransaction(new DbTransactionUser() { public Boolean useTransaction() throws InnerClassException { return 0 != executeUpdate(deleteContentData, new DbPreparedStatementHandler() { public void setParameters(DbPreparedStatement statement) { statement .setInt("contentId", id); } }); } }); } catch (DatabaseException e) { throw new DeleteContentDataErrorException(id, e); } return result != null && result.booleanValue(); } protected int _getSize(Select retrieveSize, final int id) throws ContentManagerException { if (id < 0) throw new IllegalArgumentException("id must be positive"); assert retrieveSize != null; try { return executeGetFirstInt(retrieveSize, new DbPreparedStatementHandler() { public void setParameters(DbPreparedStatement statement) { statement .setInt("contentId", id); } }); } catch (DatabaseException e) { throw new RetrieveSizeErrorException(id, e); } } protected boolean _hasContentData(Select hasContentData, final int id) throws ContentManagerException { if (id < 0) throw new IllegalArgumentException("id must be positive"); assert hasContentData != null; try { return executeHasResultRows(hasContentData, new DbPreparedStatementHandler() { public void setParameters(DbPreparedStatement statement) { statement .setInt("contentId", id); } }); } catch (DatabaseException e) { throw new HasContentDataErrorException(id, e); } } protected String getContentSizeColumnName() { return "size"; } protected void _serveContentData(Select retrieveContent, final ElementSupport element, final int id) throws ContentManagerException { if (null == element) throw new IllegalArgumentException("element can't be null"); if (id < 0) { element.defer(); return; } assert retrieveContent != null; try { if (!executeFetchFirst(retrieveContent, new DbRowProcessor() { public boolean processRow(ResultSet resultSet) throws SQLException { // set the content length header element.setContentLength(resultSet.getInt(getContentSizeColumnName())); // output the content OutputStream os = element.getOutputStream(); outputContentColumn(resultSet, os); return true; } }, new DbPreparedStatementHandler() { public void setParameters(DbPreparedStatement statement) { statement .setInt("contentId", id); } })) { element.defer(); return; } } catch (DatabaseException e) { Logger.getLogger("com.uwyn.rife.cmf").severe(ExceptionUtils.getExceptionStackTrace(e)); element.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } protected abstract void outputContentColumn(ResultSet resultSet, OutputStream os) throws SQLException; }
true
7891a0656d6b169e0e874fcbd925c20a4736c16e
Java
erja/funpro
/v4/02/Strategy/StrategyIF.java
UTF-8
133
2.375
2
[]
no_license
//package strategy; /** * * @author Simo */ @FunctionalInterface public interface StrategyIF{ String apply(String s); }
true
3b24718b8498071b3a94bb443aa1f071439ff999
Java
AndryMaxy/TacoTest
/src/main/java/by/akulich/tacocloud/repository/IngredientRepository.java
UTF-8
234
1.617188
2
[]
no_license
package by.akulich.tacocloud.repository; import by.akulich.tacocloud.domain.Ingredient; import org.springframework.data.repository.CrudRepository; public interface IngredientRepository extends CrudRepository<Ingredient, String> { }
true
e16f3f2ce9178a87ba550d514d9413b8ba86c598
Java
joker-xjh/crawlers
/crawler/src/main/java/demo49/aop/Interceptor.java
UTF-8
166
2
2
[]
no_license
package demo49.aop; import java.lang.reflect.Method; public interface Interceptor { Object interceptor(Object target, Method method, Object[] args); }
true
3f6d5f374288010d085034c5f87afb20529881c9
Java
foretjerome/ARE
/fr/pe/d12dal/dictionnaire/EtatAdministratifDossierInstructionEnumeration.java
UTF-8
4,829
2.1875
2
[]
no_license
package fr.pe.d12dal.dictionnaire; public final class EtatAdministratifDossierInstructionEnumeration { public static final EtatAdministratifDossierInstructionEnumeration E_16 = new EtatAdministratifDossierInstructionEnumeration("AUTRE ATTENTE", "AUTRE ATTENTE", "16"); public static final EtatAdministratifDossierInstructionEnumeration E_10 = new EtatAdministratifDossierInstructionEnumeration("PASSAGE EN IPR", "PASSAGE EN IPR", "10"); public static final EtatAdministratifDossierInstructionEnumeration E_03 = new EtatAdministratifDossierInstructionEnumeration("ATTENTE DE LA DIRECCTE", "ATTENTE DE LA DIRECCTE", "03"); public static final EtatAdministratifDossierInstructionEnumeration E_01 = new EtatAdministratifDossierInstructionEnumeration("ATTENTE DE DRC", "ATTENTE DE DRC", "01"); public static final EtatAdministratifDossierInstructionEnumeration E_02 = new EtatAdministratifDossierInstructionEnumeration("ATTENTE D’ENTRETIEN", "ATTENTE D'ENTRETIEN", "02"); public static final EtatAdministratifDossierInstructionEnumeration E_13 = new EtatAdministratifDossierInstructionEnumeration("ATTENTE D’EXAMEN", "ATTENTE D'EXAMEN", "13"); public static final EtatAdministratifDossierInstructionEnumeration E_11 = new EtatAdministratifDossierInstructionEnumeration("ATTENTE DE PLANIFICATION", "ATTENTE DE PLANIFICATION", "11"); public static final EtatAdministratifDossierInstructionEnumeration E_15 = new EtatAdministratifDossierInstructionEnumeration("ATTENTE DE PAIEMENT", "ATTENTE DE PAIEMENT", "15"); public static final EtatAdministratifDossierInstructionEnumeration E_00 = new EtatAdministratifDossierInstructionEnumeration("ATTENTE DE REPONSE", "ATTENTE DE REPONSE", "00"); public static final EtatAdministratifDossierInstructionEnumeration E_12 = new EtatAdministratifDossierInstructionEnumeration("ATTENTE DE REEXAMEN", "ATTENTE DE REEXAMEN", "12"); public static final EtatAdministratifDossierInstructionEnumeration E_20 = new EtatAdministratifDossierInstructionEnumeration("DECISIONNE", "DECISIONNE", "20"); public static final EtatAdministratifDossierInstructionEnumeration E_05 = new EtatAdministratifDossierInstructionEnumeration("ENVOI D’INFORMATION", "ENVOI D'INFORMATION", "05"); public static final EtatAdministratifDossierInstructionEnumeration E_99 = new EtatAdministratifDossierInstructionEnumeration("DOSSIER FS CLOTURE", "DOSSIER FS CLOTURE", "99"); public static final EtatAdministratifDossierInstructionEnumeration E_21 = new EtatAdministratifDossierInstructionEnumeration("TRAITE", "TRAITE", "21"); static final EtatAdministratifDossierInstructionEnumeration[] LISTE_ENUM = { E_16, E_10, E_03, E_01, E_02, E_13, E_11, E_15, E_00, E_12, E_20, E_05, E_99, E_21 }; final String m_libelleCourt; final String m_libelleLong; final String m_valeur; private EtatAdministratifDossierInstructionEnumeration(String pLibelleCourt, String pLibelleLong, String pValeur) { m_libelleCourt = pLibelleCourt; m_libelleLong = pLibelleLong; m_valeur = pValeur; } private EtatAdministratifDossierInstructionEnumeration(String pLibelleCourt, String pValeur) { m_libelleCourt = pLibelleCourt; m_libelleLong = null; m_valeur = pValeur; } public String getLibelleCourt() { return m_libelleCourt; } public String getLibelleLong() { return m_libelleLong; } public String getValeur() { return m_valeur; } public static EtatAdministratifDossierInstructionEnumeration getPourLibelleCourt(String pLibelleCourt) { EtatAdministratifDossierInstructionEnumeration retour = null; for (int i = 0; (retour == null) && (i < LISTE_ENUM.length); i++) { if (LISTE_ENUM[i].getLibelleCourt().equals(pLibelleCourt)) { retour = LISTE_ENUM[i]; } } return retour; } public static EtatAdministratifDossierInstructionEnumeration getPourLibelleLong(String pLibelleLong) { EtatAdministratifDossierInstructionEnumeration retour = null; for (int i = 0; (retour == null) && (i < LISTE_ENUM.length); i++) { if (LISTE_ENUM[i].getLibelleLong().equals(pLibelleLong)) { retour = LISTE_ENUM[i]; } } return retour; } public static EtatAdministratifDossierInstructionEnumeration getPourValeur(String pValeur) { EtatAdministratifDossierInstructionEnumeration retour = null; for (int i = 0; (retour == null) && (i < LISTE_ENUM.length); i++) { if (LISTE_ENUM[i].getValeur().equals(pValeur)) { retour = LISTE_ENUM[i]; } } return retour; } public static EtatAdministratifDossierInstructionEnumeration[] getAll() { return LISTE_ENUM; } } /* Location: * Qualified Name: EtatAdministratifDossierInstructionEnumeration * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
8ddd070964aeaa0e0d50e53243359fe57281730d
Java
KateAres/studentsmanager
/main/java/ua/com/foxminded/studentsmanager/domain/entities/Student.java
UTF-8
632
2.578125
3
[]
no_license
package ua.com.foxminded.studentsmanager.domain.entities; public class Student { private int studentId; private Integer groupId; private String firstName; private String lastName; public Student(int studentId, Integer groupId, String firstName, String lastName) { this.studentId = studentId; this.groupId = groupId; this.firstName = firstName; this.lastName = lastName; } public Integer getGroupId() { return groupId; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }
true
c18afb6d29783a1aa86a7e2ead0d698f221a311e
Java
jupazpinheiro/AT_MediCare
/src/main/java/infnet/julia/fdj/medicare/model/exceptions/ClinicoSemDiagnosticoException.java
UTF-8
199
2.15625
2
[]
no_license
package infnet.julia.fdj.medicare.model.exceptions; public class ClinicoSemDiagnosticoException extends Exception { public ClinicoSemDiagnosticoException(String mensagem) { super(mensagem); } }
true
6f08a5f61ea37ca1f23fd337d617d5b48b5f0275
Java
ganeshank/SableBadiya
/src/main/java/com/sb/integration/dao/CartRepository.java
UTF-8
2,475
2.078125
2
[]
no_license
package com.sb.integration.dao; import java.sql.Connection; import java.util.List; import com.sb.integration.vo.CartDetails; import com.sb.integration.vo.CartItem; import com.sb.integration.vo.DeliveryOption; import com.sb.integration.vo.DeliveryTypeVo; public interface CartRepository { public Long createEmptyCart(Connection con, Long userId) throws Exception; public Boolean isCartItemAlreadyExist(Connection con, Long userId, Long goodsId) throws Exception; public List<CartItem> getActiveCartItemsForUser(Connection con, Long userId) throws Exception; public CartDetails getActiveCartForUser(Connection con, Long userId) throws Exception; public void updateExistingCartItem(Connection con, CartDetails cartDetails, CartItem cartItem, Boolean isCartUpdateRequired) throws Exception; public Boolean updateCart(Connection con, CartDetails cartDetails) throws Exception; public void addCartItem(Connection con, CartDetails cartDetails, CartItem cartItem, Boolean isCartUpdateNeeded) throws Exception; public CartItem getCartItemForId(Connection con, Long cartItemId, Boolean isRequiredGoodsQuantity) throws Exception; public CartDetails getActiveCartForId(Connection con, Long cartId) throws Exception; public CartDetails deleteCartItemForId(Connection con, Long cartItemId) throws Exception; public void emptyCart(Connection con, Long cartId) throws Exception; public Boolean isEmailValid(Connection con, String email) throws Exception; public void resetPassword(Connection con, String emailId, String resetPass) throws Exception; public List<DeliveryTypeVo> getAllDeliveryTpyes(Connection con) throws Exception; public void placeOrder(Connection con, CartDetails cartDetails) throws Exception; public Long persistCart(Connection con, CartDetails cartDetails) throws Exception; public CartDetails getOrderForId(Connection con, Long cartId)throws Exception; public List<CartItem> getActiveCartItemsForCartId(Connection con, Long cartId, Boolean isSellerInfoRequired) throws Exception; public void inActiveCartItemById(Connection con, Long cartItemId)throws Exception; public List<DeliveryOption> getDeliveryOption(Connection con, String deliveryIds)throws Exception; public Boolean isCartEmpty(Connection con, Long userId) throws Exception; public void updateShippingAddress(Connection con, Long addressId, Long cartId) throws Exception; public void inActiveOrder(Connection con, Long cartId) throws Exception; }
true
d75b81c789dbffc094eb0eba6fa3845945e22d74
Java
eh2arch/PingPong-Speech-Recognizer
/src/scoreFrame.java
UTF-8
6,472
2.453125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author archit */ public class scoreFrame extends javax.swing.JFrame { /** * Creates new form scoreFrame */ public scoreFrame() { initComponents(); } public int getAchooScore() { return Integer.parseInt(achooScore.getText()); } public int getLoserScore() { return Integer.parseInt(loserScore.getText()); } public void setAchooScore(int score) { achooScore.setText(Integer.toString(score)); } public void setLoserScore(int score) { loserScore.setText(Integer.toString(score)); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { achooLabel = new javax.swing.JLabel(); loserLabel = new javax.swing.JLabel(); achooScore = new javax.swing.JLabel(); loserScore = new javax.swing.JLabel(); colonLabel = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setAutoRequestFocus(false); setName("scoreFrame"); // NOI18N setUndecorated(true); setResizable(false); achooLabel.setFont(new java.awt.Font("Ubuntu", 0, 48)); // NOI18N achooLabel.setText("PLayer1"); loserLabel.setFont(new java.awt.Font("Ubuntu", 0, 48)); // NOI18N loserLabel.setText("PLayer2"); achooScore.setFont(new java.awt.Font("Ubuntu", 0, 48)); // NOI18N achooScore.setText("0"); loserScore.setFont(new java.awt.Font("Ubuntu", 0, 48)); // NOI18N loserScore.setText("0"); colonLabel.setFont(new java.awt.Font("Ubuntu", 0, 48)); // NOI18N colonLabel.setText(":"); jLabel1.setText("Press 'R' to restart the game :)"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(135, 135, 135) .addComponent(achooScore) .addGap(88, 88, 88) .addComponent(colonLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 94, Short.MAX_VALUE) .addComponent(loserScore) .addGap(155, 155, 155)) .addGroup(layout.createSequentialGroup() .addGap(167, 167, 167) .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(64, 64, 64) .addComponent(achooLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(loserLabel) .addGap(107, 107, 107)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(achooLabel) .addComponent(loserLabel)) .addGap(74, 74, 74) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(achooScore) .addComponent(loserScore) .addComponent(colonLabel)) .addGap(35, 35, 35) .addComponent(jLabel1) .addContainerGap(69, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(scoreFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(scoreFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(scoreFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(scoreFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new scoreFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel achooLabel; private javax.swing.JLabel achooScore; private javax.swing.JLabel colonLabel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel loserLabel; private javax.swing.JLabel loserScore; // End of variables declaration//GEN-END:variables }
true
0d640a936a30ff35b60289776dbe68060c206a54
Java
nicolas2lee/nomenclature
/batch/src/main/java/com/bnpparibas/dsibddf/nomenclature/batch/config/csv/JobConfiguration.java
UTF-8
1,603
2.03125
2
[]
no_license
package com.bnpparibas.dsibddf.nomenclature.batch.config.csv; import com.bnpparibas.dsibddf.nomenclature.batch.config.csv.data.DataStepConfig; import com.bnpparibas.dsibddf.nomenclature.batch.config.csv.table.TableStepConfig; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({TableStepConfig.class, DataStepConfig.class}) public class JobConfiguration { private final JobBuilderFactory jobBuilderFactory; //@Resource(name = "createTableStep") @Autowired @Qualifier(value = "createTableStep") private Step createTableStep; @Autowired @Qualifier(value = "insertDataStep") //@Resource(name = "insertDataStep") private Step insertDataStep; JobConfiguration(JobBuilderFactory jobBuilderFactory) { this.jobBuilderFactory = jobBuilderFactory; } @Bean public Job importDataFromCsvJob() { return jobBuilderFactory.get("importDataFromCsvJob") .incrementer(new RunIdIncrementer()) .flow(createTableStep) .next(insertDataStep) .end() .build(); } }
true
bce7ca545c641715a6cbce678f054a7f5a708584
Java
ToanNguyenSVR/API_CRUD_User
/src/main/java/com/example/resfulapi/api/APIController.java
UTF-8
2,009
2.40625
2
[]
no_license
package com.example.resfulapi.api; import com.example.resfulapi.entity.User; import com.example.resfulapi.model.DTO.UserDTO; import com.example.resfulapi.reponsitory.UserReponsitory; import com.example.resfulapi.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class APIController { @Autowired UserService userService ; @Autowired UserReponsitory userReponsitory ; @GetMapping("/users") public ResponseEntity<?> getAllUser(){ List<UserDTO> users = userService.findAll(); // for(int i = 0 ; i< 100 ; i ++){ // User user = new User(); // user.setName("Name" + i ); // user.setPassword("Password" + i ); // user.setAddress("Address" + i ); // user.setEmail("Email" + i ); // user.setPhone("phone" + i ); // userReponsitory.save(user); // } return ResponseEntity.ok(users); } @GetMapping("/users/{id}") public ResponseEntity<?> findById(@PathVariable(name = "id") Long userID){ UserDTO user = userService.findById(userID); return ResponseEntity.ok(user); } // tạo user @PostMapping("/users") public ResponseEntity<?> create(@RequestBody User user){ return ResponseEntity.ok(userService.save(user)); } // update user @PutMapping("/users/{id}") public ResponseEntity<?> update(@RequestBody User user , @PathVariable (name = "id") Long id){ User u = userReponsitory.findById(id).get(); if(u != null ){ user.setId(id); userService.save(user); } return ResponseEntity.ok(u); } // delete user @DeleteMapping("/users/{id}") public ResponseEntity<?> deletw(@PathVariable (name = "id") Long id){ return ResponseEntity.ok(userService.delete(id)); } }
true
5f66b42de1e8bd8ec6dfb399627e61cc535c1bb3
Java
michaelruocco/simple-dynamo
/src/test/java/uk/co/mruoc/dynamo/test/FakeTableExceptionTest.java
UTF-8
394
2.046875
2
[]
no_license
package uk.co.mruoc.dynamo.test; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class FakeTableExceptionTest { @Test public void shouldReturnMessage() { String message = "error-message"; FakeTableException exception = new FakeTableException(message); assertThat(exception.getMessage()).isEqualTo(message); } }
true
661eec72404425a85c41bf3116d2b004ef54d33f
Java
ncwade/CS106
/CS106-Chapter9-Homework/src/com/thewadegeek/Student.java
UTF-8
483
3.71875
4
[ "MIT" ]
permissive
package com.thewadegeek; /* * Question 5: "this" and "super" both reference members of the class. "this" is used to reference variables or method defined locally, "super" is used to reference inherited methods. * Question 6: No to the private members, yes for the method. */ public class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public void setAge(int age) { this.age = age; } }
true
bfded6fe64da418e7201425a921241b51d0336ec
Java
qoo7972365/timmy
/OSWE/oswe/openCRX/rtjar/rt.jar.src/com/sun/org/apache/xerces/internal/dom/DeferredNode.java
UTF-8
392
1.632813
2
[]
no_license
package com.sun.org.apache.xerces.internal.dom; import org.w3c.dom.Node; public interface DeferredNode extends Node { public static final short TYPE_NODE = 20; int getNodeIndex(); } /* Location: /Users/timmy/timmy/OSWE/oswe/openCRX/rt.jar!/com/sun/org/apache/xerces/internal/dom/DeferredNode.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
true
694de805a233a5fcb8a93edd7ac1bb9028291541
Java
bellmit/poprice
/love-poprice/src/main/java/poprice/wechat/web/mvc/account/RoleController.java
UTF-8
7,337
2.015625
2
[]
no_license
package poprice.wechat.web.mvc.account; import com.google.common.collect.Lists; import poprice.wechat.domain.Authority; import poprice.wechat.domain.Role; import poprice.wechat.repository.RoleRepository; import poprice.wechat.security.SecurityUtils; import poprice.wechat.service.AuthorityService; import poprice.wechat.service.RoleService; import poprice.wechat.util.BeanUtils; import poprice.wechat.util.Servlets; import poprice.wechat.util.persistence.SearchFilter; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.List; import java.util.Map; /** * 角色的CRUD,字典表, 无分页和搜索,可以页面排序。 */ @Controller @RequestMapping("/account/role") public class RoleController { private final Logger log = LoggerFactory.getLogger(RoleController.class); @Inject private RoleRepository roleRepository; @Inject private RoleService roleService; @Inject private AuthorityService authorityService; @RequestMapping(value = "/list") public String list(@RequestParam(value = "sortProp", defaultValue = "id") String sortProp, @RequestParam(value = "sortOrder", defaultValue = "asc") String sortOrder, final Model model, final HttpServletRequest request) { Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_"); Specification<Role> spec = SearchFilter.buildSpecificationByParams(searchParams, Role.class); Sort sort = SearchFilter.buildSort(sortProp, sortOrder); List<Role> list = roleRepository.findAll(spec, sort); model.addAttribute("list", list); return "account/role/list"; } @RequestMapping(value = "/create") public String create(final Model model) { Role entity = new Role(); model.addAttribute("entity", entity); List<Authority> authList = authorityService.getList(); model.addAttribute("authList", authList); return "account/role/create"; } @RequestMapping(value = "/save", method = RequestMethod.POST) public String save(@Valid final Role entity, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) { if (bindingResult.hasErrors()) { model.addAttribute("org.springframework.validation.BindingResult.entity", bindingResult); model.addAttribute("entity", entity); List<Authority> authList = authorityService.getList(); model.addAttribute("authList", authList); return "account/role/create"; } entity.setId(null); entity.setCreatedBy(SecurityUtils.getCurrentLogin()); entity.setLastModifiedBy(SecurityUtils.getCurrentLogin()); roleService.save(entity); redirectAttributes.addFlashAttribute("flash.message", "新增角色'" + entity.getName() + "'成功"); log.info("{}新增角色{}成功, ID:{}", SecurityUtils.getCurrentLogin(), entity.getName(), entity.getId()); return "redirect:/account/role/show/" + entity.getId(); } @RequestMapping(value = "/show/{id}") public String show(@PathVariable("id") final Long id, final Model model, final RedirectAttributes redirectAttributes) { Role entity = roleRepository.findOne(id); if (entity == null) { redirectAttributes.addFlashAttribute("flash.error", "没有找到这条数据,请重试"); return "redirect:/account/role/list"; } List<String> descList = Lists.newArrayList(); for (String authKey : entity.getAuthorities()) { descList.add(authorityService.getByAuthority(authKey).getName()); } model.addAttribute("entity", entity); model.addAttribute("descList", descList); return "account/role/show"; } @RequestMapping(value = "/edit/{id}") public String edit(@PathVariable("id") final Long id, final Model model, final RedirectAttributes redirectAttributes) { Role entity = roleRepository.findOne(id); if (entity == null) { redirectAttributes.addFlashAttribute("flash.error", "没有找到这条数据,请重试"); return "redirect:/account/role/list"; } model.addAttribute("entity", entity); List<Authority> authList = authorityService.getList(); model.addAttribute("authList", authList); return "account/role/edit"; } @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(@Valid final Role entity, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) { Role exist = roleRepository.findOne(entity.getId()); if (exist == null) { redirectAttributes.addFlashAttribute("flash.error", "没有找到这条数据,请重试"); return "redirect:/account/role/list"; } if (bindingResult.hasErrors()) { model.addAttribute("org.springframework.validation.BindingResult.entity", bindingResult); model.addAttribute("entity", entity); List<Authority> authList = authorityService.getList(); model.addAttribute("authList", authList); return "account/role/edit"; } BeanUtils.copyPropertiesByDefault(entity, exist); roleService.save(exist); redirectAttributes.addFlashAttribute("flash.message", "更新角色'" + exist.getName() + "'成功"); log.info("{}更新角色{}成功, ID:{}", SecurityUtils.getCurrentLogin(), exist.getName(), exist.getId()); return "redirect:/account/role/list"; } @RequestMapping(value = "/delete/{id}") public String delete(@PathVariable("id") final Long id, final RedirectAttributes redirectAttributes, final HttpServletRequest request) { Role entity = roleRepository.findOne(id); try { roleService.delete(id); } catch (Exception e) { log.error(SecurityUtils.getCurrentLogin() + "删除角色失败id:" + id, e); redirectAttributes.addFlashAttribute("flash.error", "删除角色'" + entity.getName() + "'失败"); return "redirect:" + request.getHeader("referer"); } redirectAttributes.addFlashAttribute("flash.message", "删除角色'" + entity.getName() + "'成功"); log.info("{}删除角色{}成功, ID:{}", SecurityUtils.getCurrentLogin(), entity.getName(), entity.getId()); return "redirect:/account/role/list"; } }
true
b77a978cc8b226fa2bdcbcf0378cdecedc572a7b
Java
FAST-LAHORE/project-phase-3-cs-a-and-e-facebook
/TextPost.java
UTF-8
702
1.984375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Post.Responce; import java.util.ArrayList; /** * * @author MHA */ public class TextPost extends Post{ public TextPost(String _uid, String _id, String _text) { res=new ArrayList(); id=_id; uId=_uid; text=_text; } @Override public void show() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
true
a2070202048f6d294ae7171c99ba2f81367b021e
Java
ubiratansoares/bira-bachelor-files
/courses/COMPILADORES/[2012] Thiago/Trabalhos/T3/compiler/src/compiler/SemanticError.java
UTF-8
352
2.625
3
[ "Apache-2.0" ]
permissive
package compiler; /** * Mensagem de erro do compilador. * */ public class SemanticError extends CompilationError { /** * Cria uma mensagem de erro do compilador. * * @param t * O token que causou o erro. * * @param msg * A mensagem de erro. */ public SemanticError(Token t, String msg) { super(t, msg); } }
true
c12f5680b57a1c910f2781b40edb26fca744497a
Java
dinakarg/rampup
/bundle/action/src/main/java/com/ndtv/model/ImageBean.java
UTF-8
5,246
2.6875
3
[]
no_license
package com.ndtv.model; import java.io.Serializable; /** * The Class ImageBean. */ public class ImageBean implements Serializable { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The title. */ private String title; /** The title1. */ private String title1; /** The title2. */ private String title2; /** The description. */ private String description; /** The description1. */ private String description1; /** The description2. */ private String description2; /** The link url. */ private String linkURL; /** The link ur l1. */ private String linkURL1; /** The link ur l2. */ private String linkURL2; /** The image. */ private String image; /** The image1. */ private String image1; /** The image2. */ private String image2; /** * Gets the title. * * @return the title */ public final String getTitle() { return title; } /** * Sets the title. * * @param paramTitle * the new title */ public final void setTitle(final String paramTitle) { this.title = paramTitle; } /** * Gets the title1. * * @return the title1 */ public final String getTitle1() { return title1; } /** * Sets the title1. * * @param paramTitle1 * the new title1 */ public final void setTitle1(final String paramTitle1) { this.title1 = paramTitle1; } /** * Gets the title2. * * @return the title2 */ public final String getTitle2() { return title2; } /** * Sets the title2. * * @param paramTitle2 * the new title2 */ public final void setTitle2(final String paramTitle2) { this.title2 = paramTitle2; } /** * Gets the description. * * @return the description */ public final String getDescription() { return description; } /** * Sets the description. * * @param paramDescription * the new description */ public final void setDescription(final String paramDescription) { this.description = paramDescription; } /** * Gets the description1. * * @return the description1 */ public final String getDescription1() { return description1; } /** * Sets the description1. * * @param paramDescription1 * the new description1 */ public final void setDescription1(final String paramDescription1) { this.description1 = paramDescription1; } /** * Gets the description2. * * @return the description2 */ public final String getDescription2() { return description2; } /** * Sets the description2. * * @param paramDescription2 * the new description2 */ public final void setDescription2(final String paramDescription2) { this.description2 = paramDescription2; } /** * Gets the link url. * * @return the link url */ public final String getLinkURL() { return linkURL; } /** * Sets the link url. * * @param link * the new link url */ public final void setLinkURL(final String link) { this.linkURL = link; } /** * Gets the link ur l1. * * @return the link ur l1 */ public final String getLinkURL1() { return linkURL1; } /** * Sets the link ur l1. * * @param link1 * the new link ur l1 */ public final void setLinkURL1(final String link1) { this.linkURL1 = link1; } /** * Gets the link ur l2. * * @return the link ur l2 */ public final String getLinkURL2() { return linkURL2; } /** * Sets the link ur l2. * * @param paramSecond * the new link ur l2 */ public final void setLinkURL2(final String paramSecond) { this.linkURL2 = paramSecond; } /** * Gets the image. * * @return the image */ public final String getImage() { return image; } /** * Sets the image. * * @param paramImage * the new image */ public final void setImage(final String paramImage) { this.image = paramImage; } /** * Gets the image1. * * @return the image1 */ public final String getImage1() { return image1; } /** * Sets the image1. * * @param paramImage1 * the new image1 */ public final void setImage1(final String paramImage1) { this.image1 = paramImage1; } /** * Gets the image2. * * @return the image2 */ public final String getImage2() { return image2; } /** * Sets the image2. * * @param image2URL * the new image2 */ public final void setImage2(final String image2URL) { this.image2 = image2URL; } }
true
aee2a2ab65433c6f54255857d4add3cd7bb54c69
Java
AlexKovalenko96s/Test2
/app/src/main/java/com/example/alexkovalenko/test2/MustSee.java
UTF-8
4,718
2.125
2
[]
no_license
package com.example.alexkovalenko.test2; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.net.Socket; /** * Created by AlexKovalenko on 05.08.2017. */ public class MustSee extends AppCompatActivity { public static String[] names; public TextView tv_user; public ListView lv_mustSee; public static String user; public byte[] imgByte = null; private Socket socket; public Thread thread; private String line = ""; public String name; public String location; public String email; public String number; public String like; public String greenOrNo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mustsee); tv_user = (TextView) findViewById(R.id.tv_user); tv_user.setText(user); lv_mustSee = (ListView) findViewById(R.id.lv_mustSee); ArrayAdapter<String> adapter = new ArrayAdapter<String>(MustSee.this, R.layout.list, R.id.textview, names); lv_mustSee.setAdapter(adapter); lv_mustSee.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final String text = lv_mustSee.getItemAtPosition(position).toString().trim(); thread = new Thread(new Runnable() { @Override public void run() { try { socket = new Socket("192.168.0.103", 9152); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); out.println("mustSeeItem&" + text + "&mustSee&" + user); out.print("END"); line = in.readLine(); name = line.substring(0, line.indexOf("&")); line = line.substring(line.indexOf("&") + 1); location = line.substring(0, line.indexOf("&")); line = line.substring(line.indexOf("&") + 1); number = line.substring(0, line.indexOf("&")); line = line.substring(line.indexOf("&") + 1); email = line.substring(0, line.indexOf("&")); line = line.substring(line.indexOf("&") + 1); like = line.substring(0, line.indexOf("&")); line = line.substring(line.indexOf("&") + 1); greenOrNo = line.substring(0, line.indexOf("&")); line = line.substring(line.indexOf("&") + 1); byte[] imgBytes = line.getBytes("UTF-8"); byte[] valueDecoded= android.util.Base64.decode(imgBytes, android.util.Base64.DEFAULT); ItemMustSee.name = name; ItemMustSee.email = email; ItemMustSee.number = number; ItemMustSee.location = location; ItemMustSee.like = like; ItemMustSee.greenOrNo = greenOrNo; ItemMustSee.imgBytes = valueDecoded; ItemMustSee.user = user; // byte[] imgByte = line.getBytes("UTF-8"); // Bitmap bmp = BitmapFactory.decodeByteArray(imgByte,0,imgByte.length); // ItemMustSee.imgByte = imgByte; Intent i = new Intent(MustSee.this, ItemMustSee.class); startActivity(i); socket.close(); } catch (IOException ex) { ex.printStackTrace(); } } }); thread.start(); } }); } }
true
7c93dc4485683e8bfe9c589e3f365aa51fbdd41d
Java
iipc/webarchive-commons
/src/main/java/org/archive/io/GenerationFileHandler.java
UTF-8
6,852
2.46875
2
[ "Apache-2.0" ]
permissive
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.io; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.LogRecord; import org.archive.util.FileUtils; /** * FileHandler with support for rotating the current file to * an archival name with a specified integer suffix, and * provision of a new replacement FileHandler with the current * filename. * * @author gojomo */ public class GenerationFileHandler extends FileHandler { private LinkedList<String> filenameSeries = new LinkedList<String>(); private boolean shouldManifest = false; /** * @return Returns the filenameSeries. */ public List<String> getFilenameSeries() { return filenameSeries; } /** * Constructor. * @param pattern * @param append * @param shouldManifest * @throws IOException * @throws SecurityException */ public GenerationFileHandler(String pattern, boolean append, boolean shouldManifest) throws IOException, SecurityException { super(pattern, append); filenameSeries.addFirst(pattern); this.shouldManifest = shouldManifest; } /** * @param filenameSeries * @param shouldManifest * @throws IOException */ public GenerationFileHandler(LinkedList<String> filenameSeries, boolean shouldManifest) throws IOException { super((String)filenameSeries.getFirst(), false); // Never append in this case this.filenameSeries = filenameSeries; this.shouldManifest = shouldManifest; } /** * Move the current file to a new filename with the storeSuffix in place * of the activeSuffix; continuing logging to a new file under the * original filename. * * @param storeSuffix Suffix to put in place of <code>activeSuffix</code> * @param activeSuffix Suffix to replace with <code>storeSuffix</code>. * @return GenerationFileHandler instance. * @throws IOException */ public GenerationFileHandler rotate(String storeSuffix, String activeSuffix) throws IOException { return rotate(storeSuffix, activeSuffix, false); } public GenerationFileHandler rotate(String storeSuffix, String activeSuffix, boolean mergeOld) throws IOException { close(); String filename = (String) filenameSeries.getFirst(); if (!filename.endsWith(activeSuffix)) { throw new FileNotFoundException("Active file does not have" + " expected suffix"); } String storeFilename = filename.substring(0, filename.length() - activeSuffix.length()) + storeSuffix; File activeFile = new File(filename); File storeFile = new File(storeFilename); FileUtils.moveAsideIfExists(storeFile); if (mergeOld) { File fileToAppendTo = new File(filenameSeries.getLast()); for (int i = filenameSeries.size() - 2; i >= 0; i--) { File f = new File(filenameSeries.get(i)); FileUtils.appendTo(fileToAppendTo, f); f.delete(); } filenameSeries.clear(); filenameSeries.add(filename); if (!fileToAppendTo.renameTo(storeFile)) { throw new IOException("Unable to move " + fileToAppendTo + " to " + storeFilename); } } else { if (!activeFile.renameTo(storeFile)) { throw new IOException("Unable to move " + filename + " to " + storeFilename); } } filenameSeries.add(1, storeFilename); GenerationFileHandler newGfh = new GenerationFileHandler( filenameSeries, shouldManifest); newGfh.setFormatter(this.getFormatter()); return newGfh; } /** * @return True if should manifest. */ public boolean shouldManifest() { return this.shouldManifest; } /** * Constructor-helper that rather than clobbering any existing * file, moves it aside with a timestamp suffix. * * @param filename * @param append * @param shouldManifest * @return * @throws SecurityException * @throws IOException */ public static GenerationFileHandler makeNew(String filename, boolean append, boolean shouldManifest) throws SecurityException, IOException { FileUtils.moveAsideIfExists(new File(filename)); return new GenerationFileHandler(filename, append, shouldManifest); } @Override public void publish(LogRecord record) { // when possible preformat outside synchronized superclass method // (our most involved UriProcessingFormatter can cache result) Formatter f = getFormatter(); if(!(f instanceof Preformatter)) { super.publish(record); } else { try { ((Preformatter)f).preformat(record); super.publish(record); } finally { ((Preformatter)f).clear(); } } } // // TODO: determine if there's another way to have this optimization without // negative impact on log-following (esp. in web UI) // /** // * Flush only 1/100th of the usual once-per-record, to reduce the time // * spent holding the synchronization lock. (Flush is primarily called in // * a superclass's synchronized publish()). // * // * The eventual close calls a direct flush on the target writer, so all // * rotates/ends will ultimately be fully flushed. // * // * @see java.util.logging.StreamHandler#flush() // */ // @Override // public synchronized void flush() { // flushCount++; // if(flushCount==100) { // super.flush(); // flushCount=0; // } // } // int flushCount; }
true
e2bfb8178f3e22a0e652e098623c845b434f1aa1
Java
xiwasong/freebatis
/src/main/java/cn/hn/java/summer/freebatis/mapper/rule/UnderlinedBeanMapperRule.java
UTF-8
2,702
2.90625
3
[]
no_license
package cn.hn.java.summer.freebatis.mapper.rule; /** * 下划线风格的映射规则 * UserId=>user_id * Created by xw2sy on 2017-04-15. */ public class UnderlinedBeanMapperRule implements IBeanMapperRule { //表名前缀 private String tablePrefix=""; //类名前缀 private String classPrefix=""; public UnderlinedBeanMapperRule() { } /** * @param tablePrefix 表名前缀 */ public UnderlinedBeanMapperRule(String tablePrefix){ this.tablePrefix=tablePrefix; } /** * @param tablePrefix 表名前缀 * @param classPrefix 类名前缀 */ public UnderlinedBeanMapperRule(String tablePrefix, String classPrefix){ this.tablePrefix=tablePrefix; this.classPrefix=classPrefix; } /** * 取表名 * * @param className 类名 * @return 表名 */ public String getTableName(String className) { return tablePrefix+camelToUnderline(className); } /** * 取列名 * * @param fieldName 属性名 * @return 列名 */ public String getColName(String fieldName) { return camelToUnderline(fieldName); } /** * 驼峰转为下划线风格 * @param name 待转换的名称 * @return 下划线风格 */ private String camelToUnderline(String name){ return name.replaceAll("([a-z]+)([A-Z])","$1_$2").toLowerCase(); } /** * 通过表名取类名 * * @param tableName 表名 * @return 类名 */ public String getClassName(String tableName) { return underlinedToCamel(classPrefix+"_"+tableName.replace(tablePrefix,""),false); } /** * 通过列名取属性名 * * @param colName * @return 属性名 */ public String getFieldName(String colName) { return underlinedToCamel(colName,true); } /** * 下划线转为驼峰 * @param name 待转换的名称 * @param skipFirst 忽略第一个 * @return 驼峰风格 */ private String underlinedToCamel(String name, boolean skipFirst){ String[] parts=name.split("_"); StringBuilder sbClassName=new StringBuilder(); for(String p : parts){ if (p == null || p.length() == 0) { continue; } if(skipFirst && sbClassName.length()==0){ sbClassName.append(p); continue; } sbClassName.append(p.substring(0,1).toUpperCase()+p.substring(1)); } return sbClassName.toString(); } }
true
82878b3484fda8a086f49eb2af8738c667ad4cd2
Java
MartinGeisse/public
/name.martingeisse.stackd-core-client/src/main/java/name/martingeisse/stackd/client/gui/element/PulseFillColor.java
UTF-8
2,837
2.6875
3
[ "MIT" ]
permissive
/** * Copyright (c) 2010 Martin Geisse * * This file is distributed under the terms of the MIT license. */ package name.martingeisse.stackd.client.gui.element; import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA; import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA; import static org.lwjgl.opengl.GL11.glBlendFunc; import name.martingeisse.common.util.ParameterUtil; import name.martingeisse.stackd.client.gui.util.Color; import name.martingeisse.stackd.client.gui.util.PulseFunction; import org.lwjgl.opengl.GL11; /** * This element fills its area with a pulsing RGBA color. * * This class does not store a pulse amplitude; use the color's * alpha value for that. */ public final class PulseFillColor extends AbstractFillElement { /** * the color */ private Color color; /** * the pulseFunction */ private PulseFunction pulseFunction; /** * the period */ private int period; /** * Constructor. */ public PulseFillColor() { this.color = Color.WHITE; this.pulseFunction = PulseFunction.ABSOLUTE_SINE; this.period = 2000; } /** * Getter method for the color. * @return the color */ public Color getColor() { return color; } /** * Setter method for the color. * @param color the color to set * @return this for chaining */ public PulseFillColor setColor(final Color color) { ParameterUtil.ensureNotNull(color, "color"); this.color = color; return this; } /** * Getter method for the pulseFunction. * @return the pulseFunction */ public PulseFunction getPulseFunction() { return pulseFunction; } /** * Setter method for the pulseFunction. * @param pulseFunction the pulseFunction to set * @return this for chaining */ public PulseFillColor setPulseFunction(final PulseFunction pulseFunction) { ParameterUtil.ensureNotNull(pulseFunction, "pulseFunction"); this.pulseFunction = pulseFunction; return this; } /** * Getter method for the period. * @return the period */ public int getPeriod() { return period; } /** * Setter method for the period. * @param period the period to set * @return this for chaining */ public PulseFillColor setPeriod(final int period) { this.period = period; return this; } /* (non-Javadoc) * @see name.martingeisse.stackd.client.gui.element.AbstractFillElement#draw() */ @Override protected void draw() { GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); color.glColorWithCombinedAlpha(pulseFunction.evaluate(getGui().getTime(), period)); final int x = getAbsoluteX(), y = getAbsoluteY(), w = getWidth(), h = getHeight(); GL11.glBegin(GL11.GL_TRIANGLE_FAN); GL11.glVertex2i(x, y); GL11.glVertex2i(x + w, y); GL11.glVertex2i(x + w, y + h); GL11.glVertex2i(x, y + h); GL11.glEnd(); } }
true
064a1bd17749f919233eb0e1e5ac7bad53ba79c1
Java
markus1978/tef
/hub.sam.tef.ocl/src/org/eclipse/emf/ocl/internal/cst/util/CSTAdapterFactory.java
UTF-8
34,778
1.921875
2
[]
no_license
/** * <copyright> * </copyright> * * $Id$ */ package org.eclipse.emf.ocl.internal.cst.util; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ocl.internal.cst.*; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see org.eclipse.emf.ocl.internal.cst.CSTPackage * @generated */ public class CSTAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static CSTPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CSTAdapterFactory() { if (modelPackage == null) { modelPackage = CSTPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch the delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CSTSwitch modelSwitch = new CSTSwitch() { public Object caseCSTNode(CSTNode object) { return createCSTNodeAdapter(); } public Object casePackageDeclarationCS(PackageDeclarationCS object) { return createPackageDeclarationCSAdapter(); } public Object caseContextDeclCS(ContextDeclCS object) { return createContextDeclCSAdapter(); } public Object casePropertyContextCS(PropertyContextCS object) { return createPropertyContextCSAdapter(); } public Object caseClassifierContextDeclCS(ClassifierContextDeclCS object) { return createClassifierContextDeclCSAdapter(); } public Object caseOperationContextDeclCS(OperationContextDeclCS object) { return createOperationContextDeclCSAdapter(); } public Object casePrePostOrBodyDeclCS(PrePostOrBodyDeclCS object) { return createPrePostOrBodyDeclCSAdapter(); } public Object caseOperationCS(OperationCS object) { return createOperationCSAdapter(); } public Object caseInitOrDerValueCS(InitOrDerValueCS object) { return createInitOrDerValueCSAdapter(); } public Object caseDerValueCS(DerValueCS object) { return createDerValueCSAdapter(); } public Object caseInitValueCS(InitValueCS object) { return createInitValueCSAdapter(); } public Object caseInvOrDefCS(InvOrDefCS object) { return createInvOrDefCSAdapter(); } public Object caseInvCS(InvCS object) { return createInvCSAdapter(); } public Object caseDefCS(DefCS object) { return createDefCSAdapter(); } public Object caseDefExpressionCS(DefExpressionCS object) { return createDefExpressionCSAdapter(); } public Object casePathNameCS(PathNameCS object) { return createPathNameCSAdapter(); } public Object caseVariableExpCS(VariableExpCS object) { return createVariableExpCSAdapter(); } public Object caseSimpleNameCS(SimpleNameCS object) { return createSimpleNameCSAdapter(); } public Object caseTypeCS(TypeCS object) { return createTypeCSAdapter(); } public Object casePrimitiveTypeCS(PrimitiveTypeCS object) { return createPrimitiveTypeCSAdapter(); } public Object caseTupleTypeCS(TupleTypeCS object) { return createTupleTypeCSAdapter(); } public Object caseCollectionTypeCS(CollectionTypeCS object) { return createCollectionTypeCSAdapter(); } public Object caseOCLExpressionCS(OCLExpressionCS object) { return createOCLExpressionCSAdapter(); } public Object caseLetExpCS(LetExpCS object) { return createLetExpCSAdapter(); } public Object caseIfExpCS(IfExpCS object) { return createIfExpCSAdapter(); } public Object caseMessageExpCS(MessageExpCS object) { return createMessageExpCSAdapter(); } public Object caseOCLMessageArgCS(OCLMessageArgCS object) { return createOCLMessageArgCSAdapter(); } public Object caseVariableCS(VariableCS object) { return createVariableCSAdapter(); } public Object caseLiteralExpCS(LiteralExpCS object) { return createLiteralExpCSAdapter(); } public Object caseEnumLiteralExpCS(EnumLiteralExpCS object) { return createEnumLiteralExpCSAdapter(); } public Object caseCollectionLiteralExpCS(CollectionLiteralExpCS object) { return createCollectionLiteralExpCSAdapter(); } public Object caseTupleLiteralExpCS(TupleLiteralExpCS object) { return createTupleLiteralExpCSAdapter(); } public Object casePrimitiveLiteralExpCS(PrimitiveLiteralExpCS object) { return createPrimitiveLiteralExpCSAdapter(); } public Object caseIntegerLiteralExpCS(IntegerLiteralExpCS object) { return createIntegerLiteralExpCSAdapter(); } public Object caseRealLiteralExpCS(RealLiteralExpCS object) { return createRealLiteralExpCSAdapter(); } public Object caseStringLiteralExpCS(StringLiteralExpCS object) { return createStringLiteralExpCSAdapter(); } public Object caseBooleanLiteralExpCS(BooleanLiteralExpCS object) { return createBooleanLiteralExpCSAdapter(); } public Object caseNullLiteralExpCS(NullLiteralExpCS object) { return createNullLiteralExpCSAdapter(); } public Object caseInvalidLiteralExpCS(InvalidLiteralExpCS object) { return createInvalidLiteralExpCSAdapter(); } public Object caseCollectionLiteralPartCS(CollectionLiteralPartCS object) { return createCollectionLiteralPartCSAdapter(); } public Object caseCollectionRangeCS(CollectionRangeCS object) { return createCollectionRangeCSAdapter(); } public Object caseCallExpCS(CallExpCS object) { return createCallExpCSAdapter(); } public Object caseLoopExpCS(LoopExpCS object) { return createLoopExpCSAdapter(); } public Object caseIteratorExpCS(IteratorExpCS object) { return createIteratorExpCSAdapter(); } public Object caseIterateExpCS(IterateExpCS object) { return createIterateExpCSAdapter(); } public Object caseFeatureCallExpCS(FeatureCallExpCS object) { return createFeatureCallExpCSAdapter(); } public Object caseOperationCallExpCS(OperationCallExpCS object) { return createOperationCallExpCSAdapter(); } public Object caseIsMarkedPreCS(IsMarkedPreCS object) { return createIsMarkedPreCSAdapter(); } public Object caseStateExpCS(StateExpCS object) { return createStateExpCSAdapter(); } public Object defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ public Adapter createAdapter(Notifier target) { return (Adapter)modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.CSTNode <em>Node</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.CSTNode * @generated */ public Adapter createCSTNodeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.PackageDeclarationCS <em>Package Declaration CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.PackageDeclarationCS * @generated */ public Adapter createPackageDeclarationCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.ContextDeclCS <em>Context Decl CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.ContextDeclCS * @generated */ public Adapter createContextDeclCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.PropertyContextCS <em>Property Context CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.PropertyContextCS * @generated */ public Adapter createPropertyContextCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.ClassifierContextDeclCS <em>Classifier Context Decl CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.ClassifierContextDeclCS * @generated */ public Adapter createClassifierContextDeclCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.OperationContextDeclCS <em>Operation Context Decl CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.OperationContextDeclCS * @generated */ public Adapter createOperationContextDeclCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.PrePostOrBodyDeclCS <em>Pre Post Or Body Decl CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.PrePostOrBodyDeclCS * @generated */ public Adapter createPrePostOrBodyDeclCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.OperationCS <em>Operation CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.OperationCS * @generated */ public Adapter createOperationCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.InitOrDerValueCS <em>Init Or Der Value CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.InitOrDerValueCS * @generated */ public Adapter createInitOrDerValueCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.DerValueCS <em>Der Value CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.DerValueCS * @generated */ public Adapter createDerValueCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.InitValueCS <em>Init Value CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.InitValueCS * @generated */ public Adapter createInitValueCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.InvOrDefCS <em>Inv Or Def CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.InvOrDefCS * @generated */ public Adapter createInvOrDefCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.InvCS <em>Inv CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.InvCS * @generated */ public Adapter createInvCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.DefCS <em>Def CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.DefCS * @generated */ public Adapter createDefCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.DefExpressionCS <em>Def Expression CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.DefExpressionCS * @generated */ public Adapter createDefExpressionCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.PathNameCS <em>Path Name CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.PathNameCS * @generated */ public Adapter createPathNameCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.VariableExpCS <em>Variable Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.VariableExpCS * @generated */ public Adapter createVariableExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.SimpleNameCS <em>Simple Name CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.SimpleNameCS * @generated */ public Adapter createSimpleNameCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.TypeCS <em>Type CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.TypeCS * @generated */ public Adapter createTypeCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.PrimitiveTypeCS <em>Primitive Type CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.PrimitiveTypeCS * @generated */ public Adapter createPrimitiveTypeCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.TupleTypeCS <em>Tuple Type CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.TupleTypeCS * @generated */ public Adapter createTupleTypeCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.CollectionTypeCS <em>Collection Type CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.CollectionTypeCS * @generated */ public Adapter createCollectionTypeCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.OCLExpressionCS <em>OCL Expression CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.OCLExpressionCS * @generated */ public Adapter createOCLExpressionCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.LetExpCS <em>Let Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.LetExpCS * @generated */ public Adapter createLetExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.IfExpCS <em>If Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.IfExpCS * @generated */ public Adapter createIfExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.MessageExpCS <em>Message Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.MessageExpCS * @generated */ public Adapter createMessageExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.OCLMessageArgCS <em>OCL Message Arg CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.OCLMessageArgCS * @generated */ public Adapter createOCLMessageArgCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.VariableCS <em>Variable CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.VariableCS * @generated */ public Adapter createVariableCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.LiteralExpCS <em>Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.LiteralExpCS * @generated */ public Adapter createLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.EnumLiteralExpCS <em>Enum Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.EnumLiteralExpCS * @generated */ public Adapter createEnumLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.CollectionLiteralExpCS <em>Collection Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.CollectionLiteralExpCS * @generated */ public Adapter createCollectionLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.TupleLiteralExpCS <em>Tuple Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.TupleLiteralExpCS * @generated */ public Adapter createTupleLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.PrimitiveLiteralExpCS <em>Primitive Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.PrimitiveLiteralExpCS * @generated */ public Adapter createPrimitiveLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.IntegerLiteralExpCS <em>Integer Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.IntegerLiteralExpCS * @generated */ public Adapter createIntegerLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.RealLiteralExpCS <em>Real Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.RealLiteralExpCS * @generated */ public Adapter createRealLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.StringLiteralExpCS <em>String Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.StringLiteralExpCS * @generated */ public Adapter createStringLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.BooleanLiteralExpCS <em>Boolean Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.BooleanLiteralExpCS * @generated */ public Adapter createBooleanLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.NullLiteralExpCS <em>Null Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.NullLiteralExpCS * @generated */ public Adapter createNullLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.InvalidLiteralExpCS <em>Invalid Literal Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.InvalidLiteralExpCS * @generated */ public Adapter createInvalidLiteralExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.CollectionLiteralPartCS <em>Collection Literal Part CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.CollectionLiteralPartCS * @generated */ public Adapter createCollectionLiteralPartCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.CollectionRangeCS <em>Collection Range CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.CollectionRangeCS * @generated */ public Adapter createCollectionRangeCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.CallExpCS <em>Call Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.CallExpCS * @generated */ public Adapter createCallExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.LoopExpCS <em>Loop Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.LoopExpCS * @generated */ public Adapter createLoopExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.IteratorExpCS <em>Iterator Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.IteratorExpCS * @generated */ public Adapter createIteratorExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.IterateExpCS <em>Iterate Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.IterateExpCS * @generated */ public Adapter createIterateExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.FeatureCallExpCS <em>Feature Call Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.FeatureCallExpCS * @generated */ public Adapter createFeatureCallExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.OperationCallExpCS <em>Operation Call Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.OperationCallExpCS * @generated */ public Adapter createOperationCallExpCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.IsMarkedPreCS <em>Is Marked Pre CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.IsMarkedPreCS * @generated */ public Adapter createIsMarkedPreCSAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.eclipse.emf.ocl.internal.cst.StateExpCS <em>State Exp CS</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.eclipse.emf.ocl.internal.cst.StateExpCS * @generated */ public Adapter createStateExpCSAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //CSTAdapterFactory
true
365b81a096d4cb874e7905bdce6b4aed0cc5bfd4
Java
xwic/sandbox
/de.xwic.sandbox.system.model/src/de/xwic/system/model/roles/editor/model/OtherControlId.java
UTF-8
2,447
1.960938
2
[]
no_license
package de.xwic.system.model.roles.editor.model; /******************************************************************************* * Copyright 2015 xWic group (http://www.xwic.de) * * 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. *******************************************************************************/ /** * * * @author Aron Cotrau */ public class OtherControlId { private String scopeId; private String lblId; private String chkAccessId; private String chkExecuteId; private boolean access = false; private boolean execute = false; /** * @return the access */ public boolean isAccess() { return access; } /** * @param access * the access to set */ public void setAccess(boolean access) { this.access = access; } /** * @return the execute */ public boolean isExecute() { return execute; } /** * @param execute * the execute to set */ public void setExecute(boolean execute) { this.execute = execute; } /** * @return the scopeId */ public String getScopeId() { return scopeId; } /** * @param scopeId * the scopeId to set */ public void setScopeId(String scopeId) { this.scopeId = scopeId; } /** * @return the lblId */ public String getLblId() { return lblId; } /** * @param lblId * the lblId to set */ public void setLblId(String lblId) { this.lblId = lblId; } /** * @return the chkAccessId */ public String getChkAccessId() { return chkAccessId; } /** * @param chkAccessId * the chkAccessId to set */ public void setChkAccessId(String chkAccessId) { this.chkAccessId = chkAccessId; } /** * @return the chkExecuteId */ public String getChkExecuteId() { return chkExecuteId; } /** * @param chkExecuteId * the chkExecuteId to set */ public void setChkExecuteId(String chkExecuteId) { this.chkExecuteId = chkExecuteId; } }
true
999c6009fecdbf610e7a4a70ef8ccc37a945ecd7
Java
epic8009/plethora
/src/main/java/org/squiddev/plethora/core/Context.java
UTF-8
1,367
2.03125
2
[ "MIT" ]
permissive
package org.squiddev.plethora.core; import dan200.computercraft.api.lua.ILuaObject; import org.apache.commons.lang3.tuple.Pair; import org.squiddev.plethora.api.method.IContext; import org.squiddev.plethora.api.method.ICostHandler; import org.squiddev.plethora.api.method.IMethod; import org.squiddev.plethora.api.method.IUnbakedContext; import org.squiddev.plethora.api.module.IModuleContainer; import org.squiddev.plethora.api.reference.IReference; import javax.annotation.Nonnull; import java.util.List; public class Context<T> extends PartialContext<T> implements IContext<T> { private final IUnbakedContext<T> parent; public Context(@Nonnull IUnbakedContext<T> parent, @Nonnull T target, @Nonnull ICostHandler handler, @Nonnull Object[] context, @Nonnull IModuleContainer modules) { super(target, handler, context, modules); this.parent = parent; } @Nonnull @Override public <U> IUnbakedContext<U> makeChild(@Nonnull IReference<U> target, @Nonnull IReference<?>... context) { return parent.makeChild(target, context); } @Nonnull @Override public IUnbakedContext<T> unbake() { return parent; } @Nonnull @Override public ILuaObject getObject() { Pair<List<IMethod<?>>, List<IUnbakedContext<?>>> pair = MethodRegistry.instance.getMethodsPaired(parent, this); return new MethodWrapperLuaObject(pair.getLeft(), pair.getRight()); } }
true
2199120e60077c06f8c9e8d30ba251e713708873
Java
pedro687/spring-feign-kafka-docker
/address/src/main/java/com/spiet/address/service/CepService.java
UTF-8
553
1.953125
2
[]
no_license
package com.spiet.address.service; import com.spiet.address.gateway.dtos.ViaCepResponse; import com.spiet.address.gateway.services.ViaCepService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @Service @Slf4j public class CepService { @Autowired private ViaCepService viaCepService; public ResponseEntity<ViaCepResponse> getCep(String cep) { return viaCepService.getCep(cep); } }
true
13428ef8f3e98c1dfccbe2f302048e8016785b8a
Java
DanierJ/learning-selenium
/testingFramework/src/main/java/com/danjerous/framework/kimway/SignUpPage.java
UTF-8
945
2.359375
2
[]
no_license
package com.danjerous.framework.kimway; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class SignUpPage extends PageObject { public SignUpPage(WebDriver driver) { super(driver); // Assert.assertTrue(firstName.isDisplayed()); } public boolean isInitialized() { return firstName.isDisplayed(); } @FindBy(id = "firstName") private WebElement firstName; @FindBy(id = "lastName") private WebElement lastName; @FindBy(id = "signUp") private WebElement submitButton; public void enterName(String firstName, String lastName) { this.firstName.clear(); this.firstName.sendKeys(firstName); this.lastName.clear(); this.lastName.sendKeys(lastName); } public ReceiptPage submit() { submitButton.click(); return new ReceiptPage(driver); } }
true
c344ef4e8ce3614ea73a51b8fd8aae4f3166ac96
Java
leobar37/ejercicios_java
/Concyt5e/src/capa_cliente/frmInvestigador.java
UTF-8
9,877
2.140625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package capa_cliente; import capa_datos.Archivo; import capa_datos.Lista_Investigador; import capa_negocio.Investigador; import javax.swing.JOptionPane; /** * * @author JOSE */ public class frmInvestigador extends javax.swing.JInternalFrame { /** * Creates new form frmInvestigador */ public frmInvestigador() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { panel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); txtCodigo = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); btnGenerarCodigo = new javax.swing.JToggleButton(); jLabel3 = new javax.swing.JLabel(); txtEdad = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); txtNombre = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); cboUniversidad = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); cboSexo = new javax.swing.JComboBox(); btnRegistrar = new javax.swing.JButton(); setClosable(true); setIconifiable(true); setMaximizable(true); jLabel1.setText("codigo Investigador:"); jLabel2.setText("Registarr Investigador"); btnGenerarCodigo.setText("Generar"); btnGenerarCodigo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGenerarCodigoActionPerformed(evt); } }); jLabel3.setText("nombre:"); jLabel4.setText("edad:"); jLabel5.setText("sexo"); cboUniversidad.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "UniversidadProcedencia", "UNI", "USAT", "UNPRG", "UTP", "UPC", "UCE", " ", " " })); jLabel6.setText("Universidad:"); cboSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "seleccione sexo", "Masculino", "Femenino", " " })); btnRegistrar.setText("Registrar Investigador"); btnRegistrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRegistrarActionPerformed(evt); } }); javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel); panel.setLayout(panelLayout); panelLayout.setHorizontalGroup( panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelLayout.createSequentialGroup() .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelLayout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel6) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cboSexo, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtEdad, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addGroup(panelLayout.createSequentialGroup() .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(35, 35, 35) .addComponent(btnGenerarCodigo)) .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cboUniversidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(panelLayout.createSequentialGroup() .addGap(174, 174, 174) .addComponent(btnRegistrar))) .addContainerGap(63, Short.MAX_VALUE)) ); panelLayout.setVerticalGroup( panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelLayout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jLabel2) .addGap(24, 24, 24) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnGenerarCodigo)) .addGap(23, 23, 23) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txtEdad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(cboSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(cboUniversidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addComponent(btnRegistrar) .addContainerGap(39, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarActionPerformed String codigo = txtCodigo.getText(); String nombre = txtNombre.getText(); int edad = Integer.parseInt(txtEdad.getText()); String sexo = cboSexo.getSelectedItem().toString(); String universidad = cboUniversidad.getSelectedItem().toString(); Investigador objInvestigador = new Investigador(codigo, nombre, edad, sexo, universidad); Lista_Investigador.adicionar(objInvestigador); Archivo.GuardarInvestigador(Lista_Investigador.consultar()); JOptionPane.showMessageDialog(null, "Registrado"); }//GEN-LAST:event_btnRegistrarActionPerformed private void btnGenerarCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerarCodigoActionPerformed String codigo = "IN"; for (int i = 0; i <4; i++) { int r = (int) (Math.random() * 9)+1; codigo = codigo +r; } txtCodigo.setText(codigo); }//GEN-LAST:event_btnGenerarCodigoActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JToggleButton btnGenerarCodigo; private javax.swing.JButton btnRegistrar; private javax.swing.JComboBox cboSexo; private javax.swing.JComboBox cboUniversidad; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel panel; private javax.swing.JTextField txtCodigo; private javax.swing.JTextField txtEdad; private javax.swing.JTextField txtNombre; // End of variables declaration//GEN-END:variables }
true
2d2f3693930ca33c3bca6497a14c623970f25f85
Java
moutainhigh/work-ms-msBoss
/src/main/java/com/eduboss/baiwang/domain/KaiPiaoContent.java
UTF-8
970
1.632813
2
[]
no_license
package com.eduboss.baiwang.domain; import java.io.Serializable; public class KaiPiaoContent implements Serializable{ private static final long serialVersionUID = -7064845154198200839L; private String FPQQLSH; private String FP_DM; private String FP_HM; private String JYM; private String KPRQ; private String PDF_URL; public String getFPQQLSH() { return FPQQLSH; } public void setFPQQLSH(String fPQQLSH) { FPQQLSH = fPQQLSH; } public String getFP_DM() { return FP_DM; } public void setFP_DM(String fP_DM) { FP_DM = fP_DM; } public String getFP_HM() { return FP_HM; } public void setFP_HM(String fP_HM) { FP_HM = fP_HM; } public String getJYM() { return JYM; } public void setJYM(String jYM) { JYM = jYM; } public String getKPRQ() { return KPRQ; } public void setKPRQ(String kPRQ) { KPRQ = kPRQ; } public String getPDF_URL() { return PDF_URL; } public void setPDF_URL(String pDF_URL) { PDF_URL = pDF_URL; } }
true
0a71b621b48d98f7d91a119fdfb6720a86f478e4
Java
treelogic-swe/aws-mock
/src/integration-test/java/com/tlswe/awsmock/cloudwatch/GetMetricStaticticsCloudwatchTest.java
UTF-8
5,040
2.1875
2
[ "MIT" ]
permissive
package com.tlswe.awsmock.cloudwatch; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.services.cloudwatch.model.Datapoint; import com.amazonaws.services.cloudwatch.model.MetricAlarm; import com.tlswe.awsmock.common.util.Constants; public class GetMetricStaticticsCloudwatchTest extends CloudWatchBaseTest { /** * 2 minutes timeout. */ private static final int TIMEOUT_LEVEL1 = 120000; /** * Log writer for this class. */ private static Logger log = LoggerFactory.getLogger(GetMetricStaticticsCloudwatchTest.class); /** * Test GetMetricStatictics for CPUUtilization. */ @Test(timeout = TIMEOUT_LEVEL1) public final void GetMetricStaticticsTest() { log.info("Start GetMetricStatictics Cloudwatch test"); Datapoint dataPoint = getMetricStaticticsTest(Constants.CPU_UTILIZATION); Assert.assertNotNull("data point should not be null", dataPoint); Assert.assertNotNull("average should not be null", dataPoint.getAverage()); Assert.assertNotNull("sample count should not be null", dataPoint.getSampleCount()); } /** * Test GetMetricStatictics for Disk Read bytes. */ @Test(timeout = TIMEOUT_LEVEL1) public final void GetMetricStaticticsTestForDiskReadBytes() { log.info("Start GetMetricStatictics Cloudwatch test"); Datapoint dataPoint = getMetricStaticticsTest(Constants.DISK_READ_BYTES); Assert.assertNotNull("data point should not be null", dataPoint); Assert.assertNotNull("average should not be null", dataPoint.getAverage()); Assert.assertNotNull("sample count should not be null", dataPoint.getSampleCount()); } /** * Test GetMetricStatictics for Disk Write bytes. */ @Test(timeout = TIMEOUT_LEVEL1) public final void GetMetricStaticticsTestForDiskWriteBytes() { log.info("Start GetMetricStatictics Cloudwatch test"); Datapoint dataPoint = getMetricStaticticsTest(Constants.DISK_WRITE_BYTES); Assert.assertNotNull("data point should not be null", dataPoint); Assert.assertNotNull("average should not be null", dataPoint.getAverage()); Assert.assertNotNull("sample count should not be null", dataPoint.getSampleCount()); } /** * Test GetMetricStatictics for Disk Read Ops. */ @Test(timeout = TIMEOUT_LEVEL1) public final void GetMetricStaticticsTestForDiskReadOps() { log.info("Start GetMetricStatictics Cloudwatch test"); Datapoint dataPoint = getMetricStaticticsTest(Constants.DISK_READ_OPS); Assert.assertNotNull("data point should not be null", dataPoint); Assert.assertNotNull("average should not be null", dataPoint.getAverage()); Assert.assertNotNull("sample count should not be null", dataPoint.getSampleCount()); } /** * Test GetMetricStatictics for Disk Write Ops. */ @Test(timeout = TIMEOUT_LEVEL1) public final void GetMetricStaticticsTestForDiskWriteOps() { log.info("Start GetMetricStatictics Cloudwatch test"); Datapoint dataPoint = getMetricStaticticsTest(Constants.DISK_WRITE_OPS); Assert.assertNotNull("data point should not be null", dataPoint); Assert.assertNotNull("average should not be null", dataPoint.getAverage()); Assert.assertNotNull("sample count should not be null", dataPoint.getSampleCount()); } /** * Test GetMetricStatictics for Network In. */ @Test(timeout = TIMEOUT_LEVEL1) public final void GetMetricStaticticsTestForNetworkIn() { log.info("Start GetMetricStatictics Cloudwatch test"); Datapoint dataPoint = getMetricStaticticsTest(Constants.NETWORK_IN); Assert.assertNotNull("data point should not be null", dataPoint); Assert.assertNotNull("average should not be null", dataPoint.getAverage()); Assert.assertNotNull("sample count should not be null", dataPoint.getSampleCount()); } /** * Test GetMetricStatictics for Network Out. */ @Test(timeout = TIMEOUT_LEVEL1) public final void GetMetricStaticticsTestForNetworkOut() { log.info("Start GetMetricStatictics Cloudwatch test"); Datapoint dataPoint = getMetricStaticticsTest(Constants.NETWORK_OUT); Assert.assertNotNull("data point should not be null", dataPoint); Assert.assertNotNull("average should not be null", dataPoint.getAverage()); Assert.assertNotNull("sample count should not be null", dataPoint.getSampleCount()); } /** * Test GetMetricAlarm. */ @Test(timeout = TIMEOUT_LEVEL1) public final void GetMetricAlarm() { log.info("Start GetMetricAlarm Cloudwatch test"); MetricAlarm metricAlarm = describerAlarmsTest(); Assert.assertNotNull("metricAlarm should not be null", metricAlarm); Assert.assertNotNull("metricAlarm Name should not be null", metricAlarm.getAlarmName()); } }
true
c70bf0bdda68ce19decbac0b03a034f322b50d7a
Java
xiexiaodong666/cbest.tiancheng
/service-settlement/src/main/java/com/welfare/servicesettlement/mq/OrderAfterSaleMqListener.java
UTF-8
3,244
2.015625
2
[]
no_license
package com.welfare.servicesettlement.mq; import com.alibaba.fastjson.JSON; import com.welfare.common.annotation.DistributedLock; import com.welfare.common.constants.WelfareConstant; import com.welfare.common.exception.BizAssert; import com.welfare.common.exception.ExceptionCode; import com.welfare.persist.dao.OrderInfoDao; import com.welfare.persist.dao.OrderInfoDetailDao; import com.welfare.persist.entity.OrderInfo; import com.welfare.persist.entity.OrderInfoDetail; import com.welfare.servicesettlement.dto.mall.AftersaleOrderMqInfo; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.logging.log4j.util.Strings; import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Objects; /** * Description: * * @author Yuxiang Li * @email yuxiang.li@sjgo365.com * @date 3/29/2021 */ @Slf4j @Component @RequiredArgsConstructor @RocketMQMessageListener( topic = "${rocketmq.topic.order-online-after-sale}", consumerGroup = MqConstant.ConsumerGroup.ONLINE_ORDER_AFTER_SALE_CONSUMER_GROUP ) public class OrderAfterSaleMqListener implements RocketMQListener<AftersaleOrderMqInfo> { private final OrderInfoDao orderInfoDao; private final OrderInfoDetailDao orderInfoDetailDao; /** * 此种类型的pay_type需要忽略(表示老的员工卡支付的) */ private static final Integer IGNORE_PAY_TYPE = 6; @Override @Transactional(rollbackFor = Exception.class) @DistributedLock(lockPrefix = "order-save",lockKey = "#aftersaleOrderMqInfo.orgOrderNo") public void onMessage(AftersaleOrderMqInfo aftersaleOrderMqInfo) { log.info("return order rocketmq msg received:{}", JSON.toJSONString(aftersaleOrderMqInfo)); String tradeNo = aftersaleOrderMqInfo.getTradeNo(); if(Strings.isEmpty(tradeNo) || IGNORE_PAY_TYPE.equals(aftersaleOrderMqInfo.getPayType())){ log.info("此逆向订单不需要保存"); //没有交易单号,则没有支付过,不保存。老的员工卡也不保存 return; } OrderInfo refundOrderInDb = orderInfoDao.getOneByTradeNo(tradeNo, WelfareConstant.TransType.REFUND.code()); if(Objects.nonNull(refundOrderInDb)){ log.info("此流水号对应的订单已经保存,不需要再次保存"); return; } String orderNo = aftersaleOrderMqInfo.getOrgOrderNo().toString(); OrderInfo originalOrder = orderInfoDao.getOneByOrderNo(orderNo, WelfareConstant.TransType.CONSUME.code()); BizAssert.notNull(originalOrder, ExceptionCode.DATA_NOT_EXIST,"正向订单不存在"); OrderInfo orderInfo = aftersaleOrderMqInfo.parseFromOriginalOrder(originalOrder); orderInfo.setOrderWholesaleAmount(aftersaleOrderMqInfo.getRefundWholesaleAmount()); List<OrderInfoDetail> orderInfoDetails = aftersaleOrderMqInfo.parseOrderInfoDetails(WelfareConstant.TransType.REFUND); orderInfoDetailDao.saveBatch(orderInfoDetails); orderInfoDao.save(orderInfo); } }
true
ddc534228879ca8a6b96a4c18c0373cb9a6902cf
Java
khurana724/technical
/src/test/java/com/exl/technical/JUnitTestSuite.java
UTF-8
654
1.640625
2
[]
no_license
package com.exl.technical; import org.junit.Rule; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import ru.stqa.selenium.factory.WebDriverPool; @RunWith(Suite.class) @SuiteClasses({GoogleMapsTest.class}) public class JUnitTestSuite { @Rule public TestRule webDriverPool = new TestWatcher() { @Override protected void finished(Description description) { super.finished(description); WebDriverPool.DEFAULT.dismissAll(); }; }; }
true
21a4f34561b237d11a02703dbf7ca3818070ec85
Java
PabloSaro/Practica2
/src/simulator/model/MostCrowdedStrategy.java
UTF-8
957
2.8125
3
[]
no_license
package simulator.model; import java.util.List; public class MostCrowdedStrategy implements LightSwitchingStrategy { private int timeSlot; public MostCrowdedStrategy(int timeSlot) { this.timeSlot= timeSlot; } public int chooseNextGreen(List<Road> roads, List<List<Vehicle>> qs, int currGreen, int lastSwitchingTime, int currTime) { int index = currGreen; int tam = 0; if(roads.size() != 0) { if(currGreen == -1) { index = 0; for(int i =0; i < roads.size();i++) { if(tam < qs.get(i).size()) { index = i; tam = qs.size(); } } }else if(currTime - lastSwitchingTime < timeSlot){ index = currGreen; }else { for(int i =(currGreen+1 % roads.size()); i != currGreen;i++) { if(i == roads.size()) { i=0; } if(tam < qs.get(i).size()) { index = i; tam = qs.size(); } } } }else { index = -1; } return index; } }
true
43702e8b47a067f4aec5895bb52f71c9a56fe091
Java
Alignment-PRP/Alignment
/app/controllers/Authenticator.java
UTF-8
932
2.5
2
[ "CC0-1.0" ]
permissive
package controllers; import models.User; import org.mindrot.jbcrypt.BCrypt; import play.mvc.Controller; import play.mvc.Result; import java.util.concurrent.Callable; /** * Created by andrfo on 16.02.2017. */ public class Authenticator extends Controller { /** * Checks username/pass combination to the database. * @param user * @param dbUser * @return */ public boolean authenticate(User user, User dbUser){ return BCrypt.checkpw(user.pass, dbUser.pass); } public Result validateSession(Callable<Result> func){ if(session("connected") != null){ try{ return func.call(); } catch (Exception e){ //TODO: Logging e.printStackTrace(); return unauthorized(); } } else{ return unauthorized(views.html.login.render()); } } }
true
f49320a8e37ab0c66858847e335cc716db824685
Java
IamKingWaiMark/AndroidFirebase
/service/src/main/java/com/kwm/android/firebase/service/interfaces/IBatchComplete.java
UTF-8
131
1.570313
2
[]
no_license
package com.kwm.android.firebase.service.interfaces; public interface IBatchComplete { void onSuccess(); void onFail(); }
true
5a8e3ab1b1c394022d6c45f3c8b5104a45bf407e
Java
Ervisa1/QUIZ_APP
/quiz-backend/src/main/java/pl/sdacademy/projektplus/quiz/StartupRunner.java
UTF-8
1,217
2.6875
3
[]
no_license
package pl.sdacademy.projektplus.quiz; import lombok.extern.java.Log; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import pl.sdacademy.projektplus.quiz.database.entities.PlayerEntity; import pl.sdacademy.projektplus.quiz.database.repositories.PlayerRepository; import pl.sdacademy.projektplus.quiz.services.QuizDataService; import java.util.List; @Component @Log public class StartupRunner implements CommandLineRunner { @Autowired private PlayerRepository playerRepository; @Autowired private QuizDataService quizDataService; @Override public void run(String...args) throws Exception { log.info("Executing startup actions..."); playerRepository.save(new PlayerEntity("John")); playerRepository.save(new PlayerEntity("Harry")); playerRepository.save(new PlayerEntity("George")); log.info("List of players from database:"); List<PlayerEntity> playersFromDatabase = playerRepository.findAll(); for (PlayerEntity player : playersFromDatabase) { log.info("Retrieved player: " + player); } } }
true
b692b4fa399935e5c8ce9ddd50214edeb6f74b0b
Java
SecurityRAT/case-management
/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionKeyDTO.java
UTF-8
1,707
2.140625
2
[]
no_license
package org.securityrat.casemanagement.service.dto; import org.securityrat.casemanagement.domain.enumeration.ExtensionSection; import org.securityrat.casemanagement.domain.enumeration.ExtensionType; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import javax.persistence.Lob; import javax.validation.constraints.NotNull; public class ExtensionKeyDTO { @NotNull private Long id; @JsonIgnore private RequirementSetDTO requirementSet; @NotNull private String name; @Lob private String description; @NotNull @JsonIgnore private ExtensionSection section; private ExtensionType type; private Integer showOrder; public Long getId() { return id; } public void setId(Long id) { this.id = id; } @JsonIgnore public RequirementSetDTO getRequirementSet() { return requirementSet; } @JsonProperty public void setRequirementSet(RequirementSetDTO requirementSet) { this.requirementSet = requirementSet; } @NotNull public String getName() { return name; } public void setName(@NotNull String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @JsonIgnore public ExtensionSection getSection() { return section; } @JsonProperty public void setSection(ExtensionSection section) { this.section = section; } public ExtensionType getType() { return type; } public void setType(ExtensionType type) { this.type = type; } public Integer getShowOrder() { return showOrder; } public void setShowOrder(Integer showOrder) { this.showOrder = showOrder; } }
true
b116ccd91932858972726b16cdf381bb592d7245
Java
sofeeGud/javajdbcgrom
/src/main/java/hibernate/lesson1/hw/Demo.java
UTF-8
496
2.53125
3
[]
no_license
package hibernate.lesson1.hw; public class Demo { public static void main(String[] args) { ProductRepository productRepository = new ProductRepository(); Product product = new Product(); product.setId(99); product.setName("table"); product.setDescription("grey & blue & red"); product.setPrice(70); productRepository.save(product); productRepository.update(product); productRepository.delete(product.getId()); } }
true
dbc0216ea6c90b624ec5faa95b536851dba324ae
Java
chenliguan/seniorlibs
/kotlinlib/src/main/java/com/read/kotlinlib/jvm/GCRootThread.java
UTF-8
2,243
3.3125
3
[]
no_license
package com.read.kotlinlib.jvm; /** * Author: chen * Version: 1.0.0 * Date: 2021/2/18. * Mender: * Modify: * Description: 验证活跃线程作为 GC Root */ public class GCRootThread { private static String TAG = "GCRoot"; private int _10MB = 10 * 1024 * 1024; private byte[] memory = new byte[8 * _10MB]; public static void main(String[] args) throws Exception { System.out.println(TAG + " start"); printMemory(); AsyncTask at = new AsyncTask(new GCRootThread()); Thread thread = new Thread(at); thread.start(); System.gc(); System.out.println(TAG + " main() end, GC end"); printMemory(); thread.join(); at = null; System.gc(); System.out.println(TAG + " thread end, GC end"); printMemory(); } /** * Print out the remaining space and total space of the current JVM */ public static void printMemory() { System.out.print(TAG + " free is " + Runtime.getRuntime().freeMemory() / 1024 / 1024 + " M, "); System.out.println(TAG + " total is " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + " M, "); } private static class AsyncTask implements Runnable { private GCRootThread gcRootThread; public AsyncTask(GCRootThread gcRootThread) { this.gcRootThread = gcRootThread; } @Override public void run() { try { Thread.sleep(500); } catch (Exception e) { } } } // GCRoot start // GCRoot free is 240 M, GCRoot total is 243 M, // GCRoot main() end, GC end // GCRoot free is 161 M, GCRoot total is 243 M, // GCRoot thread end, GC end // GCRoot free is 241 M, GCRoot total is 243 M, // 可以看出: // 程序刚开始时是 242M 内存,当调用第一次 GC 时线程并没有执行结束,并且它作为 GC Root,所以它所引用的 80M 内存并不会被 GC 回收掉。 // thread.join() 保证线程结束再调用后续代码。 // 所以当调用第二次 GC 前,线程已经执行完毕并被置为 null,这时线程已经被销毁,所以之前线程所引用的 80M 此时会被 GC 回收掉。 }
true
43b6ac74c05378ad49dc2bbd694c4c46d6b00091
Java
zjxjwxk/LeetCode
/src/com/zjxjwxk/leetcode/_0300_Longest_Increasing_Subsequence/Solution2Test.java
UTF-8
876
2.71875
3
[]
no_license
package com.zjxjwxk.leetcode._0300_Longest_Increasing_Subsequence; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class Solution2Test { private final Solution2 solution2 = new Solution2(); @Test void lengthOfLIS1() { int[] nums = {10, 9, 2, 5, 3, 7, 101, 18}; int ans = 4; assertEquals(ans, solution2.lengthOfLIS(nums)); } @Test void lengthOfLIS2() { int[] nums = {0}; int ans = 1; assertEquals(ans, solution2.lengthOfLIS(nums)); } @Test void lengthOfLIS3() { int[] nums = {}; int ans = 0; assertEquals(ans, solution2.lengthOfLIS(nums)); } @Test void lengthOfLIS4() { int[] nums = {3, 5, 6, 2, 5, 4, 19, 5, 6, 7, 12}; int ans = 6; assertEquals(ans, solution2.lengthOfLIS(nums)); } }
true
b9b66f82841818284c9d5a3b65c20e090974789b
Java
laubosslink/courses-practical-work
/java/RVB/RVB/src/Controllers/TextFieldController.java
UTF-8
1,224
3.03125
3
[]
no_license
package Controllers; import Views.*; import Models.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTextField; /** * * @author laubosslink <laubosslink@society-lbl.com> */ public class TextFieldController implements ActionListener{ private TextFieldView view; private RVBModel model; public TextFieldController(TextFieldView view, RVBModel model) { this.view = view; this.model = model; this.view.getR().addActionListener(this); this.view.getV().addActionListener(this); this.view.getB().addActionListener(this); } @Override public void actionPerformed(ActionEvent ae) { JTextField src = null; int srcInt = 0; if(ae.getSource() instanceof JTextField){ src = (JTextField) ae.getSource(); srcInt = Integer.parseInt(src.getText()); if(src == this.view.getR()){ this.model.setR(srcInt); } else if(ae.getSource() == this.view.getV()){ this.model.setV(srcInt); } else if(ae.getSource() == this.view.getB()){ this.model.setB(srcInt); } } } }
true
dd9d0a56f6633b0d4779c6dbba4fc077c5eb1d80
Java
AndreGodinho7/TAN-Bayesian-networks
/exceptions/IllegalScoreException.java
UTF-8
345
2.8125
3
[]
no_license
package exceptions; /** * Exception is thrown when a string different from "LL" or "MDL" is used to specify the score. */ public class IllegalScoreException extends Exception { public IllegalScoreException() { super("Score undefined in input command. Please insert LL for LL criteria or MDL for MDL criteria."); } }
true
ce3b0b6e95861c3847fd2f20e6bbcb463f10aa65
Java
gaied12/ecole_spring
/src/main/java/com/example/Ecoleback/Service/TtableService.java
UTF-8
3,060
2.140625
2
[]
no_license
package com.example.Ecoleback.Service; import com.example.Ecoleback.Model.File; import com.example.Ecoleback.Model.Level; import com.example.Ecoleback.Model.Prof; import com.example.Ecoleback.Model.TimeTable; import com.example.Ecoleback.Repository.FileRepository; import com.example.Ecoleback.Repository.LevelRepository; import com.example.Ecoleback.Repository.ProfRepository; import com.example.Ecoleback.Repository.TimeTableRepository; import com.example.Ecoleback.Util.Ttable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.util.Optional; @Service public class TtableService implements ItimeTableService { @Autowired FileRepository fileRepository ; @Autowired TimeTableRepository tableRepository; @Autowired IFileSytemStorage fileSytemStorage ; @Autowired LevelRepository levelRepository ; @Autowired ProfRepository profRepository; @Override public TimeTable addTtable(MultipartFile multipartFile,String idLevel,String title,String desc) { File file= fileSytemStorage.saveFile(multipartFile); Level level=null; Optional<Level> levell=levelRepository.findById(Long.valueOf(idLevel)); level=levell.get(); TimeTable timeTable=new TimeTable() ; timeTable.setLevel(level); timeTable.setTitle(title); timeTable.setDesc(desc); timeTable.setFile(file); timeTable= tableRepository.save(timeTable) ; level.setTimeTable(timeTable); levelRepository.save(level); return timeTable; } @Override public Prof addTtableToUser(MultipartFile multipartFile, String idProf, String title, String desc) { File file= fileSytemStorage.saveFile(multipartFile); Prof prof=null; Optional<Prof>prof1=profRepository.findById(Long.valueOf(idProf)); prof=prof1.get(); TimeTable timeTable=new TimeTable() ; timeTable.setTitle(title); timeTable.setDesc(desc); timeTable.setFile(file); timeTable= tableRepository.save(timeTable) ; prof.setTimeTable(timeTable); profRepository.save(prof); return prof; } @Override public void delTtable(Long id) { tableRepository.deleteById(id); Optional<Level> level= levelRepository.findByTimeTableId(id); long x=level.get().getTimeTable().getId(); level.get().setTimeTable(null); Level Llevel=level.get(); levelRepository.save(Llevel); } @Override public TimeTable getTtable(Long id) { return null; } @Override public String OwnerTtable(Long id) { String type=""; Optional<Prof>prof=profRepository.findByTimeTableId(id); Optional<Level>level=levelRepository.findByTimeTableId(id); if (prof.isPresent()){ type="ENSEIGNANT"; } if (level.isPresent()){ type="CLASSE"; } return type; } }
true
ea4331dfd0f86483ed44572009e91e1a1cbf8bee
Java
gnaderi/interview-repository
/src/main/java/com/clarusone/poker/DefaultHandParserImpl.java
UTF-8
1,239
3.40625
3
[]
no_license
package com.clarusone.poker; import com.clarusone.poker.exception.InvalidHandException; import com.clarusone.poker.exception.UnsupportedCardValueException; import com.clarusone.poker.exception.UnsupportedSuitTypeException; import java.util.ArrayList; import java.util.List; public class DefaultHandParserImpl implements HandParser { @Override public List<Card> parse(String stringOfCards) throws InvalidHandException { try { String[] rawCards = stringOfCards.split(" "); List<Card> hand = new ArrayList<>(); for (String rawCard : rawCards) { Card card = parseRawCardValue(rawCard); hand.add(card); } return hand; } catch (Exception exception) { throw new InvalidHandException("Unable to parse the hand."); } } private Card parseRawCardValue(String rawCard) throws UnsupportedSuitTypeException, UnsupportedCardValueException { CardRank cardRank = CardRank.forValue(rawCard.charAt(0)); CardValue cardValue = CardValue.forValue(rawCard.charAt(0)); SuitType suitType = SuitType.forValue(rawCard.charAt(1)); return new Card(suitType, cardValue, cardRank); } }
true
7c41b4dd869f6461b8d55b06ad5e812321a61520
Java
georgehoss/proyecto1
/app/src/main/java/com/tenneco/tennecoapp/Adapter/EmailAdapter.java
UTF-8
2,546
2.390625
2
[]
no_license
package com.tenneco.tennecoapp.Adapter; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.tenneco.tennecoapp.Model.Email; import com.tenneco.tennecoapp.R; import java.util.ArrayList; import java.util.Collections; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by ghoss on 26/09/2018. */ public class EmailAdapter extends RecyclerView.Adapter<EmailAdapter.EmailViewHolder> { private ArrayList<Email> emails; private OnEmailInteraction onEmailInteraction; public EmailAdapter(ArrayList<Email> emails, OnEmailInteraction onEmailInteraction) { if (emails!=null) Collections.sort(emails,Email.NameComparator); this.emails = emails; this.onEmailInteraction = onEmailInteraction; } @NonNull @Override public EmailViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.email_row,parent,false); return new EmailViewHolder(view); } @Override public void onBindViewHolder(@NonNull EmailViewHolder holder, int position) { final Email email = emails.get(position); if (email!=null) { holder.mTvName.setText(email.getName()); holder.mTvInfo.setText(email.getEmail()); holder.mLlEmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onEmailInteraction.EditEmail(email); } }); } } @Override public int getItemCount() { if (emails!=null && emails.size()>0) return emails.size(); return 0; } public ArrayList<Email> getEmails() { return emails; } public void setEmails(ArrayList<Email> emails) { this.emails = emails; } class EmailViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.tv_name) TextView mTvName; @BindView(R.id.tv_info) TextView mTvInfo; @BindView(R.id.ll_email) LinearLayout mLlEmail; EmailViewHolder(@NonNull View itemView) { super(itemView); ButterKnife.bind(this,itemView); } } public interface OnEmailInteraction{ void EditEmail(Email email); } }
true
5b99f97f54edb32c1f650813a5bfa2e3407def49
Java
hubuwx/Learning-app
/app/src/main/java/com/learning_app/user/chathamkulam/PaymentGateway/StatusActivity.java
UTF-8
4,063
2.171875
2
[]
no_license
package com.learning_app.user.chathamkulam.PaymentGateway; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.learning_app.user.chathamkulam.R; import com.learning_app.user.chathamkulam.Sqlite.CheckingCards; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import static com.learning_app.user.chathamkulam.Model.TestUrls.TEST_PAYMENT; public class StatusActivity extends Activity { CheckingCards checkingCards; StringBuilder stringSemester; StringBuilder stringSubject; StringBuilder stringSubjectNumber; StringBuilder stringSubjectId; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.activity_status); checkingCards = new CheckingCards(this); Intent mainIntent = getIntent(); TextView txtStatus = (TextView) findViewById(R.id.txtStatus); final String status = mainIntent.getStringExtra("transStatus"); txtStatus.setText(status); if (status.equals("Transaction Successful!")){ Cursor cursor = checkingCards.getCheckData(); if (cursor.getCount() != 0){ stringSemester = new StringBuilder(); stringSubject = new StringBuilder(); stringSubjectNumber = new StringBuilder(); stringSubjectId = new StringBuilder(); ArrayList<String> amountList = new ArrayList<String>(); while (cursor.moveToNext()) { String semester = cursor.getString(5); String subject = cursor.getString(6); String subjectId = cursor.getString(7); String subjectNumber = cursor.getString(8); String amount = cursor.getString(9); Log.d("statusData",semester+" "+subject+" "+subjectId+" "+subjectNumber+" "+amount); stringSemester.append(semester).append(", "); stringSubject.append(subject).append(", "); stringSubjectId.append(subjectId).append(", "); stringSubjectNumber.append(subjectNumber).append(", "); amountList.add(amount+1); } cursor.close(); int totalAmount = 0; for (int i = 0; i < amountList.size(); i++) { totalAmount += Integer.parseInt(amountList.get(i)); } String subjectName = stringSubject.substring(0, stringSubject.length() - 2); Log.d("concatValue",subjectName+" "+totalAmount); RequestQueue requestQueue = Volley.newRequestQueue(this); final ProgressDialog loading = ProgressDialog.show(StatusActivity.this, "Checking", "Please wait your detail will be check", false,false); StringRequest stringRequest = new StringRequest(Request.Method.POST,TEST_PAYMENT,new Response.Listener<String>() { @Override public void onResponse(String response) { loading.dismiss(); Log.d("Response",response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { loading.dismiss(); Log.d("Response",error.getMessage()); } }){ @Override protected Map<String,String> getParams(){ Map<String,String> Hashmap = new HashMap<String, String>(); String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); Hashmap.put("date",date); Hashmap.put("sem_no", String.valueOf(stringSemester)); Hashmap.put("subject_id",String.valueOf(stringSubjectId)); Hashmap.put("sub_no",String.valueOf(stringSubjectNumber)); Hashmap.put("status",status); Log.d("mappingValue",Hashmap.toString()); return Hashmap; } }; requestQueue.add(stringRequest); } } } public void showToast(String msg) { Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show(); } }
true
35216317040d51372c92d5528564957e34e585b2
Java
StarkLyu/OnlineEdu-SE.Sum.Proj
/code/backend/online-edu/src/test/java/com/se231/onlineedu/Service/PaperServiceImplTest.java
UTF-8
8,507
2.265625
2
[]
no_license
package com.se231.onlineedu.Service; import static org.mockito.ArgumentMatchers.any; import static org.assertj.core.api.Assertions.assertThat; import java.util.Calendar; import java.util.List; import java.util.Optional; import com.se231.onlineedu.exception.NotFoundException; import com.se231.onlineedu.exception.NotMatchException; import com.se231.onlineedu.message.request.PaperForm; import com.se231.onlineedu.message.request.PaperQuestionForm; import com.se231.onlineedu.message.response.PaperFinish; import com.se231.onlineedu.model.*; import com.se231.onlineedu.repository.*; import com.se231.onlineedu.service.CourseService; import com.se231.onlineedu.service.PaperService; import com.se231.onlineedu.serviceimpl.PaperServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; /** * @author Zhe Li * @date 2019/07/31 */ @RunWith(SpringRunner.class) public class PaperServiceImplTest { @TestConfiguration static class PaperServiceImplTestContextConfig{ @Bean public PaperService paperService(){ return new PaperServiceImpl(); } } @Autowired PaperService paperService; @MockBean private PaperWithQuestionsRepository paperWithQuestionsRepository; @MockBean private QuestionRepository questionRepository; @MockBean private PaperRepository paperRepository; @MockBean private CourseService courseService; @MockBean private UserRepository userRepository; @MockBean private PaperAnswerRepository paperAnswerRepository; private static Paper paper; private static Question question; private static Course course; private static User user; @Before public void init(){ paper = new Paper(); paper.setId(1L); course = new Course(); course.setId(1L); paper.setCourse(course); question = new Question(); question.setId(1L); question.setQuestionType(QuestionType.SINGLE_ANSWER); question.setQuestion("shit\0\r"); user = new User(); user.setId(1L); } @Test public void addNewPaperTest() throws Exception{ //initialize paper info PaperQuestionForm paperQuestionForm = new PaperQuestionForm(); paperQuestionForm.setQuestionId(1L); paperQuestionForm.setQuestionNumber(1); paperQuestionForm.setScore(1); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE,5); PaperForm paperForm = new PaperForm(); paperForm.setQuestionFormList(List.of(paperQuestionForm)); paperForm.setStart(calendar.getTime()); calendar.add(Calendar.DATE,5); paperForm.setEnd(calendar.getTime()); paperForm.setTitle("test"); // mockito Mockito.when(paperRepository.save(any(Paper.class))).thenAnswer(i -> i.getArguments()[0]); Mockito.when(courseService.getCourseInfo(1L)).thenReturn(course); Mockito.when(questionRepository.findById(1L)).thenReturn(Optional.of(question)); Mockito.when(paperWithQuestionsRepository.save(any(PaperWithQuestions.class))).thenAnswer(i -> i.getArguments()[0]); Paper paper2 = paperService.addNewPaper(paperForm,1L); assertThat(paper2.getQuestionList().get(0)).isEqualTo(question); } @Test(expected = NotFoundException.class) public void addPaperNotFound() throws Exception{ Mockito.when(paperRepository.save(any(Paper.class))).thenAnswer(i -> i.getArguments()[0]); PaperQuestionForm paperQuestionForm = new PaperQuestionForm(); paperQuestionForm.setQuestionId(2L); paperQuestionForm.setQuestionNumber(1); paperQuestionForm.setScore(1); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE,5); PaperForm paperForm = new PaperForm(); paperForm.setQuestionFormList(List.of(paperQuestionForm)); paperForm.setStart(calendar.getTime()); calendar.add(Calendar.DATE,5); paperForm.setEnd(calendar.getTime()); paperForm.setTitle("test"); Mockito.when(paperRepository.save(any(Paper.class))).thenAnswer(i -> i.getArguments()[0]); Mockito.when(courseService.getCourseInfo(1L)).thenReturn(course); Mockito.when(questionRepository.findById(1L)).thenReturn(Optional.empty()); paperService.addNewPaper(paperForm,1L); } @Test(expected = NotFoundException.class) public void paperNotFound1(){ course.setPapers(List.of(paper)); Mockito.when(courseService.getCourseInfo(1L)).thenReturn(course); Mockito.when(paperRepository.findById(1L)).thenReturn(Optional.empty()); paperService.getPaperFinish(1L,1L); } @Test public void notStartTest(){ course.setPapers(List.of(paper)); Mockito.when(paperRepository.findById(1L)).thenReturn(Optional.of(paper)); Mockito.when(courseService.getCourseInfo(1L)).thenReturn(course); Mockito.when(userRepository.getOne(1L)).thenReturn(user); Mockito.when(paperAnswerRepository.getMaxTimes(1L,1L)).thenReturn(Optional.empty()); List<PaperFinish> paperFinish = paperService.getPaperFinish(1L,1L); assertThat(paperFinish.get(0).getState()).isEqualTo(PaperAnswerState.NOT_START); } @Test public void getPaperFinishTest(){ course.setPapers(List.of(paper)); Mockito.when(paperRepository.findById(1L)).thenReturn(Optional.of(paper)); Mockito.when(courseService.getCourseInfo(1L)).thenReturn(course); Mockito.when(userRepository.getOne(1L)).thenReturn(user); Mockito.when(paperAnswerRepository.getMaxTimes(1L,1L)).thenReturn(Optional.of(2)); PaperAnswerPrimaryKey paperAnswerPrimaryKey = new PaperAnswerPrimaryKey(user,paper,2); PaperAnswer paperAnswer = new PaperAnswer(); paperAnswer.setPaperAnswerPrimaryKey(paperAnswerPrimaryKey); paperAnswer.setState(PaperAnswerState.TEMP_SAVE); Mockito.when(paperAnswerRepository.getOne(paperAnswerPrimaryKey)).thenReturn(paperAnswer); List<PaperFinish> paperFinish = paperService.getPaperFinish(1L,1L); assertThat(paperFinish.get(0).getState()).isEqualTo(PaperAnswerState.TEMP_SAVE); assertThat(paperFinish.get(0).getTimes()).isEqualTo(2); } @Test(expected = NotFoundException.class) public void paperNotFound2(){ Mockito.when(courseService.getCourseInfo(1L)).thenReturn(course); Mockito.when(paperRepository.findById(1L)).thenReturn(Optional.empty()); paperService.getStudentFinish(1L,1L); } @Test(expected = NotMatchException.class) public void notMatchTest(){ Mockito.when(courseService.getCourseInfo(1L)).thenReturn(course); Paper paper2 = new Paper(); Course course2 = new Course(); course2.setId(2L); paper2.setCourse(course2); Mockito.when(paperRepository.findById(2L)).thenReturn(Optional.of(paper2)); paperService.getStudentFinish(1L,2L); } @Test public void getStudentFinishTest(){ course.setPapers(List.of(paper)); Learn learn = new Learn(user,course); course.setLearns(List.of(learn)); Mockito.when(paperRepository.findById(1L)).thenReturn(Optional.of(paper)); Mockito.when(courseService.getCourseInfo(1L)).thenReturn(course); Mockito.when(userRepository.getOne(1L)).thenReturn(user); Mockito.when(paperAnswerRepository.getMaxTimes(1L,1L)).thenReturn(Optional.of(2)); PaperAnswerPrimaryKey paperAnswerPrimaryKey = new PaperAnswerPrimaryKey(user,paper,2); PaperAnswer paperAnswer = new PaperAnswer(); paperAnswer.setPaperAnswerPrimaryKey(paperAnswerPrimaryKey); paperAnswer.setState(PaperAnswerState.TEMP_SAVE); Mockito.when(paperAnswerRepository.getOne(paperAnswerPrimaryKey)).thenReturn(paperAnswer); List<PaperFinish> paperFinish = paperService.getStudentFinish(1L,1L); assertThat(paperFinish.get(0).getState()).isEqualTo(PaperAnswerState.TEMP_SAVE); assertThat(paperFinish.get(0).getTimes()).isEqualTo(2); } }
true
3afacaad033473d07351a5c69b3055d94fa7d998
Java
rromaya/cardballcolor
/app/src/main/java/com/cardsball/colors/BackCalculating.java
UTF-8
4,670
2.828125
3
[]
no_license
package com.cardsball.colors; /** * Created by daviduch on 4/01/2019. */ import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import java.util.LinkedList; import java.util.List; import java.util.Random; class BackCalculating { private int maximumX; private int maximumY; private Paint paint; List<MoveBall> mBalls; static int[] myGreatArr = {Color.BLUE, Color.GREEN, Color.RED, Color.YELLOW, Color.LTGRAY}; private final int BALL_NUM = 50; private ScrBoard scrBoard; PatternBoard patternBoard; static boolean isPattern = true; BackCalculating(int xMin, int minimumY, int xMax, int maximumY, int colorIn, int colorOut) { this.maximumX = xMax; this.maximumY = maximumY; paint = new Paint(); paint.setColor(colorIn); // paint style and custom Paint paintingOut = new Paint(); paintingOut.setColor(colorOut); mBalls = new LinkedList<MoveBall>(); initMBalls(this.BALL_NUM); scrBoard = new ScrBoard(10); patternBoard = new PatternBoard(7); } private void pushBalls() { for (MoveBall mB : this.mBalls) { mB.moveWithCollisionDetection(this); } } void draw(Canvas canvas, DisplayArea disp, CentralBall cball) { // Draw the board canvas.drawRect(0, 0, disp.xMax, disp.yMax, paint); // JP: cancle collision // float dLeft = disp.maximumX / 2 - cball.ballX; // float dRight = disp.maximumX / 2 - (this.maximumX - cball.ballX); // float dTop = disp.maximumY / 2 - cball.ballY; // float dBottom = disp.maximumY / 2 - (this.maximumY - cball.ballY); // if (dLeft > 0) { // canvas.drawRect(0, 0, dLeft, disp.maximumY, paintingOut); // } // if (dRight > 0) { // canvas.drawRect(disp.maximumX - dRight, 0, disp.maximumX, disp.maximumY, paintingOut); // } // if (dTop > 0) { // canvas.drawRect(0, 0, disp.maximumX, dTop, paintingOut); // } // if (dBottom > 0) { // canvas.drawRect(0, disp.maximumY - dBottom, disp.maximumX, disp.maximumY, paintingOut); // } // Draw central ball cball.draw(canvas, disp); // Collision detection. cball.collisionDetection(this, scrBoard); // Update the position of the ball, including collision detection and reaction. cball.moveWithCollisionDetection(this); // Draw other balls. for (MoveBall ball : mBalls) { ball.updateLocation(disp, cball); ball.draw(canvas, disp, cball); } // Update ball positions pushBalls(); if (isPattern) patternBoard.drawPatternBoard(canvas); scrBoard.drawScoreBoard(canvas); addOneBall(disp, cball); } private void initMBalls(int numOfBalls) { Random randomGenerator = new Random(); for (int i = 0; i < numOfBalls; i++) { float x = randomGenerator.nextInt(this.maximumX) + randomGenerator.nextFloat(); if (x > maximumX) x -= 1; float y = randomGenerator.nextInt(this.maximumY) + randomGenerator.nextFloat(); if (y > maximumY) y -= 1; float radius = 20; int color = myGreatArr[randomGenerator.nextInt(myGreatArr.length)]; float dx = randomGenerator.nextFloat() - (float)0.5; float dy = randomGenerator.nextFloat() - (float)0.5; MoveBall mB = new MoveBall(x, y, radius, color, 5, dx, dy); this.mBalls.add(mB); } } private void addOneBall(DisplayArea disp, CentralBall cBall) { if (this.mBalls.size() < this.BALL_NUM) { Random randomGenerator = new Random(); float x = randomGenerator.nextInt(this.maximumX) + randomGenerator.nextFloat(); if (x > maximumX) x -= 1; float y = randomGenerator.nextInt(this.maximumY) + randomGenerator.nextFloat(); if (y > maximumY) y -= 1; // avoid putting new ball near central ball if (Math.abs(cBall.ballX - x) < (disp.xMax / 2)) x = cBall.ballX - (disp.xMax / 2); if (Math.abs(cBall.ballY - y) < (disp.yMax / 2)) y = cBall.ballY - (disp.yMax / 2); float radius = 20; int color = myGreatArr[randomGenerator.nextInt(myGreatArr.length)]; float dx = randomGenerator.nextFloat() - (float)0.5; float dy = randomGenerator.nextFloat() - (float)0.5; MoveBall mB = new MoveBall(x, y, radius, color, 5, dx, dy); this.mBalls.add(mB); } } }
true
bd0127c34ac238069602314c520e005038c292ed
Java
ExtaSoft/extacrm
/src/main/java/ru/extas/web/product/ProdCredPercentField.java
UTF-8
6,420
2.203125
2
[ "Apache-2.0" ]
permissive
package ru.extas.web.product; import com.vaadin.data.Property; import com.vaadin.data.Validator; import com.vaadin.data.util.BeanItem; import com.vaadin.ui.Component; import com.vaadin.ui.GridLayout; import com.vaadin.ui.MenuBar; import com.vaadin.ui.Table; import ru.extas.model.product.ProdCredit; import ru.extas.model.product.ProdCreditPercent; import ru.extas.web.commons.ExtaTheme; import ru.extas.web.commons.Fontello; import ru.extas.web.commons.FormUtils; import ru.extas.web.commons.component.ExtaCustomField; import ru.extas.web.commons.container.ExtaBeanContainer; import ru.extas.web.commons.converters.StringToPercentConverter; import java.util.ArrayList; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static ru.extas.server.ServiceLocator.lookup; /** * Поле редактирования процентных ставок в кредитном продукте * * @author Valery Orlov * Date: 07.02.14 * Time: 15:28 * @version $Id: $Id * @since 0.3 */ public class ProdCredPercentField extends ExtaCustomField<List> { private final ProdCredit product; private Table procentTable; private ExtaBeanContainer<ProdCreditPercent> container; /** * <p>Constructor for ProdCredPercentField.</p> * * @param caption a {@link java.lang.String} object. * @param description a {@link java.lang.String} object. * @param product a {@link ProdCredit} object. */ public ProdCredPercentField(final String caption, final String description, final ProdCredit product) { super(caption, description); this.product = product; setWidth(100, Unit.PERCENTAGE); setHeight(200, Unit.PIXELS); } /** * {@inheritDoc} */ @Override protected Component initContent() { final GridLayout panel = new GridLayout(1, 2); panel.setSizeFull(); panel.setRowExpandRatio(1, 1); panel.setMargin(true); if (!isReadOnly()) { panel.setSpacing(true); final MenuBar commandBar = new MenuBar(); commandBar.setAutoOpen(true); commandBar.addStyleName(ExtaTheme.GRID_TOOLBAR); commandBar.addStyleName(ExtaTheme.MENUBAR_BORDERLESS); final MenuBar.MenuItem addProdBtn = commandBar.addItem("Добавить", event -> { final ProdCreditPercent newObj = new ProdCreditPercent(product); final ProdCreditPercentForm editWin = new ProdCreditPercentForm("Новая процентная ставка", newObj); editWin.setModified(true); editWin.addCloseFormListener(event1 -> { if (editWin.isSaved()) { container.addBean(newObj); } }); FormUtils.showModalWin(editWin); }); addProdBtn.setDescription("Добавить процентную стаквку в продукт"); addProdBtn.setIcon(Fontello.DOC_NEW); final MenuBar.MenuItem edtProdBtn = commandBar.addItem("Изменить", event -> { if (procentTable.getValue() != null) { final BeanItem<ProdCreditPercent> percentItem = (BeanItem<ProdCreditPercent>) procentTable.getItem(procentTable.getValue()); final ProdCreditPercentForm editWin = new ProdCreditPercentForm("Редактирование процентной ставки", percentItem.getBean()); editWin.addCloseFormListener(event1 -> { if (editWin.isSaved()) { fireValueChange(false); } }); FormUtils.showModalWin(editWin); } }); edtProdBtn.setDescription("Изменить выделенную в списке процентную ставку"); edtProdBtn.setIcon(Fontello.EDIT_3); final MenuBar.MenuItem delProdBtn = commandBar.addItem("Удалить", event -> { if (procentTable.getValue() != null) { procentTable.removeItem(procentTable.getValue()); } }); delProdBtn.setDescription("Удалить процентную ставку из продукта"); delProdBtn.setIcon(Fontello.TRASH); panel.addComponent(commandBar); } procentTable = new Table(); procentTable.setSizeFull(); procentTable.addStyleName(ExtaTheme.TABLE_SMALL); procentTable.addStyleName(ExtaTheme.TABLE_COMPACT); procentTable.setRequired(true); procentTable.setSelectable(true); final Property dataSource = getPropertyDataSource(); final List<ProdCreditPercent> percentList = dataSource != null ? (List<ProdCreditPercent>) dataSource.getValue() : new ArrayList<ProdCreditPercent>(); container = new ExtaBeanContainer<>(ProdCreditPercent.class); if (percentList != null) { for (final ProdCreditPercent percent : percentList) { container.addBean(percent); } } procentTable.setContainerDataSource(container); procentTable.addItemSetChangeListener(event -> setValue(newArrayList(procentTable.getItemIds()))); // Колонки таблицы procentTable.setVisibleColumns("percent", "period", "downpayment"); procentTable.setColumnHeader("percent", "Процент"); procentTable.setConverter("percent", lookup(StringToPercentConverter.class)); procentTable.setColumnHeader("period", "Срок"); procentTable.setColumnHeader("downpayment", "Первоначальный взнос"); procentTable.setConverter("downpayment", lookup(StringToPercentConverter.class)); panel.addComponent(procentTable); return panel; } /** * {@inheritDoc} */ @Override public void commit() throws SourceException, Validator.InvalidValueException { super.commit(); final Property dataSource = getPropertyDataSource(); if (dataSource != null) dataSource.setValue(container.getItemIds()); } /** * {@inheritDoc} */ @Override public Class<? extends List> getType() { return List.class; } }
true
3736965172a093d9b537001f7a2d1ff121304980
Java
sungwony0906/CouponService
/src/test/java/com/sungwony/coupon/springboot/domain/user/UserRepositoryTest.java
UTF-8
1,032
2.234375
2
[]
no_license
package com.sungwony.coupon.springboot.domain.user; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest public class UserRepositoryTest { @Autowired UserRepository userRepository; @Test public void 유저생성(){ //given User user = User.builder() .userId("dummyId") .name("dummy") .password("dummyPw") .email("dummy@gmail.com") .build(); user = userRepository.save(user); //when User findUser = userRepository.findByUserId("dummyId").orElse(null); //then assertThat(user.getId()).isEqualTo(findUser.getId()); assertThat(user.getName()).isEqualTo(findUser.getName()); } }
true
ef79ebd7920060acdfa0190f8e50089f26cdeae6
Java
Alec-WAM/CrystalMod
/src/main/java/alec_wam/CrystalMod/items/tools/ItemMegaCrystalPickaxe.java
UTF-8
2,505
2.15625
2
[ "MIT" ]
permissive
package alec_wam.CrystalMod.items.tools; import java.util.Map; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import alec_wam.CrystalMod.api.tools.IMegaTool; import alec_wam.CrystalMod.util.BlockUtil; import alec_wam.CrystalMod.util.ItemNBTHelper; import alec_wam.CrystalMod.util.tool.ToolUtil; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ItemMegaCrystalPickaxe extends ItemCrystalPickaxe implements IMegaTool { public ItemMegaCrystalPickaxe(ToolMaterial material) { super(material, "megacrystalpick"); setNoRepair(); } @Override public boolean onBlockStartBreak(ItemStack itemstack, BlockPos pos, EntityPlayer player) { for(BlockPos extraPos : getAOEBlocks(itemstack, player.getEntityWorld(), player, pos)) { BlockUtil.breakExtraBlock(itemstack, player.getEntityWorld(), player, extraPos, pos); } return super.onBlockStartBreak(itemstack, pos, player); } @Override @SideOnly(Side.CLIENT) public void initModel() { final Map<String, ModelResourceLocation> models = Maps.newHashMap(); for(String color : new String[]{"blue", "red", "green", "dark", "pure"}){ ModelResourceLocation loc = new ModelResourceLocation("crystalmod:tool/megapick", "color="+color); models.put(color, loc); ModelBakery.registerItemVariants(this, loc); } ModelLoader.setCustomMeshDefinition(this, new ItemMeshDefinition() { @Override public ModelResourceLocation getModelLocation(ItemStack stack) { String color = ItemNBTHelper.getString(stack, "Color", ""); return models.get(color); } }); } @Override public ImmutableList<BlockPos> getAOEBlocks(ItemStack tool, World world, EntityPlayer player, BlockPos pos) { return ToolUtil.calcAOEBlocks(tool, world, player, pos, 3, 3, 1); } @Override public int getMaxDamage(ItemStack stack) { //Triple the durability return super.getMaxDamage(stack) * 3; } }
true
7d820748e2e5f56ce06245928b433dfc9bfcc7a5
Java
unnKoel/condtion-goal
/src/main/java/com/wind/goal/dao/po/UserCondition.java
UTF-8
1,010
2.03125
2
[]
no_license
package com.wind.goal.dao.po; import java.io.Serializable; /** * 用户条件 * * @author zhouyanjun * @version 1.0 2015-1-16 */ public class UserCondition implements Serializable { private static final long serialVersionUID = -6397232151124702265L; private Integer userId; private Integer conditionId; private String conditionValue; public UserCondition() {} public UserCondition(Integer userId, Integer conditionId, String conditionValue) { super(); this.userId = userId; this.conditionId = conditionId; this.conditionValue = conditionValue; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getConditionId() { return conditionId; } public void setConditionId(Integer conditionId) { this.conditionId = conditionId; } public String getConditionValue() { return conditionValue; } public void setConditionValue(String conditionValue) { this.conditionValue = conditionValue; } }
true
596b467d6b870d61813ec1a86d285bbe59f727e0
Java
mihristov/HackBulgaria-assingments
/Collections1/RotateElements/RotateElements.java
UTF-8
643
3.3125
3
[]
no_license
import java.util.ArrayList; public class RotateElements { public void rotate(ArrayList<Integer> collection, int rotateStep) { if (rotateStep > 0) { for (int i = 0; i < rotateStep; i++) { Integer toAdd = collection.get(collection.size() - 1); collection.add(0, toAdd); collection.remove(collection.size() - 1); } } else { for (int i = rotateStep; i < 0; i++){ Integer toAdd = collection.get(0); collection.add(collection.size(), toAdd); collection.remove(0); } } } }
true
6ad068c5d1556e2182d4c122403f0ce9b108d16d
Java
ArturMaiaP/API-Rest-SpringBoot-Bank
/src/main/java/br/com/task/bank/model/User.java
UTF-8
956
2.765625
3
[]
no_license
package br.com.task.bank.model; /** * * * @author Artur Maia Pereira * @version 1.0 - 05/10/2020 */ public class User { private String name; private String cpf; public User(String name, String cpf) { this.name = name; this.cpf = cpf; } public String getCpf() { return this.cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cpf == null) ? 0 : cpf.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof User)) { return false; } User other = (User) obj; if (cpf == null) { if (other.cpf != null) { return false; } } else if (!cpf.equals(other.cpf)) { return false; } return true; } }
true
3a3f54dbf85a0ddbb09c2706fa9a7e363d3f131a
Java
LucRyan/Healthcare-Delivery-System
/src/Final/Ryan/Location/HistoryPatient.java
UTF-8
7,669
2.015625
2
[]
no_license
package Final.Ryan.Location; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import Final.Ryan.R; import Final.Ryan.Patient.Patient; import Final.Ryan.Patient.PatientDbAdapter; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class HistoryPatient extends Activity implements OnItemClickListener{ //Start from here is the variables used in the application private static final String DATABASE_TABLE_SEE = "ToBeSee"; private static final String DATABASE_TABLE_HISTORY = "History"; static final private String TAG = "PatientsInfo"; static final private String emailOfSender = "luckin89@gmail.com"; static final private int MENU_CHRON = Menu.FIRST; static final private int MENU_ALPHB = Menu.FIRST + 1; public final static String ID = "_id"; public final static String PICTURE = "picture"; public final static String NAME = "name"; public final static String LATITUDE = "latitude"; public final static String LONGTITUDE = "longtitude"; ListView listView; Patient patient; ArrayList<Patient> patients = new ArrayList<Patient>(); private MyAdapter mSimpleAdapter; ArrayList<HashMap<String, Object>> al; PatientDbAdapter ptDbAdapter; long selectedFromList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("History Patient Infomation"); setContentView(R.layout.multiple_checkbox_main); listView = (ListView) findViewById(R.id.listview); ptDbAdapter = new PatientDbAdapter(this); ptDbAdapter.open(); fillData(DATABASE_TABLE_HISTORY); } private void fillData(String database_table) { // Get all of the books from the cart database Cursor myCursor = ptDbAdapter.fetchAllItems(database_table); startManagingCursor(myCursor); al = new ArrayList<HashMap<String,Object>>(); if(myCursor!=null){ myCursor.moveToFirst(); while(!myCursor.isAfterLast()){ HashMap<String, Object> map = new HashMap<String, Object>(); map.put( ID, myCursor.getString(0)); map.put( PICTURE, Integer.valueOf(myCursor.getString(1))); map.put( NAME, myCursor.getString(2)); map.put( LATITUDE, myCursor.getString(3)); map.put( LONGTITUDE, myCursor.getString(4)); al.add(map); myCursor.moveToNext(); } } String[] from = { PICTURE, NAME, LATITUDE, LONGTITUDE}; int[] to = { R.id.imageView1, R.id.textView1, R.id.textView2, R.id.textView3}; mSimpleAdapter = new MyAdapter(this, al, R.layout.mylistview_history, from, to); listView.setAdapter(mSimpleAdapter); listView.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox1); checkBox.toggle(); mSimpleAdapter.map.put(position, checkBox.isChecked()); Log.i(TAG, String.valueOf(position)); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_CHRON, 0, R.string.history_menu_chron); menu.add(0, MENU_ALPHB, 1, R.string.history_menu_alphb); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case (MENU_CHRON): fillData(DATABASE_TABLE_HISTORY); return true; case (MENU_ALPHB): sortAlphbetically(); return true; } return false; } public class MyAdapter extends SimpleAdapter { HashMap<Integer, Boolean> map; LayoutInflater mInflater; private List<HashMap<String, Object>> mList; public MyAdapter(Context context, List<HashMap<String, Object>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); map = new HashMap<Integer, Boolean>(); mInflater = LayoutInflater.from(context); mList = data; for(int i = 0; i < data.size(); i++) { map.put(i, false); } } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = mInflater.inflate(R.layout.mylistview_history, null); } ImageView im = (ImageView) convertView.findViewById(R.id.imageView1); im.setImageResource((Integer) mList.get(position).get(PICTURE)); TextView tN = (TextView) convertView.findViewById(R.id.textView1); tN.setText((String)mList.get(position).get(NAME)); TextView tLA = (TextView) convertView.findViewById(R.id.textView2); tLA.setText("Lat. " + (String)mList.get(position).get(LATITUDE)); TextView tLO = (TextView) convertView.findViewById(R.id.textView3); tLO.setText("Long. " + (String)mList.get(position).get(LONGTITUDE)); return convertView; } } private void sortAlphbetically(){ if (!al.isEmpty()) { Collections.sort(al, new Comparator<Map<String, Object>>() { @Override public int compare(Map<String, Object> object1, Map<String, Object> object2) { return object1.get(NAME).toString() .compareTo(object2.get(NAME).toString()); } }); } listView.setAdapter(mSimpleAdapter); } }
true
2d9c5c1e2ee51b6075a620699590713dc66cd57e
Java
madhusudhanraodumpa/DSAALGOBYMADHU
/src/com/org/learnby/dynamicprograming/palindrome/MinimumInsertionStepstoMakeaStringPalindrome.java
UTF-8
2,033
3.484375
3
[]
no_license
package com.org.learnby.dynamicprograming.palindrome; import java.util.Arrays; public class MinimumInsertionStepstoMakeaStringPalindrome { public static void main(String args[]) { System.out.println(minInsertionsDPModify("leetcode","leetcode".length())); } public static int minInsertions(String s) { int[][] dp = new int[s.length()][s.length()]; for (int i = 0; i < s.length(); i++) { for (int j = 0; j < s.length(); j++) { dp[i][j] = -1; } } return minInsertionsRec(s, 0, s.length() - 1, dp); } public static int minInsertionsRec(String s, int i, int j, int dp[][]) { if (i >= j) return 0; if(dp[i][j]!=-1) return dp[i][j]; if (s.charAt(i) == s.charAt(j)) { dp[i][j] = minInsertionsRec(s, i + 1, j - 1, dp); return dp[i][j]; } else { dp[i][j] = 1 + Math.min(minInsertionsRec(s, i + 1, j, dp), minInsertionsRec(s, i, j - 1, dp)); return dp[i][j]; } } public static int minInsertionsDP(String s, int n) { int[][] dp = new int[s.length()][s.length()]; int i; int j; for(int len=1;len<n;len++){ for(i=0,j=0 ;j<n;i++,j++){ dp[i][j]= (s.charAt(i)==s.charAt(j))?dp[i+1][j-1]:1+Math.min(dp[i+1][j],dp[i][j-1]); } } return dp[0][n-1]; } public static int minInsertionsDPModify(String s, int n) { int[][] dp = new int[s.length()][s.length()]; for(int len=2;len<=n;len++){ for(int i=0;i<n-len+1;i++){ int j = len+i-1; if(s.charAt(i) == s.charAt(j)){ dp[i][j] = dp[i+1][j-1]; }else{ if(len ==2){ dp[i][j] =1; }else { dp[i][j] = 1 + Math.min(dp[i + 1][j], dp[i][j - 1]); } } } } return dp[0][n-1]; } }
true
a2e392a7ce0ca9d19ca070db65fdb8e7da13f68e
Java
Parikshaprajapati/data-structure
/recursion/powerpuff.java
UTF-8
350
3.03125
3
[]
no_license
public class powerpuff{ public static void main(String[] args){ System.out.println(making(2,3,5,15,27,40)); } public static int making(int a,int b,int c,int A,int B,int C){ if(A==0||B==0||C==0) return 0; int count=0; if(A-a>=0&&B-b>=0&&C-c>=0) count=1+making(a,b,c,A-a,B-b,C-c); return count; } }
true
79e03065df3c52393458acd6ebeafdc5dd457163
Java
diegopacheco/java-pocs
/pocs/Fluent-Interface/src/com/blogspot/diegopacheco/fluent/interfacejava/domain/Desconto.java
UTF-8
283
2.3125
2
[ "Unlicense" ]
permissive
package com.blogspot.diegopacheco.fluent.interfacejava.domain; public class Desconto { private Integer porcetagem; public Desconto(Integer porcetagem) { super(); this.porcetagem = porcetagem; } public Integer getPorcetagem() { return porcetagem; } }
true
e3bc17a3fb14166e24c0c418cc74bf535cd4f685
Java
KubbyDev/OrbitalSimulator
/src/orbitalsimulator/graphics/ui/UI.java
UTF-8
1,572
3.265625
3
[]
no_license
package orbitalsimulator.graphics.ui; import orbitalsimulator.maths.vector.Vector2; import orbitalsimulator.physics.tools.Time; import orbitalsimulator.tools.Input; import orbitalsimulator.tools.KeyCode; import java.awt.*; import java.util.ArrayList; public class UI { public static ArrayList<Button> buttons = new ArrayList<>(); public static void init() { //Adds buttons to accelerate or decelerate time UI.buttons.add(new Button(50, 50, 45, 45, new Color(1.0f,1.0f,1.0f), () -> { Time.multiplier *= 0.5; System.out.println("/2"); })); UI.buttons.add(new Button(100, 50, 45, 45, new Color(1.0f,1.0f,1.0f), () -> { Time.multiplier *= 2; System.out.println("x2"); })); //Adds a events that call onLeftClick or onRightClick when the user presses a mouse button Input.addMouseEvent(KeyCode.MOUSE_LEFT, UI::onLeftClick); Input.addMouseEvent(KeyCode.MOUSE_RIGHT, UI::onRightClick); } public static void display() { for(Button button : buttons) button.display(); } private static void onLeftClick() { //Calls the callback of all the buttons inside of which the mouse is Vector2 mouse = Input.getMousePosition(); for(Button button : buttons) if(mouse.x() >= button.x && mouse.x() < button.x + button.width && mouse.y() >= button.y && mouse.y() < button.y + button.height) button.onClick.run(); } private static void onRightClick() { } }
true
48e77bc8726d12e60abc37bfacb747751a6dfb43
Java
seasarorg/test-ymir-component-1
/ymir-core/src/main/java/org/seasar/ymir/redirection/ScopeIdManager.java
UTF-8
1,708
2.71875
3
[]
no_license
package org.seasar.ymir.redirection; import org.seasar.ymir.Request; import org.seasar.ymir.Response; /** * RedirectionScopeのIDを管理するためのインタフェースです。 * <p><b>同期化:</b> * このインタフェースの実装クラスはスレッドセーフである必要があります。 * </p> * * @author YOKOTA Takehiko * @since 1.0.2 */ public interface ScopeIdManager { /** * 現在のリクエストのための値を取得するRedirectionScopeのIDを返します。 * <p>このメソッドが返すのは、次のリクエストに引き継ぐRedirectionScopeのIDではなく、 * 前のリクエストから引き継がれたRedirectionScopeのIDです。 * </p> * * @return 現在のリクエストのための値を取得するRedirectionScopeのID。 * RedirectionScopeが引き継がれていない場合はnullを返します。 */ String getScopeId(); /** * RedirectionScopeを引き継ぐためのIDをレスポンスに設定します。 * <p>このメソッドはレスポンスが確定してから呼び出されることが保証されていますので、 * このメソッド内でコンテナからResponseオブジェクトを取り出して状態を変更することができます。 * </p> * <p>IDをレスポンスに設定できない場合などはnullを返すようにして下さい。 * </p> * * @param scopeExists 引き継ぐべきRedirectionScopeが存在する(空でない)かどうか。 * @return レスポンスに設定したID。 */ String populateScopeId(boolean scopeExists); }
true
350b7487185aeaeba6a89b23a937a9613148764b
Java
galvezsergio19/obs
/src/main/java/com/smg/model/AtmModel.java
UTF-8
600
2.390625
2
[]
no_license
package com.smg.model; public class AtmModel { private long account_no; private long web_verify; /**** CONSTRUCTOR ****/ public AtmModel(){} public AtmModel(long account_no, long web_verify) { this.account_no = account_no; this.web_verify = web_verify; } /**** SETTER ****/ public void setAccount_no(long account_no) { this.account_no = account_no; } public void setWeb_verify(long web_verify) { this.web_verify = web_verify; } /**** GETTER ****/ public long getAccount_no() { return account_no; } public long getWeb_verify() { return web_verify; } }
true
713f184e4694500b58b8ecf553febb83827e04ca
Java
cleancode1116/OpenBP
/openbp-cockpit/src/main/java/org/openbp/guiclient/util/DisplayObjectTreeNode.java
UTF-8
2,971
2.5625
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
/* * Copyright 2007 skynamics AG * * 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.openbp.guiclient.util; import javax.swing.tree.TreeNode; import org.openbp.common.generic.description.DisplayObject; import org.openbp.guiclient.plugins.displayobject.DisplayObjectPlugin; import org.openbp.swing.components.tree.DefaultTreeNode; /** * General-purpose tree node that holds a reference to a display object. * The display text of the object will be used as tree node text. * * @author Heiko Erhardt */ public class DisplayObjectTreeNode extends DefaultTreeNode { ////////////////////////////////////////////////// // @@ Properties ////////////////////////////////////////////////// /** Display object represented by this node */ protected DisplayObject object; ////////////////////////////////////////////////// // @@ Construction ////////////////////////////////////////////////// /** * Default constructor. */ public DisplayObjectTreeNode() { } /** * Default constructor. * * @param object Display object represented by this node */ public DisplayObjectTreeNode(DisplayObject object) { this.object = object; } /** * Default constructor. * * @param parent Parent tree node */ public DisplayObjectTreeNode(TreeNode parent) { this.parent = parent; } /** * Default constructor. * * @param object Display object represented by this node * @param parent Parent tree node */ public DisplayObjectTreeNode(DisplayObject object, TreeNode parent) { this.object = object; this.parent = parent; } /** * Returns the string representation of this node. * According to the role manager, either the display text or the name of the item. * @nowarn */ public String toString() { if (object != null) { return DisplayObjectPlugin.getInstance().isTitleModeText() ? object.getDisplayText() : object.getName(); } return ""; } ////////////////////////////////////////////////// // @@ Property access ////////////////////////////////////////////////// /** * Gets the display object represented by this node. * @nowarn */ public DisplayObject getObject() { return object; } /** * Sets the display object represented by this node. * @nowarn */ public void setObject(DisplayObject object) { this.object = object; } }
true
f5232f172c3a4fcfd3f155ef6d84e9de289e194a
Java
alt236/thejsonappyouarelookingfor
/app/src/main/java/uk/co/alt236/thejsonappyouaskedfor/ui/components/home/HomeActivity.java
UTF-8
1,662
2.1875
2
[]
no_license
package uk.co.alt236.thejsonappyouaskedfor.ui.components.home; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import uk.co.alt236.thejsonappyouaskedfor.R; import uk.co.alt236.thejsonappyouaskedfor.ui.core.common.activity.BaseActivity; public class HomeActivity extends BaseActivity { private static final int LAYOUT_ID = R.layout.activity_default_fragment_container; private static final String FRAGMENT_TAG = HomeActivity.class.getSimpleName() + "_fragment_tag"; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(LAYOUT_ID); setTitle(getString(R.string.title_home_activity)); addContentFragmentIfMissing(HomeFragment.newInstance(), FRAGMENT_TAG); } @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.home_menu, menu); return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { // Handle action bar actions click final int itemId = item.getItemId(); final View view = findViewById(itemId); switch (itemId) { case R.id.action_open_dev_screen: getIntentDispatcher().openDevScreen(view); return true; default: return super.onOptionsItemSelected(item); } } public static Intent getInstance(final Context context) { return new Intent(context, HomeActivity.class); } }
true
73a221e7455578f59a6ee645bf1251b320e8a4a0
Java
himcs/bbgs
/common/src/main/java/top/himcs/bbgs/common/service/impl/RedisServiceImpl.java
UTF-8
1,060
2.359375
2
[]
no_license
package top.himcs.bbgs.common.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import top.himcs.bbgs.common.service.RedisService; import java.util.concurrent.TimeUnit; @Service public class RedisServiceImpl implements RedisService { @Autowired private RedisTemplate<String, Object> redisTemplate; @Override public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } @Override public Object get(String key) { return redisTemplate.opsForValue().get(key); } @Override public boolean expire(String key, long expire) { return redisTemplate.expire(key, expire, TimeUnit.SECONDS); } @Override public Boolean remove(String key) { return redisTemplate.delete(key); } @Override public Long increment(String key, long delta) { return redisTemplate.opsForValue().increment(key, delta); } }
true
0139b470a66750efee699e35eeadeaa9f8bdb7e5
Java
Tony-E-Boy/Ballance
/src/main/java/com/abs/testartifact/models/User.java
UTF-8
1,543
2.609375
3
[]
no_license
package com.abs.testartifact.models; import javax.persistence.*; @Entity @Table(name = "user") public class User { private static Long USER_NUMBER; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "Id") private Long id; @Column(name = "name") private String name; @Column(name = "email") private String email; @Column(name = "hex") private String hex; public User(Long id, String name, String email, String hex) { this.id = id; this.name = name; this.email = email; this.hex = hex; } public User(){} public void save(User user){ user.setId(++USER_NUMBER); user.setEmail(email); user.setName(name); user.setHex(hex); } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", email='" + email + '\'' + ", hex='" + hex + '\'' + '}'; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getHex() { return hex; } public void setHex(String hex) { this.hex = hex; } }
true
0a4fb8146e46457ef85a06ad0b744144e27aab07
Java
kzbigboss/bellevuecollege_201804_cs210_java1
/Submitted Assignments/Chapter3G.java
UTF-8
779
3.640625
4
[]
no_license
// CS210 Quiz, your name: Mark Kazzaz import java.awt.*; public class Chapter3G { public static void main(String[] args) { showOrbital(600, 200); } public static void showOrbital(int x, int y) { // create panel, set red DrawingPanel panel = new DrawingPanel(x, y); panel.setBackground(Color.RED); Graphics g = panel.getGraphics(); // loop to draw circles for (int i = 1; i <= 4; i++) { // alternate colors between black and white if (i % 2 == 0) { g.setColor(Color.WHITE); } else { g.setColor(Color.BLACK); } g.fillOval (20 + (x / 12) * i, 20 + (y / 12) * i, x - 20 - (x / 12) * 2 * i, y - 20 - (y / 12) * 2 * i); } } // required method follows... }
true
1c03726bc8f324b4822386c75200d1ca602e232b
Java
Archemedes/protocolize
/protocolize-world/src/main/java/de/exceptionflug/protocolize/world/SoundMapping.java
UTF-8
724
2.640625
3
[]
no_license
package de.exceptionflug.protocolize.world; public class SoundMapping { private final int protocolVersionRangeStart, protocolVersionRangeEnd; private final String soundName; public SoundMapping(int protocolVersionRangeStart, int protocolVersionRangeEnd, String soundName) { this.protocolVersionRangeStart = protocolVersionRangeStart; this.protocolVersionRangeEnd = protocolVersionRangeEnd; this.soundName = soundName; } public int getProtocolVersionRangeStart() { return protocolVersionRangeStart; } public int getProtocolVersionRangeEnd() { return protocolVersionRangeEnd; } public String getSoundName() { return soundName; } }
true
bd2d36ba80cc8cca85a409d1534b9c9ef692605c
Java
jesushl/SIGA
/SIGApp/src/SIGAMARKS2/Marks/Finders/ApplicationMarks.java
UTF-8
1,645
2.3125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package SIGAMARKS2.Marks.Finders; import java.util.List; import mx.unam.patronato.auditoria.siga.core.daoimpl.MarcaDAOImpl; import mx.unam.patronato.auditoria.siga.core.daoimpl.Marca_DocumentoDAOImpl; import mx.unam.patronato.auditoria.siga.core.model.Documento; import mx.unam.patronato.auditoria.siga.core.model.MarcaDocumento; /** * * @author J3SU5 Herrera Ledón */ public class ApplicationMarks { private List<MarcaDocumento> marksOnDocument; public ApplicationMarks() { } /** * * @param idDocumento * @param numPag * @return */ public static List <MarcaDocumento> getListOfMarksForDocumentPage(Documento idDocumento, int numPag){ ApplicationMarks gpmObj = new ApplicationMarks(); gpmObj.setMarksOnDocument(Marca_DocumentoDAOImpl.getInstance().select(idDocumento, numPag)); return gpmObj.getMarksOnDocument(); } /** * regresa el nombre de la marca a travez de idMarca * @param idMarca * idMarca obtenida en Marca_Documento * @return * String de nombre marca */ public static String getMarkName(int idMarca){ return MarcaDAOImpl.getInstance().select(idMarca).getNombreMarca(); } public List<MarcaDocumento> getMarksOnDocument() { return marksOnDocument; } public void setMarksOnDocument(List<MarcaDocumento> marksOnDocument) { this.marksOnDocument = marksOnDocument; } }
true
8b93b6bc73464e020d07319ed241dcab2df3886a
Java
BISAECG/BisaNewHome
/bisa-shop-CN-service/src/main/java/com/bisa/health/shop/service/HtmlInfoServiceImpl.java
UTF-8
1,515
2.03125
2
[]
no_license
package com.bisa.health.shop.service; import com.bisa.health.basic.entity.Pager; import com.bisa.health.basic.entity.SystemContext; import com.bisa.health.shop.dao.IHtmlInfoDao; import com.bisa.health.shop.model.HtmlInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.stereotype.Service; import java.util.List; @Service @CacheConfig(cacheNames = "HtmlInfoServiceImpl") public class HtmlInfoServiceImpl implements IHtmlInfoService{ @Autowired private IHtmlInfoDao iAdminHtmlInfoDao; @Override public HtmlInfo addHtmlInfo(HtmlInfo htmlInfo) { return iAdminHtmlInfoDao.addHtmlInfo(htmlInfo); } @Override public HtmlInfo updateHtmlInfo(HtmlInfo htmlInfo) { return iAdminHtmlInfoDao.updateHtmlInfo(htmlInfo); } @Override public Pager<HtmlInfo> page(Integer offset) { Pager<HtmlInfo> pagerOrder=iAdminHtmlInfoDao.page(); return pagerOrder; } @Override public HtmlInfo selectHtmlInfoById(Integer id) { return iAdminHtmlInfoDao.selectHtmlInfoById(id); } @Override public Boolean delectHtmlInfoById(Integer id) { return iAdminHtmlInfoDao.delectHtmlInfoById(id); } @Override public List<HtmlInfo> selectHtmlInfo() { return iAdminHtmlInfoDao.selectHtmlInfo(); } @Override public List<HtmlInfo> selectHtmlInfo(int type) { return iAdminHtmlInfoDao.selectHtmlInfo(type); } }
true
164e7bf42bcedd338a34ee3854b47650f140fb8d
Java
ricpelo/pro2021
/java/Racional.java
UTF-8
996
3.3125
3
[]
no_license
public class Racional { private int numer; private int denom; public static int cantidad; private void setNumer(int numer) { this.numer = numer; } private void setDenom(int denom) { this.denom = denom; } private void simplificar() { int mcd = Matematicas.mcd(getNumer(), getDenom()); setNumer(getNumer() / mcd); setDenom(getDenom() / mcd); } public Racional(int numer, int denom) { setNumer(numer); setDenom(denom); simplificar(); cantidad++; } public Racional(int numer) { setNumer(numer); setDenom(1); cantidad++; } public int getNumer() { return numer; } public int getDenom() { return denom; } public void imprimir() { System.out.println(String.format("%d / %d", numer, denom)); } public void imprimir(String prefijo) { System.out.print(prefijo); imprimir(); } }
true
4ed695433bfb56e8a6460b40c2bd1a406b6ea6aa
Java
atulmishra0707/HMS
/src/main/java/com/hms/spring/aspects/LoggingAspect.java
UTF-8
578
2.34375
2
[]
no_license
package com.hms.spring.aspects; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.JoinPoint; @Aspect public class LoggingAspect { @Before("allMethod()") public void loggingAdvise(){ System.out.println(" - Advise Execution - "); } @Before("within(com.hms.spring..*)") public void loggingAdviseforAll(JoinPoint jp){ System.out.println("Advise Execution of method - "+jp.toString()); } @Pointcut("within(com.hms.spring..*)") public void allMethod(){} }
true