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
155a6f03adc675fef05f9ffd04972ac582f4c66e
Java
moutainhigh/boss2
/src/main/java/cn/eeepay/framework/model/workOrder/WorkOrderTransfer.java
UTF-8
551
1.835938
2
[]
no_license
package cn.eeepay.framework.model.workOrder; /** * @author :quanhz * @date :Created in 2020/5/7 10:48 */ public class WorkOrderTransfer { private String[] orderNoArr; private Integer receiverId; public String[] getOrderNoArr() { return orderNoArr; } public void setOrderNoArr(String[] orderNoArr) { this.orderNoArr = orderNoArr; } public Integer getReceiverId() { return receiverId; } public void setReceiverId(Integer receiverId) { this.receiverId = receiverId; } }
true
eec18616f1b0903ac77096cb921974f143ff2687
Java
IlyaFX/gammacases
/src/main/java/ru/ilyafx/gammacases/type/CaseItem.java
UTF-8
1,309
2.53125
3
[]
no_license
package ru.ilyafx.gammacases.type; import lombok.AllArgsConstructor; import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import java.util.List; import java.util.function.Consumer; @AllArgsConstructor @Getter public class CaseItem { private final String id; private final Material type; private final short data; private final String name; private final double chance; private final Consumer<Player> consumer; public CaseItem(String id, Material type, String name, double chance, Consumer<Player> consumer) { this(id, type, (short) 0, name, chance, consumer); } public CaseItem(String id, Material type, short data, String name, double chance, List<String> commands) { this(id, type, data, name, chance, (player) -> commands.forEach(command -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replace("%player%", player.getName()).replace("%player_uid%", player.getUniqueId().toString())))); } public CaseItem(String id, Material type, String name, double chance, List<String> commands) { this(id, type, (short) 0, name, chance, commands); } public void execute(Player player) { consumer.accept(player); } }
true
b328160da54e8937c47e641daa92330d3406c880
Java
Turn-Phantom/yunding
/server/server-queue/src/main/java/com/yunding/server/queue/entity/IpAddrInfo.java
UTF-8
1,190
1.929688
2
[]
no_license
package com.yunding.server.queue.entity; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.apache.ibatis.type.Alias; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @desc IP地址福归属地信息表 * @date 2020-04-09 */ @Table(name = "tb_addr_ipAddr") @Alias("ipAddrInfo") @Setter @Getter @Entity @ToString public class IpAddrInfo { // 主键 @Id @Column(name = "id") private Integer id; // IP地址 @Column(name = "ip") private String ip; // 地址 @Column(name = "address") private String address; // 国家 @Column(name = "country") private String country; // 省份 @Column(name = "province") private String province; // 城市 @Column(name = "city") private String city; // 乡镇 @Column(name = "village") private String village; // 备用字段1 @Column(name = "spare1") private String spare1; // 备用字段2 @Column(name = "spare2") private String spare2; // 备用字段3 @Column(name = "spare3") private String spare3; }
true
4d62bf1f1ae250baede7d4a314d0f1b7c3e3e16c
Java
assecopl/fh
/documentation/fh-docs/src/main/java/pl/fhframework/docs/dynamic_content/DynamicContentUC.java
UTF-8
17,981
2.078125
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package pl.fhframework.docs.dynamic_content; import pl.fhframework.core.security.annotations.SystemFunction; import pl.fhframework.core.uc.UseCase; import pl.fhframework.core.uc.IInitialUseCase; import pl.fhframework.core.uc.url.UseCaseWithUrl; import pl.fhframework.core.util.ComponentsUtils; import pl.fhframework.docs.DocsSystemFunction; import pl.fhframework.docs.dynamic_content.model.DynamicContentModel; import pl.fhframework.annotations.Action; import pl.fhframework.binding.AdHocActionBinding; import pl.fhframework.binding.AdHocModelBinding; import pl.fhframework.binding.CompiledBinding; import pl.fhframework.model.forms.*; import pl.fhframework.model.forms.Component; import pl.fhframework.model.forms.messages.Messages; import pl.fhframework.events.ViewEvent; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * Created by krzysztof.kobylarek on 2016-12-28. */ @UseCase @UseCaseWithUrl(alias = "docs-dynamic-content") //@SystemFunction(DocsSystemFunction.FH_DOCUMENTATION_VIEW) public class DynamicContentUC implements IInitialUseCase { private DynamicContentForm dynamicContentForm = null; private DynamicContentModel model = new DynamicContentModel(); private static String PARENT_GROUP_NAME = "placementGroup"; private static final AtomicInteger ID_SEQ = new AtomicInteger(1); @Override public void start() { dynamicContentForm = showForm(DynamicContentForm.class, model); } @Action public void onDynamicContentAddComponent(ViewEvent viewEvent) { PanelGroup panelGroup = (PanelGroup) ComponentsUtils.find(viewEvent.getSourceForm(), PARENT_GROUP_NAME); panelGroup.addSubcomponent(createComponent(viewEvent.getSourceForm(), panelGroup)); } @Action public void onDynamicContentRemoveComponent(ViewEvent viewEvent) { PanelGroup panelGroup = (PanelGroup) ComponentsUtils.find(viewEvent.getSourceForm(), PARENT_GROUP_NAME); if (panelGroup.getSubcomponents().size() > 0) { panelGroup.getSubcomponents().remove(panelGroup.getSubcomponents().size() - 1); } else { Messages.showInfoMessage(getUserSession(), "Placement group is empty"); } } @Action public void onDynamicContentAdd3Components(ViewEvent viewEvent) { PanelGroup panelGroup = (PanelGroup) ComponentsUtils.find(viewEvent.getSourceForm(), PARENT_GROUP_NAME); for (int i = 0; i < 3; ++i) { panelGroup.addSubcomponent(createComponent(viewEvent.getSourceForm(), panelGroup)); } } @Action public void onDynamicContentAdd_1Begining_2Middle_Components(ViewEvent viewEvent) { PanelGroup panelGroup = (PanelGroup) ComponentsUtils.find(viewEvent.getSourceForm(), PARENT_GROUP_NAME); { FormElement component = createComponent(viewEvent.getSourceForm(), panelGroup); ((LinkedList) panelGroup.getSubcomponents()).addFirst(component); } { FormElement component = createComponent(viewEvent.getSourceForm(), panelGroup); int size = ((LinkedList) panelGroup.getSubcomponents()).size(); ((LinkedList) panelGroup.getSubcomponents()).add((int) Math.ceil(size / 2), component); } { FormElement component = createComponent(viewEvent.getSourceForm(), panelGroup); ((LinkedList) panelGroup.getSubcomponents()).addLast(component); } } @Action public void onDynamicContentAdd_1Begining_2End_Components(ViewEvent viewEvent) { PanelGroup panelGroup = (PanelGroup) ComponentsUtils.find(viewEvent.getSourceForm(), PARENT_GROUP_NAME); { FormElement component = createComponent(viewEvent.getSourceForm(), panelGroup); ((LinkedList) panelGroup.getSubcomponents()).addFirst(component); } { FormElement component = createComponent(viewEvent.getSourceForm(), panelGroup); ((LinkedList) panelGroup.getSubcomponents()).addLast(component); } { FormElement component = createComponent(viewEvent.getSourceForm(), panelGroup); ((LinkedList) panelGroup.getSubcomponents()).addLast(component); } } @Action public void onDynamicContentRemove3Components(ViewEvent viewEvent) { PanelGroup panelGroup = (PanelGroup) ComponentsUtils.find(viewEvent.getSourceForm(), PARENT_GROUP_NAME); if (panelGroup.getSubcomponents().size() == 0) { Messages.showInfoMessage(getUserSession(), "Placement group is empty"); } else if (panelGroup.getSubcomponents().size() <= 3) { panelGroup.getSubcomponents().removeAll(panelGroup.getSubcomponents()); } else { LinkedList temp = new LinkedList(panelGroup.getSubcomponents()); for (int i = 0; i < 3; i++) { panelGroup.getSubcomponents().remove(temp.pollLast()); } } } @Action public void onDynamicContentRemoveAll(ViewEvent viewEvent) { PanelGroup panelGroup = (PanelGroup) ComponentsUtils.find(viewEvent.getSourceForm(), PARENT_GROUP_NAME); if (panelGroup.getSubcomponents() != null && panelGroup.getSubcomponents().size() > 0) { panelGroup.getSubcomponents().clear(); } else { Messages.showInfoMessage(getUserSession(), "Placement group is empty"); } } @Action public void onDynamicContentChangeComponentType(ViewEvent viewEvent) { ; } @Action public void onAddGroup(ViewEvent viewEvent) { Form<?> form = viewEvent.getSourceForm(); PanelGroup panelGroup = (PanelGroup) ComponentsUtils.find(form, PARENT_GROUP_NAME); PanelGroup newPanelGroup = new PanelGroup(viewEvent.getSourceForm()); newPanelGroup.init(); newPanelGroup.getSubcomponents().add(createComponent(form, panelGroup, Optional.of(DynamicContentModel.ChosenType.OUTPUTLABEL))); newPanelGroup.getSubcomponents().add(createComponent(form, panelGroup, Optional.of(DynamicContentModel.ChosenType.OUTPUTLABEL))); newPanelGroup.getSubcomponents().add(createComponent(form, panelGroup, Optional.of(DynamicContentModel.ChosenType.INPUTTEXT))); panelGroup.getSubcomponents().add(newPanelGroup); } private static String generateId(Component component) { return component.getClass().getSimpleName() + ID_SEQ.getAndIncrement(); } private FormElement createComponent(Form form, IGroupingComponent<Component> parent, Optional<DynamicContentModel.ChosenType> type) { FormElement component = null; if (type.isPresent()) { switch (type.get()) { case OUTPUTLABEL: OutputLabel outputLabel = new OutputLabel(form); outputLabel.setId(generateId(outputLabel)); outputLabel.setValueBindingAdHoc("I'm OutputLabel " + outputLabel.getId()); outputLabel.setWidth("md-4"); component = outputLabel; break; case SELECT_ONE_MENU: SelectOneMenu selectOneMenu = new SelectOneMenu(form); selectOneMenu.setId(generateId(selectOneMenu)); selectOneMenu.setListBinding(new CompiledBinding<>(List.class, model::getSelectOneMenuValues)); selectOneMenu.setModelBindingAdHoc("{selectOneMenuValue}"); selectOneMenu.setLabelModelBindingAdHoc("I'm SelectOneMenu " + selectOneMenu.getId()); selectOneMenu.setOnChange(new AdHocActionBinding("onChangeEvent(this)", form, selectOneMenu)); selectOneMenu.setWidth("md-4"); selectOneMenu.refreshElementToForm(); selectOneMenu.init(); component = selectOneMenu; break; case CHECKBOX: CheckBox checkBox = new CheckBox(form); checkBox.setId(generateId(checkBox)); checkBox.setModelBindingAdHoc("{checkboxValue}"); checkBox.setLabelModelBindingAdHoc("I'm CheckBox" + checkBox.getId()); checkBox.setOnChange(new AdHocActionBinding("onChangeEvent(this)", form, checkBox)); checkBox.refreshElementToForm(); checkBox.init(); component = checkBox; break; case INPUTTEXT: InputText inputText = new InputText(form); inputText.setId(generateId(inputText)); inputText.setModelBindingAdHoc("{inputTextValue}"); inputText.setLabelModelBindingAdHoc("I'm InputText " + inputText.getId()); inputText.setOnInput(new AdHocActionBinding("onInputEvent(this)", form, inputText)); inputText.setWidth("md-4"); inputText.refreshElementToForm(); inputText.init(); component = inputText; break; case REPEATER: Repeater repeater = new Repeater(form); repeater.setWidth("md-12"); repeater.setCollection(new CompiledBinding<>(List.class, model::getIterations)); repeater.setIterator("iter"); repeater.setInteratorComponentFactory((thisRepeater, rowNumberOffset, index) -> { OutputLabel outputLabel2 = new OutputLabel(form); outputLabel2.setId(generateId(outputLabel2)); outputLabel2.setValueBinding( new CompiledBinding<>(String.class, () -> "I'm OutpuLabel inside Repeater (iteration " + model.getIterations().get(index).getLabel() + ") + " + outputLabel2.getId())); outputLabel2.setGroupingParentComponent(repeater); outputLabel2.setWidth("md-4"); outputLabel2.init(); return Arrays.asList(outputLabel2); }); repeater.setGroupingParentComponent(parent); repeater.init(); component = repeater; break; case GROUP_IN_REPEATER: Repeater repeaterAndGroup = new Repeater(form); repeaterAndGroup.setCollection(new AdHocModelBinding<>(form, repeaterAndGroup, "{iterations}")); repeaterAndGroup.setIterator("iter"); repeaterAndGroup.setGroupingParentComponent(parent); repeaterAndGroup.setWidth("md-12"); repeaterAndGroup.init(); OutputLabel outputLabel_repeaterWithGroup = new OutputLabel(form); outputLabel_repeaterWithGroup.setId(generateId(outputLabel_repeaterWithGroup)); outputLabel_repeaterWithGroup.setValueBindingAdHoc("I'm OutpuLabel inside Repeater (iteration {iter.label}) " + outputLabel_repeaterWithGroup.getId()); outputLabel_repeaterWithGroup.setWidth("md-4"); repeaterAndGroup.addSubcomponent(outputLabel_repeaterWithGroup); outputLabel_repeaterWithGroup.setGroupingParentComponent(repeaterAndGroup); outputLabel_repeaterWithGroup.init(); PanelGroup panelGroup_repeaterWithPanelGroup = new PanelGroup(form); panelGroup_repeaterWithPanelGroup.setLabelModelBinding(panelGroup_repeaterWithPanelGroup.createAdHocModelBinding("I'm PanelGroup replicated inside Repeater")); panelGroup_repeaterWithPanelGroup.setGroupingParentComponent(repeaterAndGroup); panelGroup_repeaterWithPanelGroup.init(); InputText inputText_grupa_repeaterInGroup = new InputText(form); //inputText_grupa_repeaterInGroup.setBinding(""); inputText_grupa_repeaterInGroup.setId(generateId(inputText_grupa_repeaterInGroup)); inputText_grupa_repeaterInGroup.setModelBindingAdHoc("-"); inputText_grupa_repeaterInGroup.setLabelModelBindingAdHoc("I'm InputText added to PanelGroup replicated by Repeater (iteration {iter.label}) " + inputText_grupa_repeaterInGroup.getId()); inputText_grupa_repeaterInGroup.setGroupingParentComponent(panelGroup_repeaterWithPanelGroup); inputText_grupa_repeaterInGroup.setWidth("md-4"); inputText_grupa_repeaterInGroup.init(); panelGroup_repeaterWithPanelGroup.addSubcomponent(inputText_grupa_repeaterInGroup); repeaterAndGroup.addSubcomponent(panelGroup_repeaterWithPanelGroup); component = repeaterAndGroup; break; case GROUP: PanelGroup runtimePanelGroup = new PanelGroup(form); runtimePanelGroup.setLabelModelBinding(runtimePanelGroup.createAdHocModelBinding("I'm PanelGroup created in runtime")); runtimePanelGroup.init(); InputText inputText_runtimeGroup = new InputText(form); inputText_runtimeGroup.setId(generateId(inputText_runtimeGroup)); inputText_runtimeGroup.setModelBindingAdHoc("-"); inputText_runtimeGroup.setLabelModelBindingAdHoc("I'm InputText added to PanelGroup created in runtime " + inputText_runtimeGroup.getId()); inputText_runtimeGroup.setGroupingParentComponent(runtimePanelGroup); inputText_runtimeGroup.setWidth("md-4"); inputText_runtimeGroup.init(); runtimePanelGroup.getSubcomponents().add(inputText_runtimeGroup); runtimePanelGroup.setGroupingParentComponent(parent); component = runtimePanelGroup; break; case REPEATER_IN_REPEATER: Repeater outerRepeater = new Repeater(form); outerRepeater.setWidth("md-12"); outerRepeater.setCollection(new CompiledBinding<>(List.class, model::getIterations)); outerRepeater.setIterator("iter"); outerRepeater.setInteratorComponentFactory((thisOuterRepeater, rowNumberOffset, index) -> { OutputLabel outputLabel1_outerRepeater = new OutputLabel(form); outputLabel1_outerRepeater.setId(generateId(outputLabel1_outerRepeater)); outputLabel1_outerRepeater.setValueBinding( new CompiledBinding<>(String.class, () -> index + ". I'm OutputLabel in Repeater with another nested Repeater (iteration " + model.getIterations().get(index).getLabel() // get element from collection + " ) " + outputLabel1_outerRepeater.getId())); outputLabel1_outerRepeater.setWidth("md-4"); outputLabel1_outerRepeater.setGroupingParentComponent(outerRepeater); outputLabel1_outerRepeater.init(); Repeater innerRepeater = new Repeater(form); innerRepeater.setWidth("md-12"); innerRepeater.setCollection(new CompiledBinding<>(List.class, () -> model.getIterations().get(index).getIterations())); innerRepeater.setIterator("iter2"); innerRepeater.setInteratorComponentFactory((thisInnerRepeater, rowNumberOffsetInner, indexInner) -> { OutputLabel outputLabel1_innerRepeater = new OutputLabel(form); outputLabel1_innerRepeater.setId(generateId(outputLabel1_innerRepeater)); outputLabel1_innerRepeater.setWidth("md-4"); outputLabel1_innerRepeater.setValueBinding( new CompiledBinding<>(String.class, () -> index + "." + indexInner + ". I'm OutputLabel of Repeater nested inside Repeater (iteration " + model.getIterations().get(index).getIterations().get(indexInner).getLabel() // get element from inner collection + ") " + outputLabel1_innerRepeater.getId())); outputLabel1_innerRepeater.setGroupingParentComponent(innerRepeater); outputLabel1_innerRepeater.init(); return Arrays.asList(outputLabel1_innerRepeater); }); innerRepeater.setGroupingParentComponent(outerRepeater); innerRepeater.init(); return Arrays.asList(outputLabel1_outerRepeater, innerRepeater); }); outerRepeater.setGroupingParentComponent(parent); outerRepeater.init(); component = outerRepeater; break; } } return component; } private FormElement createComponent(Form<DynamicContentModel> form, IGroupingComponent parent) { return createComponent(form, parent, form.getModel().getComponentChosenType()); } @Action public void onInputEvent(ViewEvent viewEvent) { Messages.showInfoMessage(getUserSession(), "onInput event triggered"); } @Action public void onChangeEvent(ViewEvent viewEvent) { Messages.showInfoMessage(getUserSession(), "onChange event triggered"); } }
true
22064d6cd3d66b3cd956116468b75c6cd8ab42c7
Java
liveqmock/cdz-admin
/cdz-biz/biz-model/src/main/java/com/ga/cdz/domain/vo/admin/ChargingPriceAddVo.java
UTF-8
5,404
2.125
2
[]
no_license
package com.ga.cdz.domain.vo.admin; import com.fasterxml.jackson.annotation.JsonFormat; import com.ga.cdz.domain.entity.ChargingPrice; import com.ga.cdz.domain.group.admin.IMChargingPriceGroup; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.springframework.format.annotation.DateTimeFormat; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.math.BigDecimal; import java.sql.Time; /** * @author:wanzhongsu * @description: 计费价格vo * @date:2018/9/11 10:56 */ @EqualsAndHashCode(callSuper = false) @Data @Accessors(chain = true) public class ChargingPriceAddVo { /** * 充电站ID */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class, IMChargingPriceGroup.Update.class}, message = "充电站Id不能为空") private Integer stationId; /** * 价格名称 */ @NotBlank(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class, IMChargingPriceGroup.Update.class}, message = "策略名称不能为空") private String priceName; /** * 价格类型 1 专场计费 2 非专场计费 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class, IMChargingPriceGroup.Update.class}, message = "价格类型不能为空") private ChargingPrice.PriceType priceType; /** * 低谷 */ private ChargingPrice.PriceIdx low; /** * 低谷开始时间 */ @DateTimeFormat(pattern = "HH:mm:ss") @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8") @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "低谷开始时间不能为空") private Time lowStart; /** * 低谷结束时间 */ @DateTimeFormat(pattern = "HH:mm:ss") @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8") @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "低谷结束时间不能为空") private Time lowEnd; /** * 低谷充电价格 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "低谷充电价格不能为空") private BigDecimal lowPrice; /** * 低谷停车场价格 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "低谷停车场价格不能为空") private BigDecimal lowParking; /** * 低谷服务费用 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "低谷服务费用不能为空") private BigDecimal lowService; /** * 平谷 */ private ChargingPrice.PriceIdx middle; /** * 平谷开始时间 */ @DateTimeFormat(pattern = "HH:mm:ss") @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8") @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "平谷开始时间不能为空") private Time middleStart; /** * 平谷结束时间 */ @DateTimeFormat(pattern = "HH:mm:ss") @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8") @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "平谷结束时间不能为空") private Time middleEnd; /** * 平谷充电价格 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "平谷充电价格不能为空") private BigDecimal middlePrice; /** * 平谷停车场价格 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "平谷停车场价格不能为空") private BigDecimal middleParking; /** * 平谷服务费用 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "平谷服务费用不能为空") private BigDecimal middleService; /** * 高峰 */ private ChargingPrice.PriceIdx high; /** * 高峰开始时间 */ @DateTimeFormat(pattern = "HH:mm:ss") @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8") @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "高峰开始时间不能为空") private Time highStart; /** * 高峰结束时间 */ @DateTimeFormat(pattern = "HH:mm:ss") @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8") @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "高峰结束时间不能为空") private Time highEnd; /** * 高峰充电价格 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "高峰充电价格不能为空") private BigDecimal highPrice; /** * 高峰停车场价格 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "高峰停车场价格不能为空") private BigDecimal highParking; /** * 高峰服务费用 */ @NotNull(groups = {IMChargingPriceGroup.Add.class, IMChargingPriceGroup.Update.class}, message = "高峰服务费用不能为空") private BigDecimal highService; }
true
52edeb9acc3d4e20ee9c60d96965684e7a1ca9fd
Java
jhonemu/Client-Futbol-NXT
/src/api/futbol/GUI/VentanaPrincipal.java
UTF-8
9,831
1.976563
2
[]
no_license
package api.futbol.GUI; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import javax.ws.rs.core.MultivaluedMap; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; @SuppressWarnings("serial") public class VentanaPrincipal extends JFrame implements ActionListener { Container contenedor; JPanel panel1,panel2,panel3,panel4,panel6,panel7,panel8,panel9,panel10,panel11,panel12,panel13; JMenuBar barra; JMenu archivo,acciones,ayuda; public static JMenuItem help,inciarpar,conectar,salir,regAdmin,listjugadas,crearjug,finpartido,consultarEXjugada,cargar,consultarEXjugador,crearjugcompleja,listJugadores,Rgolafavor,Rgolencontra; ImageIcon icon; public static JPanel panel5; public static JTextArea areah; public static ArrayList<String> jugadasdelantero = new ArrayList<>(); public static ArrayList<String> jugadasarquero = new ArrayList<>(); public static JLabel historia,cancha,marcador; public static int gafavor =0; public static int gcontra =0; JScrollPane scroll; Image s; public static Imagen im= new Imagen(); public static JButton adelante,atras,izquierda,derecha,patear,correr,chutar,runAtras , ejecutar, parar,consultar; public static int tip = 0; public static JComboBox<String> jugadascomplejas,options; public VentanaPrincipal(){ super("Futbol-NXT"); } public void lanzarAd(){ contenedor = this.getContentPane(); panel1 = new JPanel(); panel2 = new JPanel(); panel3 = new JPanel(); panel4 = new JPanel(); panel5 = new JPanel(); panel6 = new JPanel(); panel7 = new JPanel(); panel8 = new JPanel(); panel9 = new JPanel(); panel10 = new JPanel(); panel11 = new JPanel(); panel12 = new JPanel(); panel13 = new JPanel(); marcador = new JLabel(gafavor+"-"+gcontra); jugadascomplejas = new JComboBox<String>(); options = new JComboBox<String>(); consultar = new JButton("Consultar"); ejecutar = new JButton("Ejecutar"); parar = new JButton("Parar"); adelante = new JButton("Trote"); correr = new JButton("Correr"); atras = new JButton("Atras"); runAtras = new JButton("Correr Atras"); izquierda = new JButton("Izquierda"); derecha = new JButton("Derecha"); patear = new JButton("Chute"); chutar = new JButton("Patear"); historia = new JLabel("Historia"); areah = new JTextArea(5,20); areah.setEditable(false); areah.setLineWrap(true); areah.setWrapStyleWord(true); areah.setText("Zona de informacion"); scroll = new JScrollPane(areah); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); //espacio menu barra = new JMenuBar(); archivo = new JMenu("Archivo"); acciones = new JMenu("Acciones"); ayuda = new JMenu("Ayuda"); //items consultarEXjugada = new JMenuItem("Consultar Explicacion de una jugada"); consultarEXjugador = new JMenuItem("Consultar informacion de un jugador"); help = new JMenuItem("Ayuda"); Rgolafavor = new JMenuItem("Registrar gol a favor"); Rgolencontra = new JMenuItem("Registrar gol en contra"); inciarpar = new JMenuItem("Iniciar partido"); conectar =new JMenuItem("Conectar a robot"); finpartido = new JMenuItem("Finalizar partido"); salir = new JMenuItem("Salir"); //items //archivo archivo.add(consultarEXjugada); archivo.add(consultarEXjugador); archivo.add(salir); //archivo //acciones acciones.add(inciarpar); acciones.add(conectar); acciones.add(Rgolafavor); acciones.add(Rgolencontra); acciones.add(finpartido); ayuda.add(help); //acciones barra.add(archivo); barra.add(acciones); barra.add(ayuda); //espacio menu..... contenedor.setLayout(new BorderLayout()); contenedor.add(panel1,BorderLayout.NORTH); contenedor.add(panel2,BorderLayout.CENTER); panel1.setLayout(new BorderLayout()); panel1.add(barra,BorderLayout.NORTH); panel2.setLayout(new BorderLayout()); panel2.add(panel3,BorderLayout.EAST); panel2.add(panel4, BorderLayout.CENTER); panel3.setLayout(new BoxLayout(panel3,BoxLayout.Y_AXIS)); options.setMaximumSize(new Dimension(450,23)); panel3.add(options); panel3.add(consultar); panel3.add(historia); panel3.add(scroll); panel4.setLayout(new BoxLayout(panel4,BoxLayout.Y_AXIS)); panel4.add(panel5); panel4.add(panel6); cancha = new JLabel(new ImageIcon("src\\images\\can.png")); cancha.setLayout(new BorderLayout()); panel5.add(cancha); cancha.add(im); panel6.setLayout(new GridLayout(1,2)); panel6.add(panel7); panel7.setLayout(new BorderLayout()); panel7.add(panel9, BorderLayout.NORTH); panel9.setLayout(new GridLayout(1,2)); panel9.add(adelante); panel9.add(correr); panel7.add(panel10, BorderLayout.SOUTH); panel10.setLayout(new GridLayout(1,2)); panel10.add(atras); panel10.add(runAtras); panel7.add(izquierda, BorderLayout.WEST); panel7.add(derecha, BorderLayout.EAST); panel7.add(panel11, BorderLayout.CENTER); panel11.setLayout(new GridLayout(1,2)); panel11.add(patear); panel11.add(chutar); panel6.add(panel8); panel8.setLayout(new BoxLayout(panel8,BoxLayout.Y_AXIS)); panel8.add(panel12); panel8.add(panel13); panel13.setLayout(new GridLayout(1,2,10,10)); panel13.add(ejecutar); ejecutar.setEnabled(false); Rgolafavor.setEnabled(false); inciarpar.setEnabled(false); Rgolencontra.setEnabled(false); finpartido.setEnabled(false); adelante.setEnabled(false); correr.setEnabled(false); atras.setEnabled(false); runAtras.setEnabled(false); izquierda.setEnabled(false); derecha.setEnabled(false); patear .setEnabled(false); chutar.setEnabled(false); panel12.setLayout(new GridLayout(3,1,10,10)); panel12.add(new JLabel("Marcador")); panel12.add(marcador); panel12.add(jugadascomplejas); consultar.addActionListener(this); ejecutar.addActionListener(this); adelante.addActionListener(new OyenteButton()); correr.addActionListener(new OyenteButton()); atras.addActionListener(new OyenteButton()); runAtras.addActionListener(new OyenteButton()); izquierda.addActionListener(new OyenteButton()); derecha.addActionListener(new OyenteButton()); patear.addActionListener(new OyenteButton()); chutar.addActionListener(new OyenteButton()); icon = new ImageIcon("src\\images\\ic_launcher.png"); salir.addActionListener(new OyenteMenu()); conectar.addActionListener(new OyenteMenu()); consultarEXjugada.addActionListener(new OyenteMenu()); consultarEXjugador.addActionListener(new OyenteMenu()); inciarpar.addActionListener(new OyenteMenu()); help.addActionListener(new OyenteMenu()); finpartido.addActionListener(new OyenteMenu()); Rgolafavor.addActionListener(new OyenteMenu()); Rgolencontra.addActionListener(new OyenteMenu()); setIconImage(icon.getImage()); setSize(900,650); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo (null); } @Override public void actionPerformed(ActionEvent arg) { String s = (String)arg.getActionCommand(); if(s.equals("Consultar")){ if(tip == 1){ WebResource webResource = Main.client.resource(Main.URL+"jcomplejas/explicacion"); JSONObject respuesta = webResource.queryParam("nombre", (String) options.getSelectedItem()).get(JSONObject.class); try { String nombre = respuesta.getString("nombre"); String fecha = respuesta.getString("fecha"); String autor = respuesta.getString("auto"); String exp = respuesta.getString("expli"); areah.setText(""); areah.append("La jugada: "+ nombre+"\n"+ "Fue creada el: " + fecha+"\n"+ "Por: "+ autor+"\n"+"Y es una: "+exp); } catch (JSONException e) { e.printStackTrace(); } } else if(tip == 2){ WebResource webResource = Main.client.resource(Main.URL+"jugador/info"); JSONObject respuesta = webResource.queryParam("nombre", (String) options.getSelectedItem()).get(JSONObject.class); try { areah.setText(""); if(respuesta.get("posicion").equals("Arquero")){ areah.append("Eljugador: "+respuesta.get("nombre") + "\n"+ "Juega de: " + respuesta.get("posicion")+ "\n"+ "Con el dorsal: " + respuesta.get("dorsal") +"\n"+ "Lleva "+ respuesta.get("tiempo sin gol") + " Sin gol" ); }else if(respuesta.get("posicion").equals("Delantero")){ areah.append("Eljugador: "+respuesta.get("nombre") + "\n"+ "Juega de: " + respuesta.get("posicion")+ "\n"+ "Con el dorsal: " + respuesta.get("dorsal") +"\n"+ "Lleva "+ respuesta.get("goles marcados") + " goles" ); } } catch (JSONException e) { e.printStackTrace(); } } }else if(s.equals("Ejecutar")){ WebResource webResource = Main.client.resource(Main.URL+"jcomplejas/ejecutar"); MultivaluedMap<String, String> Params = new MultivaluedMapImpl(); Params.add("nombre", (String)jugadascomplejas.getSelectedItem()); Params.add("nombrejug", Posicion.activo); String respuesta = webResource.queryParams(Params).get(String.class); System.out.println(respuesta); String[] pos = respuesta.split(","); Main.posicion.calcular(Integer.valueOf(pos[0]),Integer.valueOf(pos[1])); VentanaPrincipal.cancha.add(VentanaPrincipal.im); VentanaPrincipal.cancha.revalidate(); VentanaPrincipal.cancha.repaint(); } } }
true
7aaa7ed70855c2011cca62e92d788c1d421516d9
Java
vimgaa/hello-es2
/app/src/main/java/com/android/gl2jni/GL2JNIActivity.java
UTF-8
12,142
1.789063
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gl2jni; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.PointF; import android.graphics.Rect; import android.os.Bundle; import android.os.CountDownTimer; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.io.InputStream; public class GL2JNIActivity extends Activity { GL2JNIView mView; Toast mToast; private CountDownTimer autoCount; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); mView = new GL2JNIView(getApplication()); setContentView(mView); mView.setOnTouchListener(onTouchListener); // WindowManager wm = this.getWindowManager(); // DisplayMetrics outMetrics = new DisplayMetrics(); // wm.getDefaultDisplay().getMetrics(outMetrics); // Rect frame = new Rect(); // this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); // // int height = outMetrics.heightPixels + frame.top; // float persent = height *0.618f; // // if (outMetrics.heightPixels < outMetrics.widthPixels) { // persent = height; // } // ViewGroup.LayoutParams vp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) persent); // // this.addContentView(mView, vp); Button myButton = new Button(mView.getContext()); this.addContentView(myButton, new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT , ActionBar.LayoutParams.WRAP_CONTENT)); myButton.setText("变!!!"); myButton.setBackgroundColor(Color.parseColor("#11F5F5DC")); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int type = mView.renderer.getgType(); if (++type == 7) type = 0; getBitmap(type); countDownTimer.cancel(); mView.renderer.setGLType(type); } }); } @Override protected void onPause() { super.onPause(); mView.onPause(); } @Override protected void onResume() { super.onResume(); getBitmap(mView.renderer.getgType()); getBitmap(1); mView.onResume(); mView.renderer.setGLType(mView.renderer.getgType()); autoCount = new CountDownTimer(Integer.MAX_VALUE, 10) { @Override public void onTick(long millisUntilFinished) { float xAngle = mView.renderer.mAngleX + mXSpeed/100.0f; if (mView.renderer.maxAngleX > mView.renderer.minAngleX) { if (xAngle > mView.renderer.maxAngleX) { xAngle = mView.renderer.maxAngleX; if (mView.renderer.getgType() == 6) mXSpeed *= -1; } else if (xAngle < mView.renderer.minAngleX) { xAngle = mView.renderer.minAngleX; if (mView.renderer.getgType() == 6) mXSpeed *= -1; } } mView.renderer.mAngleX = xAngle; } @Override public void onFinish() { } }; autoCount.start(); } @Override protected void onDestroy() { mView.renderer.releaseLib(); super.onDestroy(); } private Bitmap loadBitmap(Context context, int resourceId) { InputStream is = context.getResources().openRawResource(resourceId); Bitmap bitmap = null; try { // 利用BitmapFactory生成Bitmap bitmap = BitmapFactory.decodeStream(is); } finally { try { // 关闭流 is.close(); is = null; } catch (IOException e) { e.printStackTrace(); } } return bitmap; } public void getBitmap(int type) { // Bitmap bitmap = loadBitmap(GL2JNIActivity.this, type != 6 ? R.drawable.image : R.drawable.bg); // Bitmap bitmap = loadBitmap(GL2JNIActivity.this, type != 6 ? R.drawable.xm343 : R.drawable.bg); Bitmap bitmap = loadBitmap(GL2JNIActivity.this, R.drawable.xm3); if (bitmap != null) { mView.renderer.updateImage(bitmap); } if (mToast != null) mToast.cancel(); switch (type) { case 0: mToast = Toast.makeText(this, "0", Toast.LENGTH_SHORT); break; case 1: mToast = Toast.makeText(this, "1", Toast.LENGTH_SHORT); break; case 2: mToast = Toast.makeText(this, "2", Toast.LENGTH_SHORT); break; case 3: mToast = Toast.makeText(this, "3", Toast.LENGTH_SHORT); break; case 4: mToast = Toast.makeText(this, "4", Toast.LENGTH_SHORT); break; case 5: mToast = Toast.makeText(this, "5", Toast.LENGTH_SHORT); break; case 6: mToast = Toast.makeText(this, "6", Toast.LENGTH_SHORT); break; default: return; } // mXSpeed = type == 6 ? 10 : 5; mToast.show(); } private View.OnTouchListener onTouchListener = new View.OnTouchListener() { float lastX, lastY; private int mode = 0; // 触控点的个数 float oldDist = 0; private VelocityTracker vTracker ; @Override public boolean onTouch(View v, MotionEvent event) { mView.mScaleDetector.onTouchEvent(event); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: countDownTimer.cancel(); //初始化速度检测器 if(vTracker == null){ vTracker = VelocityTracker.obtain(); }else{ vTracker.clear(); } vTracker.addMovement(event); mode = 1; lastX = event.getRawX(); lastY = event.getRawY(); break; case MotionEvent.ACTION_POINTER_DOWN: mode += 1; oldDist = caluDist(event); break; case MotionEvent.ACTION_POINTER_UP: mode -= 1; break; case MotionEvent.ACTION_UP: // case MotionEvent.ACTION_CANCEL: if (vTracker != null) { if (Math.abs(vTracker.getXVelocity()) > 1000) { mDelta = 2; mXSpeed = (vTracker.getXVelocity() < 0 ? -1 : 1) * (mView.renderer.getgType() == 6 ? 5 : 10); countDownTimer.start(); } vTracker.recycle(); vTracker = null; } mode = 0; break; case MotionEvent.ACTION_MOVE: vTracker.addMovement(event); vTracker.computeCurrentVelocity(1000); if (mode >= 2) { float newDist = caluDist(event); if (Math.abs(newDist - oldDist) > 2f) { zoom(newDist, oldDist); } } else { float dx = event.getRawX() - lastX; float dy = event.getRawY() - lastY; //TODO float width =mView.renderer.view_width; float height=mView.renderer.view_height; float a = 160.0f / 320; mView.renderer.transByPointF(new PointF(dx / width*2,dy / height *2)); // mView.requestRender(); float xAngle = mView.renderer.mAngleX + dx * a; if (mView.renderer.maxAngleX > mView.renderer.minAngleX) { if (xAngle > mView.renderer.maxAngleX) { xAngle = mView.renderer.maxAngleX; } else if (xAngle < mView.renderer.minAngleX) { xAngle = mView.renderer.minAngleX; } } mView.renderer.mAngleX = xAngle; float yAngle = mView.renderer.mAngleY - dy * a / 10; if (mView.renderer.maxAngleY > mView.renderer.minAngleY) { if (yAngle > mView.renderer.maxAngleY) { yAngle = mView.renderer.maxAngleY; } else if (yAngle < mView.renderer.minAngleY) { yAngle = mView.renderer.minAngleY; } } mView.renderer.mAngleY = yAngle; } break; } lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); return true; } }; public void zoom(float newDist, float oldDist) { DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); float px = displayMetrics.widthPixels; float py = displayMetrics.heightPixels; float zoomValue = mView.renderer.zoom; zoomValue += (newDist - oldDist) * ( mView.renderer.maxZoom - mView.renderer.minZoom) / Math.sqrt(px * px + py * py) / 4; if ( zoomValue > mView.renderer.maxZoom) { zoomValue = mView.renderer.maxZoom; } else if ( zoomValue < mView.renderer.minZoom) { zoomValue = mView.renderer.minZoom; } mView.renderer.zoom = zoomValue; } public float caluDist(MotionEvent event) { float dx = event.getX(0) - event.getX(1); float dy = event.getY(0) - event.getY(1); return (float)Math.sqrt((double)(dx * dx + dy * dy)); } private float mXSpeed = 10; private float mDelta = 2; public CountDownTimer countDownTimer = new CountDownTimer(3 * 1000, 25) { @Override public void onTick(long millisUntilFinished) { float xAngle = mView.renderer.mAngleX + mXSpeed / (float)Math.sqrt(mDelta); if (mView.renderer.maxAngleX > mView.renderer.minAngleX) { if (xAngle > mView.renderer.maxAngleX) { xAngle = mView.renderer.maxAngleX; } else if (xAngle < mView.renderer.minAngleX) { xAngle = mView.renderer.minAngleX; } } mView.renderer.mAngleX = xAngle; mDelta++; } @Override public void onFinish() { } }; }
true
9be51443c9558b2b7a96587ac89c5b70d7dab1b1
Java
x4e/vrtvm
/src/test/java/me/xdark/vrtvm/tests/ClassFileTests.java
UTF-8
1,091
2.578125
3
[]
no_license
package me.xdark.vrtvm.tests; import me.xdark.vrtvm.JavaObject; import me.xdark.vrtvm.MemberDeclaration; import me.xdark.vrtvm.VM; import me.xdark.vrtvm.VMThread; import me.xdark.vrtvm.mirror.JavaClass; import me.xdark.vrtvm.tests.classfiles.HelloWorldGenerator; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassWriter; class ClassFileTests { @Test @DisplayName("Hello World") void testHelloWorld() throws Throwable { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); HelloWorldGenerator.generate(cw); run(cw.toByteArray()); } private void run(byte[] classFile) throws InterruptedException { VM vm = new VM(); JavaClass clazz = vm.defineClass(new JavaObject(), new JavaObject(), null, classFile, 0, classFile.length); JavaObject instance = new JavaObject(); instance.setJClass(clazz); VMThread thread = new VMThread(vm, instance, new MemberDeclaration("run", "()V")); thread.start(); thread.wait(); } }
true
8fa24906ca193aa64d55bc594adb294af4a1455c
Java
RadioCooperativa/Presidenciales2018
/app/src/main/java/cl/cooperativa/presidenciales2018/RSSParserDetail.java
UTF-8
4,295
2.28125
2
[]
no_license
package cl.cooperativa.presidenciales2018; import android.content.Context; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import javax.net.ssl.HttpsURLConnection; /** * Created by innova6 on 14-07-2017. */ public class RSSParserDetail implements Serializable { private static Context context; //Context context; private InputStream urlStream; private XmlPullParserFactory factory; private XmlPullParser parser; private List<ArticleDetail> rssFeedList; private ArticleDetail rssFeed; private String urlString; private String tagName; private String title; private String link; private String description; private String cuerpoEnVivo; public static final String ITEM = "artic_data"; public static final String CHANNEL = "private"; public static final String TITLE = "_txt_titular"; public static final String LINK = "fotofija_port_649x365"; public static final String DESCRIPTION = "vtxt_cuerpo"; public static final String CUERPOENVIVO = "cuerpo_en_vivo"; public RSSParserDetail( String urlString ) { this.urlString=urlString; } public InputStream downloadUrl(String urlString) throws IOException, NoSuchAlgorithmException, KeyManagementException { URL url = new URL(urlString); HttpsURLConnection con = (HttpsURLConnection)url.openConnection(); InputStream stream = con.getInputStream(); return stream; } public List<ArticleDetail> parse() { try { int count = 0; factory = XmlPullParserFactory.newInstance(); parser = factory.newPullParser(); System.out.println("RSSPerserDetail, urlString: "+urlString); urlStream = downloadUrl(urlString); parser.setInput(urlStream, null); int eventType = parser.getEventType(); boolean done = false; rssFeed = new ArticleDetail(); rssFeedList = new ArrayList<ArticleDetail>(); while (eventType != XmlPullParser.END_DOCUMENT && !done) { tagName = parser.getName(); switch (eventType) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: if (tagName.equals(ITEM)) { rssFeed = new ArticleDetail(); } if (tagName.equals(TITLE)) { title = parser.nextText().toString(); } if (tagName.equals(LINK)) { link = parser.nextText().toString(); link= link.trim();//quitamos los espacios en blaco de path de conexión. // System.out.println("RSSParserDetail, trae el link foto"+link); } if (tagName.equals(DESCRIPTION)) { description = parser.nextText().toString(); } if (tagName.equals(CUERPOENVIVO)) { cuerpoEnVivo = parser.nextText().toString(); cuerpoEnVivo=cuerpoEnVivo.trim(); } break; case XmlPullParser.END_TAG: if (tagName.equals(CHANNEL)) { done = true; } else if (tagName.equals(ITEM)) { System.out.println("RSSParserDetail, em case XmlPullParser.END_TAG"); rssFeed=new ArticleDetail(title,description,link,cuerpoEnVivo); rssFeedList.add(rssFeed); } break; } eventType = parser.next(); } } catch (Exception e) { e.printStackTrace(); } return rssFeedList; } }
true
11ad66f40d961cf2a3a5802ac4ab223098e13773
Java
GabeOchieng/ggnn.tensorflow
/data/libgdx/BaseBulletTest_dispose.java
UTF-8
376
1.992188
2
[]
no_license
@Override public void dispose() { world.dispose(); world = null; for (Disposable disposable : disposables) disposable.dispose(); disposables.clear(); modelBatch.dispose(); modelBatch = null; shadowBatch.dispose(); shadowBatch = null; if (shadows) ((DirectionalShadowLight) light).dispose(); light = null; super.dispose(); }
true
5abb0da37b8a02527eef9f41041798e17cfa46df
Java
fercarcedo/AlgMeter
/AlgMeter/src/main/java/fergaral/algmeter/Meter.java
UTF-8
1,252
3.203125
3
[]
no_license
package fergaral.algmeter; import java.util.Map; import java.util.TreeMap; /** * Class used to measure the execution * time of a given algorithm * * @author fercarcedo * */ public class Meter { private Algorithm algorithm; private long startN; private long endN; private StepFunction stepFunction; private long repetitions; public Meter(Algorithm algorithm, long startN, long endN, StepFunction stepFunction, long repetitions) { this.algorithm = algorithm; this.startN = startN; this.endN = endN; this.stepFunction = stepFunction; this.repetitions = repetitions; } /** * Measures the execution time of the specified * algorithm, with n in [startN, endN], incremented * by stepN and repeated repetitions times * * @return algorithm execution time as map of [n, time] */ public Map<Long, Long> run() { Map<Long, Long> result = new TreeMap<>(); for (long n = startN; n <= endN; n = stepFunction.nextN(n)) { long totalTime = 0; for (long i = 0; i < repetitions; i++) { long startTime = System.currentTimeMillis(); algorithm.execute(n); totalTime += (System.currentTimeMillis() - startTime); } long time = totalTime / repetitions; result.put(n, time); } return result; } }
true
fcebf4aa0bc4b4a3a98b7877191f8c156b36e003
Java
diachron/quality
/lod-qualitymetrics/lod-qualitymetrics-representation/src/main/java/eu/diachron/qualitymetrics/representational/interpretability/NoBlankNodeUsage.java
UTF-8
5,061
2.03125
2
[ "MIT" ]
permissive
/** * */ package eu.diachron.qualitymetrics.representational.interpretability; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import org.mapdb.DB; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.impl.StatementImpl; import com.hp.hpl.jena.sparql.core.Quad; import com.hp.hpl.jena.vocabulary.RDF; import de.unibonn.iai.eis.diachron.mapdb.MapDbFactory; import de.unibonn.iai.eis.diachron.semantics.DQM; import de.unibonn.iai.eis.diachron.technques.probabilistic.ReservoirSampler; import de.unibonn.iai.eis.luzzu.datatypes.ProblemList; import de.unibonn.iai.eis.luzzu.properties.EnvironmentProperties; import de.unibonn.iai.eis.luzzu.semantics.utilities.Commons; import eu.diachron.qualitymetrics.utilities.AbstractQualityMetric; /** * @author Jeremy Debattista * * This metric calculates the number of blank nodes found in the subject or the object * of a triple. The metric value returns a value [0-1] where a higher number of blank nodes * will result in a value closer to 0. */ public class NoBlankNodeUsage extends AbstractQualityMetric { private static Logger logger = LoggerFactory.getLogger(NoBlankNodeUsage.class); //we will store all data level constraints that are URIs private static DB mapDb = MapDbFactory.getMapDBAsyncTempFile(); private Set<String> uniqueDLC = MapDbFactory.createHashSet(mapDb, UUID.randomUUID().toString()); private Set<String> uniqueBN = MapDbFactory.createHashSet(mapDb, UUID.randomUUID().toString()); // private Set<SerialisableQuad> _problemList = MapDbFactory.createHashSet(mapDb, UUID.randomUUID().toString()); ReservoirSampler<ProblemReport> problemSampler = new ReservoirSampler<ProblemReport>(250000, false); private Model problemModel = ModelFactory.createDefaultModel(); // private Resource bagURI = Commons.generateURI(); // private Bag problemBag = problemModel.createBag(bagURI.getURI()); @Override public void compute(Quad quad) { Node predicate = quad.getPredicate(); Node subject = quad.getSubject(); Node object = quad.getObject(); logger.debug("Assessing quad: " + quad.asTriple().toString()); // we will skip all "typed" triples if (!(predicate.hasURI(RDF.type.getURI()))){ if (subject.isBlank()) { uniqueBN.add(subject.getBlankNodeLabel()); ProblemReport pr = new ProblemReport(quad); problemSampler.add(pr); } else uniqueDLC.add(subject.getURI()); if (!(object.isLiteral())){ if (object.isBlank()){ uniqueBN.add(object.getBlankNodeLabel()); ProblemReport pr = new ProblemReport(quad); problemSampler.add(pr); } else uniqueDLC.add(object.getURI()); } } } @Override public double metricValue() { statsLogger.info("No Blank Node Usage. Dataset: {} - Unique DLC {}, Unique BN {}", EnvironmentProperties.getInstance().getDatasetURI(), uniqueDLC.size(), uniqueBN.size() ); return ((double) uniqueDLC.size()) / ((double) uniqueDLC.size() + (double) uniqueBN.size()); } @Override public Resource getMetricURI() { return DQM.NoBlankNodeMetric; } //TODO: fix problem report @Override public ProblemList<?> getQualityProblems() { ProblemList<Model> tmpProblemList = new ProblemList<Model>(); if(this.problemSampler != null && this.problemSampler.size() > 0) { // for(ProblemReport pr : this.problemSampler.getItems()){ // List<Statement> stmt = pr.createProblemModel(); // this.problemBag.add(stmt.get(0).getSubject()); // this.problemModel.add(stmt); // } // tmpProblemList.getProblemList().add(this.problemModel); } else { tmpProblemList = new ProblemList<Model>(); } return tmpProblemList; } // public ProblemList<?> getQualityProblems() { // ProblemList<SerialisableQuad> pl = null; // try { // if(this._problemList != null && this._problemList.size() > 0) { // pl = new ProblemList<SerialisableQuad>(this._problemList); // } else { // pl = new ProblemList<SerialisableQuad>(); // } // } catch (ProblemListInitialisationException e) { // logger.error(e.getMessage()); // } // return pl; // } @Override public boolean isEstimate() { return false; } @Override public Resource getAgentURI() { return DQM.LuzzuProvenanceAgent; } private class ProblemReport{ private Quad q; ProblemReport(Quad q){ this.q = q; } List<Statement> createProblemModel(){ List<Statement> lst = new ArrayList<Statement>(); Resource anon = ModelFactory.createDefaultModel().createResource(Commons.generateURI()); lst.add(new StatementImpl(anon, RDF.subject, Commons.asRDFNode(q.getSubject()))); lst.add(new StatementImpl(anon, RDF.predicate, Commons.asRDFNode(q.getPredicate()))); lst.add(new StatementImpl(anon, RDF.object, Commons.asRDFNode(q.getObject()))); return lst; } } }
true
069da9adf678e0b45898053a303e48586ef87ca0
Java
jozefzatko/page-flow-project
/page-flow-project/page-flow-project/page-flow-project/log-parser/src/test/java/sk/zatko/dp/logparser/parser/LogFileParserServiceAssemblyTest.java
UTF-8
1,504
2.359375
2
[]
no_license
package sk.zatko.dp.logparser.parser; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import sk.zatko.dp.data.accesslog.AccessLog; import sk.zatko.dp.logparser.config.TestConfig; /** * Assembly test for @see sk.zatko.dp.logparser.parser.LogFileParserService * * @author Jozef Zatko */ @RunWith(SpringRunner.class) @ContextConfiguration(classes = {TestConfig.class}) @TestPropertySource("classpath:test.properties") public class LogFileParserServiceAssemblyTest { private static final String RIGHT_ACCESS_LOG_FILE_PATH = "src//test//resources//test_access_log.txt"; private static final String WRONG_ACCESS_LOG_FILE_PATH = "src//test//resources//non_existing_file.txt"; @Autowired private LogFileParserService logFileParserService; @Test public void testCorrect() throws IOException { AccessLog accessLog = logFileParserService.parseLogFile(RIGHT_ACCESS_LOG_FILE_PATH); Assert.assertNotNull(accessLog); Assert.assertEquals(accessLog.getLogs().size(), 7); } @Test(expected = FileNotFoundException.class) public void testToFail() throws IOException { logFileParserService.parseLogFile(WRONG_ACCESS_LOG_FILE_PATH); Assert.fail(); } }
true
f59154077ea80a6ac807d06266ff98ef8329e1f0
Java
VictorBonasa/Multimedia-RA3
/WS Multimedia RA3/Teemo's Mushroom/src/com/victor/teemo/EndScreen.java
UTF-8
1,553
2.3125
2
[]
no_license
package com.victor.teemo; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; public class EndScreen implements Screen { final Teemo juego; OrthographicCamera camara; long setas; long vida; Sound sonidoDefeat; public EndScreen(Teemo juego, long setas){ this.juego = juego; this.setas = setas; camara = new OrthographicCamera(); camara.setToOrtho(false, 1024, 768); sonidoDefeat = Gdx.audio.newSound(Gdx.files.internal("Female1_OnDefeat_1.ogg")); sonidoDefeat.play(); } @Override public void render(float delta) { Gdx.gl.glClearColor(0, 0, 0.2f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); camara.update(); juego.spriteBatch.setProjectionMatrix(camara.combined); juego.spriteBatch.begin(); juego.fuente.draw(juego.spriteBatch, "Fin del Juego", 400, 400); juego.fuente.draw(juego.spriteBatch, "Puntuacion Final: " + setas , 400, 384); juego.spriteBatch.end(); } @Override public void resize(int width, int height) { // TODO Auto-generated method stub } @Override public void show() { // TODO Auto-generated method stub } @Override public void hide() { // TODO Auto-generated method stub } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void dispose() { // TODO Auto-generated method stub } }
true
2bdaa2edc6e24e75de03cdf3cb92fb12e36fd635
Java
okokokok123/ssm-
/mybatisCode/mybatis03/src/dao/IAreaInfoNewDao.java
UTF-8
140
1.867188
2
[]
no_license
package dao; import java.util.List; import entity.AreaInfoNew; public interface IAreaInfoNewDao { public List<AreaInfoNew> getAll(); }
true
5efa5da39c9e3cd567141eeae9555381799ba931
Java
OwnPurpose/httpserver-kafka
/src/com/kafka/KafkaProducer.java
UTF-8
808
2.515625
3
[]
no_license
package com.kafka; import java.util.Properties; import com.protobuff.AccountBook.Account; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; /** * <p> * This is a Kafka Producer. This will send received Account data to specified Kafka Queue. * </p> */ public class KafkaProducer { public void send(Account account) { Properties props = new Properties(); props.put("zk.connet", "localhost:2181"); props.put("serializer.class", "kafka.serializer.StringEncoder"); props.put("metadata.broker.list", "localhost:9092"); ProducerConfig config = new ProducerConfig(props); Producer<String, String> pro = new Producer<>(config); pro.send(new KeyedMessage<String, String>("TutorialTopic", account.toString())); } }
true
4d96e4ca0296ebd5fecbecbc278313e8d27c0c73
Java
git-sky/javabasics
/src/main/java/cn/com/json_tools/fastjson/domain/WoMen.java
UTF-8
492
2.328125
2
[]
no_license
package cn.com.json_tools.fastjson.domain; import com.alibaba.fastjson.annotation.JSONField; /** * fastjson解析有下划线的对象会有问题,需要用@JSONField(name="_name")解决。 */ public class WoMen { private String _3name; private int _3age; public int get_3age() { return _3age; } public void set_3age(int _3age) { this._3age = _3age; } public String get_3name() { return _3name; } public void set_3name(String _3name) { this._3name = _3name; } }
true
b179ab6b78481ce6e839ece23e0d52ef30b64538
Java
nguyentrongdoan/Contact-manager
/src/Controller/MainController.java
UTF-8
9,260
2.859375
3
[]
no_license
package Controller; import Commons.FileCSV; import Commons.validation.FunValidation; import Moderm.User; //import java.io.BufferedReader; //import java.io.FileReader; //import java.io.FileWriter; //import java.io.Writer; //import java.nio.file.Files; //import java.nio.file.Path; //import java.nio.file.Paths; import java.util.ArrayList; import java.util.Scanner; public class MainController { private static ArrayList<User> listContact = new ArrayList<>(); private static Scanner input = new Scanner(System.in); private static ArrayList<String> list = new ArrayList<>(); private static ArrayList<String> list1 = new ArrayList<>(); private static ArrayList<String> list2 = new ArrayList<>(); public static void displayMenu(){ System.out.println("\n1. Show Contact" + "\n2. Add New User" + "\n3. Edit User" + "\n4. Delete User" + "\n5. Search User" + "\n6. Exit" + "\n. Please select one below: "); String choose = input.nextLine(); switch (choose){ case "1": showContact(); break; case "2": addUser(); break; case "3": editUser(); break; case "4": deleteUser(); break; case "5": searchUserContact(); break; case "6": System.exit(0); break; default: System.out.println("Error! Please choose again! Enter to continue..."); input.nextLine(); displayMenu(); } } private static void showContact() { getAllInformationContact(); if (listContact.isEmpty()){ System.out.println("Error! you are not information add! "); } System.out.println("Enter to continue...."); input.nextLine(); displayMenu(); } private static void getAllInformationContact(){ listContact = FileCSV.readFile(); for (User user: listContact){ System.out.println("-------------------"); System.out.println("Phone Number: " + user.getPhoneNumber()); System.out.println("Group contact: " + user.getGroupContact()); System.out.println("Name: " + user.getName()); System.out.println("Sex: " + user.getSex()); System.out.println("Address: " + user.getAddress()); System.out.println("-------------------"); } } private static void addUser() { listContact = FileCSV.readFile(); User user = new User(); System.out.println("Enter Phone Number: "); String phoneNumber = input.nextLine(); while (!FunValidation.checkPhoneNumber(phoneNumber)){ System.out.println("Phone number is invalid! Please try again: (exam: 0123456789 or +84123456789"); phoneNumber = input.nextLine(); } user.setPhoneNumber(phoneNumber); System.out.println("Enter Group Contact: "); user.setGroupContact(input.nextLine()); System.out.println("Enter Name: "); user.setName(input.nextLine()); System.out.println("Enter Male or Female: "); user.setSex(input.nextLine()); System.out.println("Enter Address: "); user.setAddress(input.nextLine()); System.out.println("Enter Birthday: "); user.setBirthday(input.nextLine()); System.out.println("Enter Email: "); String email = input.nextLine(); checkValidEmail(email, user); listContact.add(user); FileCSV.writerFile(listContact); System.out.println("Add new contact complete! Enter to continue..."); input.nextLine(); displayMenu(); } private static void editUser() { getAllInformationContact(); System.out.println("Please enter phone number you want edit information:"); String choosePhoneEdit = input.nextLine(); int count = 0; for (int i = 0; i < listContact.size(); i++){ if (listContact.get(i).getPhoneNumber().equals(choosePhoneEdit)){ System.out.println("1.Group contacts: " + listContact.get(i).getGroupContact()); System.out.println("2.FullName: " + listContact.get(i).getName()); System.out.println("3.Sex: " + listContact.get(i).getSex()); System.out.println("4.Address: " + listContact.get(i).getAddress()); System.out.println("5.Birthday: " + listContact.get(i).getBirthday()); System.out.println("6.Email: " + listContact.get(i).getEmail()); System.out.println("Please information you want edit: "); String chooseProperty = input.nextLine(); System.out.println("Please enter data you want change: "); String value = input.nextLine(); switch (chooseProperty){ case "1": listContact.get(i).setGroupContact(value); break; case "2": listContact.get(i).setName(value); break; case "3": listContact.get(i).setSex(value); break; case "4": listContact.get(i).setAddress(value); break; case "5": listContact.get(i).setBirthday(value); break; case "6": checkValidEmail(value, listContact.get(i)); break; } FileCSV.writerFile(listContact); System.out.println("Edit completed!"); count++; System.out.println("Enter to continue..."); input.nextLine(); displayMenu(); } } if (count == 0){ System.out.println("not found"); } count = 0; System.out.println("Enter to continue..."); input.nextLine(); displayMenu(); } private static void checkValidEmail(String value, User user) { while (!FunValidation.checkEmail(value)) { System.out.println("Email is invalid! Please try again: "); value = input.nextLine(); } user.setEmail(value); } private static void deleteUser() { getAllInformationContact(); int count = 0; do { System.out.println("Please enter phone number you want delete: "); String choosePhoneDelete = input.nextLine(); for (int i = 0; i < listContact.size(); i++) { if (listContact.get(i).getPhoneNumber().equalsIgnoreCase(choosePhoneDelete)) { System.out.println("Bạn có chắc chắn muốn xóa thông tin danh bạ này không ? Nhập Y nếu bạn muốn xóa."); String choose = input.nextLine(); String regex = "^[Y]$"; if (choose.toUpperCase().matches(regex)) { listContact.remove(i); FileCSV.writerFile(listContact); System.out.println("Delete complete!"); count++; break; } else { System.out.println("Enter to continue..."); input.nextLine(); displayMenu(); } } } if (count == 0) { System.out.println("not found"); } } while (count == 0); count = 0; System.out.println("Enter to continue..."); input.nextLine(); displayMenu(); } private static void searchUser() { getAllInformationContact(); System.out.println("Enter User name: "); String chooseWordSearch = input.nextLine(); String result = chooseWordSearch.toLowerCase(); String regex = ".*" + result + ".*"; for (int i = 0; i < listContact.size(); i++) { if (listContact.get(i).getName().matches(regex)) { list.add(listContact.get(i).getPhoneNumber()); list.add(listContact.get(i).getGroupContact()); list.add(listContact.get(i).getName()); list.add(listContact.get(i).getSex()); list.add(listContact.get(i).getAddress()); list.add(listContact.get(i).getBirthday()); list.add(listContact.get(i).getEmail()); } } } public static void searchUserContact () { searchUser(); if (list.size() != 0) { for (String s : list) { System.out.println(s); } } else { System.out.println("not found!!!"); } list.clear(); System.out.println("Enter to continue..."); input.nextLine(); displayMenu(); } }
true
95edd71aa6b7c287d82c1bcdceacdd59dbf33c40
Java
cheng13576927404/MyFramework
/XmwApp/src/main/java/com/xiaomaowu/activitys/fragments/MainTab03.java
UTF-8
628
1.9375
2
[]
no_license
package com.xiaomaowu.activitys.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.xiaomaowu.R; public class MainTab03 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View newsLayout = inflater.inflate(R.layout.main_tab_03, container, false); return newsLayout; } @Override public void onResume() { super.onResume(); Log.i("chengsong", "MainTab03----onResume----->"); } }
true
798b6f0958c2d6f80dcd140ec3b8a678924cbc52
Java
qls0ulp/FCM-toolbox
/app/src/main/java/fr/smarquis/fcm/payloads/Payload.java
UTF-8
474
1.789063
2
[ "Apache-2.0" ]
permissive
package fr.smarquis.fcm.payloads; import androidx.annotation.DrawableRes; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; public interface Payload { @DrawableRes int icon(); @Nullable CharSequence display(); @IdRes int notificationId(); @NonNull NotificationCompat.Builder configure(@NonNull NotificationCompat.Builder builder); }
true
46e9e3bda9f15262cce96279d0eeb6d13e4687d4
Java
Peter-Chensl/JavaCode
/day_06_03/src/demo/Developer.java
UTF-8
285
2.40625
2
[]
no_license
package demo; public abstract class Developer extends Employee { public Developer() { // TODO Auto-generated constructor stub super(); } public Developer(String name,int age){ super(name,age); } @Override public void work() { // TODO Auto-generated method stub } }
true
432b0d79cf9fb96579458ab4386026ffe22634e9
Java
tjudoubi/vben-admin-java
/admin-server/src/main/java/com/xm/admin/module/content/controller/ConArticleCategoryController.java
UTF-8
3,091
2.0625
2
[]
no_license
package com.xm.admin.module.content.controller; import com.xm.admin.module.content.entity.ConArticleCategory; import com.xm.admin.module.content.payload.ArticleCategoryAddEditRequest; import com.xm.admin.module.content.service.IConArticleCategoryService; import com.xm.common.utils.ResultUtil; import com.xm.common.vo.Result; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * <p> * 前端控制器 * </p> * * @author xiaomalover <[email protected]> * @since 2021-09-26 */ @RestController @RequestMapping("/article/category") public class ConArticleCategoryController { final IConArticleCategoryService articleCategoryService; public ConArticleCategoryController(IConArticleCategoryService articleCategoryService) { this.articleCategoryService = articleCategoryService; } @GetMapping("/getCategoryTree") public Result<Object> getDepartmentTree( @RequestParam(required = false) String categoryName, @RequestParam(required = false) Integer status ) { return new ResultUtil<>().success(articleCategoryService.getCategoryTree(categoryName , status)); } @PostMapping("/add") public Result<Object> add(@Valid @ModelAttribute ArticleCategoryAddEditRequest articleCategoryAddEditRequest) { ConArticleCategory articleCategory = new ConArticleCategory(); articleCategory.setName(articleCategoryAddEditRequest.getCategoryName()); articleCategory.setParentId(articleCategoryAddEditRequest.getParentCategory()); articleCategory.setSortOrder(articleCategoryAddEditRequest.getOrderNo()); articleCategory.setDescription(articleCategoryAddEditRequest.getRemark()); articleCategory.setStatus(articleCategoryAddEditRequest.getStatus()); if (articleCategoryService.save(articleCategory)) { return new ResultUtil<>().success(true); } return new ResultUtil<>().error(); } @PostMapping("/edit") public Result<Object> edit(@Valid @ModelAttribute ArticleCategoryAddEditRequest articleCategoryAddEditRequest) { ConArticleCategory articleCategory = articleCategoryService.getById(articleCategoryAddEditRequest.getId()); articleCategory.setName(articleCategoryAddEditRequest.getCategoryName()); articleCategory.setParentId(articleCategoryAddEditRequest.getParentCategory()); articleCategory.setSortOrder(articleCategoryAddEditRequest.getOrderNo()); articleCategory.setDescription(articleCategoryAddEditRequest.getRemark()); articleCategory.setStatus(articleCategoryAddEditRequest.getStatus()); if (articleCategoryService.updateById(articleCategory)) { return new ResultUtil<>().success(true); } return new ResultUtil<>().error(); } @DeleteMapping("/delete/{id}") public Result<Object> edit(@PathVariable String id) { if (articleCategoryService.removeById(id)) { return new ResultUtil<>().success(true); } return new ResultUtil<>().error(); } }
true
0f180233aa42f17f3e02c0801603e8ea8e7146a0
Java
SreeHarsha1/Playground
/Finding the frequency of alphabets/Main.java
UTF-8
845
3.125
3
[]
no_license
import java.util.Scanner; class Main{ public static void main(String args[]) { Scanner in = new Scanner(System.in); String str1=in.nextLine(); String str = str1.toLowerCase(); int ch[] = new int[26]; for(int i=0;i<=25;i++) { ch[i]=0; } for(int i=0;i<str.length();i++) { if(str.charAt(i)>='a'&&str.charAt(i)<='z') { int o = str.charAt(i)+1-'a'; ch[o]++; } } for(int i=0;i<str.length();i++) { if(str.charAt(i)>='a'&&str.charAt(i)<='z') { int o = str.charAt(i)+1-'a'; ch[o]++; if(ch[o]!=1) { System.out.print(str.charAt(i)); System.out.print(ch[o]-1+" "); ch[o]=0;} }} // Type your code here }}
true
350dcaf1c517c741a08fee3cf76410d0ece3feab
Java
hylrf0/practice
/src/main/java/thinkinjava/exercises/five/TwentyOne.java
UTF-8
1,267
3.90625
4
[]
no_license
package thinkinjava.exercises.five; /** * Created by linrufeng on 2017/2/28. * 21和22题 */ public class TwentyOne { private Money money; public TwentyOne(Money money) { this.money = money; } public void description() { switch (money) { case ONE: System.out.println("1块钱"); break; case FIVE: System.out.println("5块钱"); break; case TEN: System.out.println("10块钱"); break; case TWENTY: System.out.println("20块钱"); break; case FIVTEEN: System.out.println("50块钱"); break; case ONE_HUNDRED: System.out.println("100块钱"); break; default: System.out.println("????"); } } public static void main(String[] args) { for (Money money : Money.values()) { System.out.println(money + ", ordinal " + money.ordinal()); } TwentyOne twentyOne = new TwentyOne(Money.FIVE); twentyOne.description(); } } enum Money { ONE, FIVE, TEN, TWENTY, FIVTEEN, ONE_HUNDRED }
true
80955445d3271b4e5d04b67f5b712f5aad03bc36
Java
WAndromeda/OOP
/Labs (3 Semester)/Lab5/MenuLab.java
UTF-8
4,196
3.078125
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class MenuLab extends JFrame { private final static int N = 3; private String path = new String(); private Font font = new Font("Times New Roman", Font.PLAIN, 30); private JPanel mainPanel; private JButton[] buttons; private JLabel[] tasks; MenuLab(){ super("Лабораторная работа 5 | Меню"); setDefaultCloseOperation(EXIT_ON_CLOSE); setFont(font); mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); creatingJLablel(); creatingJButtons(); panelAdd(); mainPanel.setBorder(BorderFactory.createLineBorder(Color.orange)); setContentPane(mainPanel); addKeyListener(new EscapeAction()); locateWindow(); requestFocusInWindow(); } MenuLab(String path){ this(); this.path = new String(path); } private void creatingJLablel(){ tasks = new JLabel[N]; for (int i = 0; i < tasks.length; i++){ tasks[i] = new JLabel("Задание " + (i+1)); tasks[i].setFont(font); tasks[i].addKeyListener(new EscapeAction()); } tasks[0].setToolTipText("Создать окно, нарисовать в нем 20 случайных фигур, случайного цвета. Классы фигур должны наследоваться от абстрактного класса Shape, в котором описаны свойства фигуры: цвет, позиция"); tasks[1].setToolTipText("Создать окно, отобразить в нем картинку, путь к которой указан в аргументах командной строки"); tasks[2].setToolTipText("Создать окно, реализовать анимацию, с помощью картинки, состоящей из нескольких кадров"); } private void creatingJButtons(){ buttons = new JButton[N]; for (int i = 0; i < buttons.length; i++) { buttons[i] = new JButton("Запустить"); buttons[i].setFont(font); buttons[i].setFocusPainted(false); buttons[i].addKeyListener(new EscapeAction()); } buttons[0].addActionListener(new ActionTask()); buttons[1].addActionListener(new ActionTask()); buttons[2].addActionListener(new ActionTask()); } private void panelAdd(){ int k = 0; mainPanel.add(Box.createVerticalStrut(30)); JPanel[] panels = new JPanel[N]; for (JPanel i : panels) { i = new JPanel(); i.setLayout(new BoxLayout(i, BoxLayout.X_AXIS)); i.add(Box.createHorizontalStrut(50)); i.add(tasks[k]); i.add(Box.createHorizontalStrut(50)); i.add(buttons[k]); i.add(Box.createHorizontalStrut(50)); mainPanel.add(i); mainPanel.add(Box.createVerticalStrut(30)); k++; } } private void locateWindow(){ pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((screenSize.getWidth() - getWidth())/2); int y = (int) ((screenSize.getHeight() - getHeight())/2); setResizable(false); setLocation(x, y); } class ActionTask implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == buttons[0]) new Task1().setVisible(true); else if (e.getSource() == buttons[1]) new Task2(path).setVisible(true); else new Task3().setVisible(true); dispose(); } } class EscapeAction extends KeyAdapter{ @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) System.exit(0); } } }
true
c3cc76f7f85ba4cfc6f389663139f54a0492bbd4
Java
awantik/spring-MindTree-7
/spring-mvc-test-examples-master/controllers-unittest/src/test/java/net/skillspeed/spring/testmvc/todo/TestUtil.java
UTF-8
671
2.5625
3
[ "Apache-2.0" ]
permissive
package net.skillspeed.spring.testmvc.todo; /** * @author Awantik Das */ public class TestUtil { private static final String CHARACTER = "a"; public static String createRedirectViewPath(String path) { StringBuilder redirectViewPath = new StringBuilder(); redirectViewPath.append("redirect:"); redirectViewPath.append(path); return redirectViewPath.toString(); } public static String createStringWithLength(int length) { StringBuilder builder = new StringBuilder(); for (int index = 0; index < length; index++) { builder.append(CHARACTER); } return builder.toString(); } }
true
7d6ea68e30f73c139ffe091b799f1bf8205f7fb3
Java
soulline/soulline
/Yaoyle/src/com/yyl/sensor/YylSensorManager.java
UTF-8
3,014
2.53125
3
[]
no_license
package com.yyl.sensor; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Vibrator; public class YylSensorManager { private Context context; private SensorManager sensorManager; private Vibrator vibrator; // 手机上一个位置时重力感应坐标 private float lastX; private float lastY; private float lastZ; // 上次检测时间 private long lastUpdateTime; private long lastShakeTime; //上一次摇骰子时间 // 速度阈值,当摇晃速度达到这值后产生作用 private static final int SPEED_SHRESHOLD = 300; // 两次检测的时间间隔 private static final int UPTATE_INTERVAL_TIME = 70; //摇骰子响应时间间隔 private static final int SHAKE_INTERVAL_TIME = 2000; private OnShakeListener listener; public YylSensorManager(Context context, OnShakeListener listener) { this.context = context; this.listener = listener; } public void initSensor() { sensorManager = (SensorManager) context .getSystemService(Context.SENSOR_SERVICE); vibrator = (Vibrator) context .getSystemService(Context.VIBRATOR_SERVICE); registerSensor(); } public void registerSensor() { if (sensorManager != null) { sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); } } private SensorEventListener sensorEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { // 现在检测时间 long currentUpdateTime = System.currentTimeMillis(); // 两次检测的时间间隔 long timeInterval = currentUpdateTime - lastUpdateTime; // 判断是否达到了检测时间间隔 if (timeInterval < UPTATE_INTERVAL_TIME) return; // 现在的时间变成last时间 lastUpdateTime = currentUpdateTime; // 获得x,y,z坐标 float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; // 获得x,y,z的变化值 float deltaX = x - lastX; float deltaY = y - lastY; float deltaZ = z - lastZ; // 将现在的坐标变成last坐标 lastX = x; lastY = y; lastZ = z; // sqrt 返回最近的双近似的平方根 double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / timeInterval * 10000; if (speed >= SPEED_SHRESHOLD) { if (SHAKE_INTERVAL_TIME > (currentUpdateTime - lastShakeTime)) { return; } lastShakeTime = currentUpdateTime; onShake(); if (listener != null) { listener.onShake(); } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; public void unRegistSensor() { if (sensorManager != null) { sensorManager.unregisterListener(sensorEventListener); } } private void onShake() { vibrator.vibrate(new long[] { 500, 200, 500, 200 }, -1); } }
true
dfbf872b3cc3f2b1fa0268102160d7e31d04d4d8
Java
netallied/ADK
/de.netallied.adk/src/org/automationml/internal/aml/persistence/AMLCreateAttributeInstruction.java
UTF-8
3,637
1.953125
2
[ "MIT" ]
permissive
/******************************************************************************* * Copyright (c) 2019 NetAllied Systems GmbH, Ravensburg. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for details. *******************************************************************************/ package org.automationml.internal.aml.persistence; import org.automationml.aml.AMLAttribute; import org.automationml.aml.AMLAttributeContainer; import org.automationml.aml.AMLDocumentElement; import org.automationml.aml.AMLFacet; import org.automationml.aml.AMLInternalElement; import org.automationml.aml.AMLRoleRequirements; import org.automationml.aml.AMLSession; import org.automationml.aml.AMLSupportedRoleClass; public class AMLCreateAttributeInstruction extends AMLCreateInstruction { private AMLDeserializeIdentifier parentIdentifier; public String name = ""; public String dataType = ""; public String unit = ""; public String description = ""; public String defaultValue = ""; public String value = ""; protected AMLCreateAttributeInstruction(AMLSession session, AMLDeserializeIdentifier selfIdentifier, AMLDeserializeIdentifier parentIdentifier) { super(session, selfIdentifier); this.parentIdentifier = parentIdentifier; } @Override public AMLDeserializeIdentifier getParentIdentifier() { return parentIdentifier; } public AMLDocumentElement getParent() { if (parentIdentifier instanceof AMLDeserializeIdentifier) return parentIdentifier.getResolvedElement(); return null; } @Override public void execute() throws Exception { AMLDocumentElement parent = getParent(); if (parent instanceof AMLRoleRequirements) { AMLRoleRequirements roleRequirements = (AMLRoleRequirements)parent; AMLSupportedRoleClass supportedRoleClass = roleRequirements.getSupportedRoleClass(); String unescapedName = name; if (name.contains(".")) { AMLInternalElement internalElement = (AMLInternalElement) roleRequirements.getParent(); for (AMLSupportedRoleClass supportedRoleClass2 : internalElement.getSupportedRoleClasses()) { if (name.contains(supportedRoleClass2.getRoleClass().getName() + ".")) { supportedRoleClass = supportedRoleClass2; break; } } unescapedName = name.replace(supportedRoleClass.getRoleClass().getName() + ".", ""); } AMLAttribute attribute = roleRequirements.createAttribute(supportedRoleClass, unescapedName); attribute.setDataType(dataType); attribute.setDefaultValue(defaultValue); attribute.setDescription(description); attribute.setUnit(unit); attribute.setValue(value); if (selfIdentifier instanceof AMLDeserializeIdentifier) { selfIdentifier.setResolvedElement(attribute); } } else if (parent instanceof AMLFacet) { AMLFacet facet = (AMLFacet) parent; AMLInternalElement internalElement = (AMLInternalElement) parent.getParent(); AMLAttribute attribute = internalElement.getAttribute(name); facet.addAttribute(attribute); if (selfIdentifier instanceof AMLDeserializeIdentifier) { selfIdentifier.setResolvedElement(attribute); } } else if (parent instanceof AMLAttributeContainer) { AMLAttributeContainer attributeContainer = (AMLAttributeContainer) parent; AMLAttribute attribute = attributeContainer.createAttribute(name); attribute.setDataType(dataType); attribute.setDefaultValue(defaultValue); attribute.setDescription(description); attribute.setUnit(unit); attribute.setValue(value); if (selfIdentifier instanceof AMLDeserializeIdentifier) { selfIdentifier.setResolvedElement(attribute); } } } }
true
1be73a90dfd2589b85bbb1c0051971f88c21a194
Java
kishorsutar/Ds_Algo
/DS/src/main/java/ds/arraystring/CeaserCipher.java
UTF-8
391
3.375
3
[]
no_license
package ds.arraystring; public class CeaserCipher { public static void main(String[] args) { ceaserCepher("jahdfkjf", 45); } static void ceaserCepher(String s, int k) { int base = 'a'; for (char c : s.toCharArray()) { int value = ((c + k - base) % 26 + base); System.out.println("Value " + (char) value); } } }
true
dfef33ab452f67d9af20f13347b68c7d74ca3d6c
Java
m1kit/cc-archive
/2019.09/2019.09.15 - AtCoder Beginner Contest 141/EWhoSaysAPun.java
UTF-8
2,649
2.796875
3
[]
no_license
package dev.mikit.atcoder; import dev.mikit.atcoder.lib.io.LightScanner; import dev.mikit.atcoder.lib.io.LightWriter; import dev.mikit.atcoder.lib.debug.Debug; import java.util.ArrayList; import java.util.List; public class EWhoSaysAPun { private static final int MOD = (int) 1e9 + 7; public void solve(int testNumber, LightScanner in, LightWriter out) { // out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP); int n = in.ints(); String s = in.string(); if (s.substring(0, n / 2).equals(s.substring(n / 2, n))) { out.ans(n / 2).ln(); return; } int maxlen = 0, curlen = 1; for (int i = 1; i < n; i++) { if (s.charAt(i - 1) != s.charAt(i)) { if (curlen > maxlen) { maxlen = curlen; } curlen = 1; } else { curlen++; } } if (curlen > maxlen) { maxlen = curlen; } if (2 * maxlen >= n) { out.ans(maxlen / 2).ln(); return; } Substring substr = new Substring(s); List<Integer> bucket = new ArrayList<>(); for (int i = 0; i <= n; i++) bucket.add(i); bucket.sort(substr::compare); int max = 0; for (int t = 0; t < 100; t++) { for (int i = t; i < n; i++) { int cnt = 0; int x = bucket.get(i - t), y = bucket.get(i + 1); int len = n - Math.max(x, y); for (int j = 0; j < Math.min(len, Math.abs(x - y)); j++) { if (s.charAt(x + j) != s.charAt(y + j)) break; cnt++; } if (cnt > max) { max = cnt; } } } if (max == 0) { out.ans(0).ln(); } else { out.ans(max).ln(); } } private static class Substring { private int n; private String base; Substring(String base) { this.n = base.length(); this.base = base; } private int compare(int i, int j) { if (i == n && j == n) { return 0; } else if (i == n) { return -1; } else if (j == n) { return 1; } else if (base.charAt(i) == base.charAt(j)) { return compare(i + 1, j + 1); } else if (base.charAt(i) < base.charAt(j)) { return -1; } else { return 1; } } } }
true
8012c714ce56d73d2fd6545736a0b96e09213080
Java
Kodr-me/algorithmic-questions
/src/main/java/Solutions/TreesAndGraphs/ListOfDepths.java
UTF-8
1,151
3.953125
4
[]
no_license
package Solutions.TreesAndGraphs; import java.util.ArrayList; import java.util.List; // Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). public class ListOfDepths { List<List<Integer>> solution(BinaryTreeNode head) { int counter = 0; List<List<Integer>> listOfLists = new ArrayList<>(); traverseAndAppend(listOfLists, head, counter); return listOfLists; } private void traverseAndAppend(List<List<Integer>> list, BinaryTreeNode node, int counter) { if (node != null) { addToList(list, counter, node.data); traverseAndAppend(list, node.left, counter + 1); traverseAndAppend(list, node.right, counter + 1); } } private void addToList(List<List<Integer>> list, int counter, int value) { try { list.get(counter).add(value); } catch (IndexOutOfBoundsException error) { list.add(counter, new ArrayList<>()); list.get(counter).add(value); } } }
true
db6426365b1333cdd3ea895ad8b1d3498c1c7b2e
Java
mroslyak/myBusUI
/src/com/mybus/model/Stop.java
UTF-8
500
2.609375
3
[]
no_license
package com.mybus.model; import java.io.Serializable; public class Stop implements Serializable { String name, stopId; public Stop(String stopId, String name){ this.stopId = stopId; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getStopId() { return stopId; } public void setStopId(String stopId) { this.stopId = stopId; } @Override public String toString(){ return name; } }
true
5263b6fd18f504df395afb446db9fd6769ebaa25
Java
richardmr36/richard-java-programs
/data-structures-and-algorithms/src/test/java/com/myprograms/algorithms/trees/TreeTraversalsTest.java
UTF-8
1,344
3.4375
3
[]
no_license
package com.myprograms.algorithms.trees; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.*; public class TreeTraversalsTest { private Node buildTree() { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); return root; } @Test public void inOrder() { Node root = buildTree(); TreeTraversals treeTraversals = new TreeTraversals(); treeTraversals.inOrder(root); Assert.assertEquals("4 2 5 1 3 ", treeTraversals.getTraversedPath()); treeTraversals = new TreeTraversals(); treeTraversals.inOrderIterative(root); Assert.assertEquals("4 2 5 1 3 ", treeTraversals.getTraversedPath()); } @Test public void preOrder() { Node root = buildTree(); TreeTraversals treeTraversals = new TreeTraversals(); treeTraversals.preOrder(root); Assert.assertEquals("1 2 4 5 3 ", treeTraversals.getTraversedPath()); } @Test public void postOrder() { Node root = buildTree(); TreeTraversals treeTraversals = new TreeTraversals(); treeTraversals.postOrder(root); Assert.assertEquals("4 5 2 3 1 ", treeTraversals.getTraversedPath()); } }
true
78c9694a4e4a404ff69c4cd6898a0ffa47bf681f
Java
isulley77/MKS22X-USACO
/USACO.java
UTF-8
1,560
2.8125
3
[]
no_license
import java.io.*; import java.util.*; public class USACO{ public static int bronze(String filename) throws FileNotFoundException{ File f = new File(filename); Scanner s = new Scanner(f); int R, C, E, N; int solution = 0; int[] assign = new int[4]; for(int i = 0; i < 4; i++){ assign[i] = Integer.parseInt(s.next()); } R = assign[0]; C = assign[1]; E = assign[2]; N = assign[3]; int[][] board = new int[R][C]; for(int i = 0; i < R; i++){ for(int j = 0; j < C; j++){ board[i][j] = Integer.parseInt(s.next()); } } int counter = 0; while(counter < N){ int row = Integer.parseInt(s.next()) - 1; int col = Integer.parseInt(s.next()) - 1; int stomp = Integer.parseInt(s.next()); int maximum = 0; for(int r = row; r < row + 3; r++){ for(int c = col; c < col + 3; c++){ if(board[r][c] > maximum){ maximum = board[r][c]; } } } for(int r = row; r < row + 3; r++){ for(int c = col; c < col + 3; c++){ int d = maximum - board[r][c]; if(d < stomp){ board[r][c] = maximum - stomp; } } } counter++; } for(int r = 0; r < R; r++){ for(int c = 0; c < C; c++){ int current = board[r][c]; if(E - current > 0){ solution += E - current; } } } solution = solution * 72 * 72; return solution; } //public static int silver(String filename); }
true
53df2e0c825737d0e1a2ecdc92dc3d65e6351adc
Java
SmoothJM/LeetCodeAndSwordOffer
/src/dataStructure/WBTCBigPlus.java
UTF-8
2,569
3.546875
4
[]
no_license
package dataStructure; import java.util.Arrays; import java.util.Scanner; import java.util.Stack; public class WBTCBigPlus { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] nums = sc.nextLine().split(" "); String num1 = nums[0]; String num2 = nums[1]; Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); int n1 = 0; int n2 = 0; int maxLength = num1.length()>num2.length()?num1.length():num2.length(); for (int i = 0; i < maxLength; i++) { if(i<num1.length()){ n1 = Integer.parseInt(num1.charAt(i)+""); stack1.push(n1); } if(i<num2.length()){ n2 = Integer.parseInt(num2.charAt(i)+""); stack2.push(n2); } } System.out.println(Arrays.toString(stack1.toArray())); System.out.println(Arrays.toString(stack2.toArray())); boolean flag=false; String result = ""; int curr =0; for (int i = 0; i < maxLength; i++) { if(!stack1.isEmpty() && !stack2.isEmpty()){ if(flag){ curr =stack1.pop()+stack2.pop()+1; }else{ curr =stack1.pop()+stack2.pop(); } if(curr>=10){ curr = curr%10; flag=true; }else{ flag=false; } result +=curr; }else if(stack1.isEmpty()){ if(flag){ curr =stack2.pop()+1; }else{ curr =stack2.pop(); } if(curr>=10){ curr = curr%10; flag=true; }else{ flag=false; } result +=curr; }else if(stack2.isEmpty()){ if(flag){ curr =stack1.pop()+1; }else{ curr =stack1.pop(); } if(curr>=10){ curr = curr%10; flag=true; }else{ flag=false; } result +=curr; } } if(flag){ System.out.print(new StringBuffer(result+1).reverse().toString()); }else{ System.out.print(new StringBuffer(result).reverse().toString()); } } }
true
a6189fc3f6f2cdd696900ee9e17eddee60450a24
Java
udallmo/155-Project
/app/src/main/java/uwaterloo/ca/lab3_204_08/AccelerometerEventListener.java
UTF-8
3,786
2.671875
3
[]
no_license
package uwaterloo.ca.lab3_204_08; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.widget.TextView; import sensortoy.LineGraphView; public class AccelerometerEventListener implements SensorEventListener { private final float FILTER_CONSTANT = 9.0f; private TextView outputGesture; private GameLoopTask GameLoop; private myFSM[] myFSMs = new myFSM[2]; //x|y|z private int myFSMCounter; private final int FSM_COUNTER_DEFAULT = 50; // timer value for determining gestures private float[][] records = new float[100][3]; //Based on the FSM readings set the output according to the gestures given //If it is undetermined it the output is "WAITING" //Sets the direction based on the gesture private void determineGesture(){ myFSM.mySig[] sigs = new myFSM.mySig[2]; for(int i = 0; i < 2; i++) { sigs[i] = myFSMs[i].getSignature(); myFSMs[i].resetFSM(); } outputGesture.setTextSize(50.0f); outputGesture.setTextColor(Color.RED); if(sigs[0] == myFSM.mySig.SIG_A && sigs[1] == myFSM.mySig.undetermined){ outputGesture.setText("RIGHT"); GameLoop.setDirection(GameLoopTask.Directions.RIGHT); } else if(sigs[0] == myFSM.mySig.SIG_B && sigs[1] == myFSM.mySig.undetermined){ outputGesture.setText("LEFT"); GameLoop.setDirection(GameLoopTask.Directions.LEFT); } else if(sigs[0] == myFSM.mySig.undetermined && sigs[1] == myFSM.mySig.SIG_A){ outputGesture.setText("UP"); GameLoop.setDirection(GameLoopTask.Directions.UP); } else if(sigs[0] == myFSM.mySig.undetermined && sigs[1] == myFSM.mySig.SIG_B){ outputGesture.setText("DOWN"); GameLoop.setDirection(GameLoopTask.Directions.DOWN); } else{ outputGesture.setText("WAITING"); GameLoop.setDirection(GameLoopTask.Directions.NO_MOVEMENT); } } public AccelerometerEventListener(TextView outputView, GameLoopTask GL) { outputGesture = outputView; GameLoop = GL; for(int i = 0; i < 3; i++) for(int j = 0; j < 100; j++) records[j][i] = 0.0f; myFSMs[0] = new myFSM(); myFSMs[1] = new myFSM(); myFSMCounter = FSM_COUNTER_DEFAULT; } public float[][] getHistoryReading(){ return records; } public void onAccuracyChanged(Sensor s, int i) { } public void onSensorChanged(SensorEvent se) { if (se.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { // Setting the first 100 records for(int i = 1; i < 100; i++){ records[i - 1][0] = records[i][0]; records[i - 1][1] = records[i][1]; records[i - 1][2] = records[i][2]; } //Applying the LPF onto the newest record records[99][0] += (se.values[0] - records[99][0]) / FILTER_CONSTANT; records[99][1] += (se.values[1] - records[99][1]) / FILTER_CONSTANT; records[99][2] += (se.values[2] - records[99][2]) / FILTER_CONSTANT; // Supplying readings to myFSM.java during the counter // if the counter goes to 0 it starts to determine the gesture with the information given in the timer if (myFSMCounter > 0) { for (int i = 0; i < 2; i++) myFSMs[i].supplyInput(records[99][i]); myFSMCounter--; } else if (myFSMCounter <= 0) { determineGesture(); myFSMCounter = FSM_COUNTER_DEFAULT; } } } }
true
8826c42ef02ec3ec785dd98c003e2ecbb708d0fc
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_45ba5f439e094c07d10c3eb6cdd48c2c77b86fb9/CMPCertificate/2_45ba5f439e094c07d10c3eb6cdd48c2c77b86fb9_CMPCertificate_s.java
UTF-8
1,649
2.25
2
[]
no_license
package org.bouncycastle.asn1.cmp; import org.bouncycastle.asn1.ASN1Choice; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.x509.X509CertificateStructure; public class CMPCertificate extends ASN1Encodable implements ASN1Choice { private X509CertificateStructure x509v3PKCert; public CMPCertificate(X509CertificateStructure x509v3PKCert) { if (x509v3PKCert.getVersion() != 2) { throw new IllegalArgumentException("only version 3 certificates allowed"); } this.x509v3PKCert = x509v3PKCert; } public static CMPCertificate getInstance(Object o) { if (o instanceof CMPCertificate) { return (CMPCertificate)o; } if (o instanceof X509CertificateStructure) { return new CMPCertificate((X509CertificateStructure)o); } if (o instanceof ASN1Sequence) { return new CMPCertificate(X509CertificateStructure.getInstance(o)); } throw new IllegalArgumentException("Invalid object: " + o.getClass().getName()); } public X509CertificateStructure getX509v3PKCert() { return x509v3PKCert; } /** * <pre> * CMPCertificate ::= CHOICE { * x509v3PKCert Certificate * } * </pre> * @return a basic ASN.1 object representation. */ public DERObject toASN1Object() { return x509v3PKCert.toASN1Object(); } }
true
e9db0eef4ac7ac41ebd304dde7f7d7879ae3006f
Java
axiopisty/usertypes
/jsr354-hibernate-usertypes/src/test/java/com/github/axiopisty/usertypes/hibernate/jsr354/MonetaryAmountTypeTest.java
UTF-8
6,470
2.203125
2
[ "Apache-2.0" ]
permissive
package com.github.axiopisty.usertypes.hibernate.jsr354; import com.github.axiopisty.usertypes.wrapper.entities.MonetaryAmountWrapper; import com.github.axiopisty.usertypes.wrapper.service.MonetaryAmountWrapperService; import org.hibernate.type.BigDecimalType; import org.hibernate.type.StringType; import org.hibernate.type.Type; import org.javamoney.moneta.Money; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.inject.Inject; import javax.money.CurrencyUnit; import javax.money.MonetaryAmount; import javax.money.MonetaryCurrencies; import javax.money.NumberValue; import javax.money.format.MonetaryAmountFormat; import javax.money.format.MonetaryFormats; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Locale; import static org.junit.Assert.*; /** * @author Elliot Huntington */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/spring/applicationContext-test.xml" }) public class MonetaryAmountTypeTest { private final static MonetaryAmountType MAT = new MonetaryAmountType(); private final static CurrencyUnit USD = MonetaryCurrencies.getCurrency("USD"); private final static CurrencyUnit CNY = MonetaryCurrencies.getCurrency("CNY"); private final static MonetaryAmount ONE_USD = Money.of(BigDecimal.ONE, USD); private final static MonetaryAmount ONE_CNY = Money.of(BigDecimal.ONE, CNY); private final static MonetaryAmountFormat USDF = MonetaryFormats.getAmountFormat(Locale.US); private final static MonetaryAmountFormat CNYF = MonetaryFormats.getAmountFormat(Locale.CHINA); @Inject private MonetaryAmountWrapperService service; @Test public void testPropertyTypes() { Type[] expected = { BigDecimalType.INSTANCE, StringType.INSTANCE }; Type[] actual = MAT.getPropertyTypes(); assertArrayEquals(expected, actual); } @Test public void testPropertyNames() { String[] expected = { "number", "currency" }; String[] actual = MAT.getPropertyNames(); assertArrayEquals(expected, actual); } @Test public void testExtractNumberProperty() { BigDecimal expected = ONE_CNY.getNumber().numberValue(BigDecimal.class); BigDecimal actual = ((NumberValue)MAT.getPropertyValue(ONE_CNY, 0)).numberValue(BigDecimal.class); assertEquals("Should return a NumberValue that produces a BigDecimal", expected, actual); } @Test public void testExtractCurrencyProperty() { String expected = ONE_CNY.getCurrency().getCurrencyCode(); String actual = ((CurrencyUnit)MAT.getPropertyValue(ONE_CNY, 1)).getCurrencyCode(); assertEquals("Should return the appropriate currency code", expected, actual); } @Test(expected = IllegalArgumentException.class) public void testExtractIllegalProperty() { MAT.getPropertyValue(ONE_CNY, 2); } @Test public void testReturnedClass() { Class expected = MonetaryAmount.class; Class actual = MAT.returnedClass(); assertEquals(expected, actual); } @Test public void testEquals() { boolean actual = MAT.equals(ONE_USD, ONE_CNY); String format = String.format("%s == %s", USDF.format(ONE_USD), USDF.format(ONE_CNY)) + " ? %s"; assertEquals(String.format(format, actual), false, actual); MonetaryAmount one = Money.parse("USD 1"); actual = MAT.equals(ONE_USD, one); assertEquals(String.format(format, actual), true, actual); } @Test public void testHashCode() { int expected = ONE_USD.hashCode(); int actual = MAT.hashCode(ONE_USD); assertEquals(expected, actual); } @Test public void testIsMutable() { assertFalse(MAT.isMutable()); } @Test public void testDisassemble() { MAT.disassemble(ONE_USD, null); } @Test public void testAssemble() { assertEquals(ONE_CNY, MAT.assemble((Serializable) ONE_CNY, null, null)); } @Test public void testReplace() { assertEquals(ONE_CNY, MAT.replace(ONE_CNY, null, null, null)); } @Test public void testSameValueDifferentCurrencyNotEqual() { assertNotEquals(String.format("%s should not equal %s", USDF.format(ONE_USD), CNYF.format(ONE_CNY)), ONE_USD, ONE_CNY); } @Test public void testPersist() { MonetaryAmount expected = ONE_USD; Long id = create(expected); assertPersistedAmount(id, expected); checkUpdate(id, null); checkUpdate(id, ONE_CNY); service.cleanDatabase(); } private void checkUpdate(Long id, MonetaryAmount expected) { update(id, expected); assertPersistedAmount(id, expected); } private Long create(MonetaryAmount amount) { Long id = service.save(amount).getId(); assertTrue("id should exist after saving the wrapper", id != null); return id; } private void update(Long id, MonetaryAmount value) { service.cleanCache(); service.update(id, value); } private void assertPersistedAmount(Long id, MonetaryAmount expected) { service.cleanCache(); assertEquals(expected, service.findById(id).getMonetaryAmount()); } @Test public void testQueryByEqualMonetaryAmounts() { int NUMBER_OF_ITEMS = 5; int ITEM_INDEX = 2; List<MonetaryAmountWrapper> wrappers = cleanDatabaseAndInsertTestRecords(NUMBER_OF_ITEMS); MonetaryAmountWrapper threshold = wrappers.get(ITEM_INDEX); service.cleanCache(); Long actual = service.queryByMonetaryAmount(threshold.getMonetaryAmount()); Long expected = threshold.getId(); assertEquals(expected, actual); } @Test public void testQueryByMonetaryAmountsGreaterThan() { int NUMBER_OF_ITEMS = 5; int ITEM_INDEX = 3; List<MonetaryAmountWrapper> wrappers = cleanDatabaseAndInsertTestRecords(NUMBER_OF_ITEMS); MonetaryAmount threshold = wrappers.get(ITEM_INDEX).getMonetaryAmount(); service.cleanCache(); List<MonetaryAmountWrapper> actual = service.getMonetaryAmountsGreaterThan(threshold); int expected = NUMBER_OF_ITEMS - ITEM_INDEX - 1; assertEquals("MonetaryAmounts should be comparable", expected, actual.size()); } private List<MonetaryAmountWrapper> cleanDatabaseAndInsertTestRecords(int count) { service.cleanDatabase(); List<MonetaryAmountWrapper> list = new ArrayList<>(); for(int i = 0; i < count; ++i) { list.add(service.save(ONE_USD.add(Money.of(new BigDecimal("" + i), USD)))); } return list; } }
true
f02759360e6c72e1f82b1abcd6692f7bb239ba38
Java
evertrue/commoncrawl_utils
/src/main/java/org/commoncrawl/rpc/InProcessActor.java
UTF-8
12,122
2.9375
3
[ "MIT" ]
permissive
package org.commoncrawl.rpc; import java.io.IOException; import java.util.concurrent.ThreadPoolExecutor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.commoncrawl.async.EventLoop; import org.commoncrawl.rpc.MessageData.Status; import org.commoncrawl.util.shared.CCStringUtils; /** * Actor - Actors are concurrent tasks that respond to messages via a strictly * defined interface. An Actor can process messages in it's own EventLoop (thread) * or it can utilize a passed in ThreadPool object to execute each message in the * context of a worker thread. * * Actor is an abstract class and inorder to create an Actor instance you must * overload the Actor's dispatch method which is called whenever an Actor * receives a message. * * To communicate with an Actor, you open a Channel to it (via the createChannel * API). You can specify a source Actor, a source EventLoop or a source ThreadPool * when opening a Channel to an Actor. The Actor will then send reply messages * to the Channel owner in the context of the sender's EventLoop thread or ThreadPool. * * The CommonCrawl RPC Compiler allows you to specify a well defined Message * Interface via the Service keyword. Whenever the compiler processes a Service * definition, it automatically creates the appropriate stubs necessary to create * an Actor from the Service Interface specification. * * For example, if you defined a data structures and a serivce using the CommonCrawl * RPC IDL: * * class KeyValueTuple { * ustring key = 1; * buffer value = 2; * } * * class KeyValueIOResult { * enum Status { * SUCCESS = 0; * FAILURE = 1; * } * ustring key = 1; * int result = 2; * ustring optionalErrorDesc = 3; * } * * Service KeyValueWriterService { * method writeKeyValuePair(in KeyValueTuple,out KeyValueIOResult); * } * * The RPC compiler would create for you the following code: * * A Service interface definition as such: * public interface KeyValueWriterService extends Service { void writeKeyValuePair(IncomingMessage<KeyValueTuple,KeyValueIOResult> message) throws RPCException; } * A typed stub, that in combination with a channel, you can use to make * asynchronous calls to the Service: * * public static class AsyncStub extends Service.AsyncStub { // constructor public AsyncStub(Channel channel) { super(channel); } public OutgoingMessage<KeyValueTuple,KeyValueIOResult> writeKeyValuePair(KeyValueTuple input,OutgoingMessage.Callback<KeyValueTuple,KeyValueIOResult> callback) throws RPCException ... } * And a Factory to construct an Actor that adheres to an responds to the * Service specification: public static class ActorFactory { public static Actor createActorForService(final KeyValueWriterService instance,ThreadPoolExecutor executor,Actor.Events optionalListener) throws IOException .... } ** Using this generated code, you would construct an Actor as such: Actor keyValueWriter = KeyValueWriterService.ActorFactory.createActorForService( new KeyValueWriterService() { void writeKeyValuePair(IncomingMessage<KeyValueTuple,KeyValueIOResult> message) throws RPCException { // THIS CODE RUNS IN THE CONTEXT OF THE ACTOR's EVENTLOOP THREAD // OR IN A THREAD-POOL THREAD, DEPENDING ON HOW YOU CREATED THE ACTOR KeyValueTuple tuple = message.getInput(); ... do some work here... message.getOutput().setKey(message.getInput().getKey()); message.getOutput().setStatus(KeyValueIOResult.Status.SUCCESS); // WHEN YOU CALL COMPLETE REQUEST, // THE MESSAGE WILL BE QUEUED UP AND EXECUTED IN THE CONTEXT OF // THE CALLING THREAD'S (Channel Owners') CONTEXT. message.completeRequest(); } }, //no thread pool .. use event loop thread null, // event callback new Actor.Events() { ... } ); .... // SOME OTHER THREAD CONTEXT ... // CREATE A CHANNEL TO THE ABOVE ACTOR (RESPONSES PROCESSED IN THREAD POOL) Channel channel = keyValueWriter.createChannel(threadPool); // CREATE A STUB TO TALK TO SEND MESSAGES TO THE ACTOR KeyValueWriterService.AsyncStub stub = new KeyValueWriterService.AsyncStub(channel); // create and populate a tuple ... KeyValueTuple tuple = new KeyValueTuple(); tuple.setKey .... // send a message to the actor via the stub stub.writeKeyValuePair(tuple,new new OutgoingMessage.Callback() { requestComplete(OutgoingMessage message) { // this code will run in the context of the sender's thread (thread pool) // in this case ... if (message.getStatus() == Status.Success) { // do something ... } } }); * * * * @author rana * */ public abstract class InProcessActor { public static final Log LOG = LogFactory.getLog(InProcessActor.class); /** interface specification **/ // the event loop in which this actor resides EventLoop _eventLoop; // owns event loop boolean _ownsEventLoop; // optional thread pool executor ThreadPoolExecutor _executor; /** * Actors broadcast startup and shutdown events * If you want to do some setup work within the context of * the Actor thread (EventLoop thread), you should do so in the * actor's onStartup event callback. * */ public static interface Events { /** * called from within the context of the actor thread * during startup */ public void onStartup(InProcessActor actor); /** * called from within the context of the actor thread * during shutdown */ public void onShutdown(InProcessActor actor); } // optional event listener Events _eventListener; /** * constructor ... Actors are constructed via typed factory methods * * @param optionalExecutor * @throws IOException */ public InProcessActor(ThreadPoolExecutor optionalExecutor, Events optionalEventListener) throws IOException { if (optionalExecutor == null) { _eventLoop = new EventLoop(); _ownsEventLoop = true; } else { _executor = optionalExecutor; } _eventListener = optionalEventListener; } public void start() { if (_ownsEventLoop) { _eventLoop.start(); } if (_eventListener != null) { Runnable callback = new Runnable() { @Override public void run() { _eventListener.onStartup(InProcessActor.this); } }; if (_eventLoop != null && _eventLoop.getEventThread() == Thread.currentThread()) { callback.run(); } else { if (_eventLoop != null) _eventLoop.queueAsyncRunnable(callback); else _executor.submit(callback); } } } public void stop() { Runnable callback = new Runnable() { @Override public void run() { if (_eventListener != null) { _eventListener.onShutdown(InProcessActor.this); } if (_ownsEventLoop) { _eventLoop.stop(); } } }; if (_eventLoop != null && _eventLoop.getEventThread() == Thread.currentThread()) { callback.run(); } else { if (_eventLoop != null) _eventLoop.queueAsyncRunnable(callback); else _executor.submit(callback); } } @SuppressWarnings("unchecked") public static class IncomingMessage extends IncomingMessageContext { OutgoingMessageContext _source; public IncomingMessage(OutgoingMessageContext source, Channel channel, int requestId, RPCStruct input, RPCStruct output) { super(channel, requestId, input, output); _source = source; } public String getServiceName() { return _source._serviceName; } public String getMethodName() { return _source._methodName; } } /** * create a channel to This actor and send responses to the * specified source Actor * * @param sourceActor * @return a Channel object */ public final Channel createChannel(final InProcessActor sourceActor) { return createChannel(sourceActor, null, null); } /** * create a channel to This actor and run the response callback * in the specified EventLoop * @param sourceEventLoop * @return a Channel object */ public final Channel createChannel(final EventLoop sourceEventLoop) { return createChannel(null, sourceEventLoop, null); } /** * create a channel to This actor and run the response callback * in the specified ThreadPool * * @param sourceExecutor * @return a Channel object */ public final Channel createChannel(ThreadPoolExecutor sourceExecutor) { return createChannel(null, null, sourceExecutor); } /** * create a channel to This actor and run the response callback * in target actor's EventLoop or ThreadPool * * @return a Channel object */ public final Channel createChannel() { return createChannel(null, null, null); } /** * An extension of Channel that adds awareness of the attached InProcessActor * @author rana * */ public static interface InProcessChannel extends Channel { public InProcessActor getActor(); } private final Channel createChannel(final InProcessActor optionalSourceActor, final EventLoop optionalSourceEventLoop, final ThreadPoolExecutor optionalSourceExecutor) { return new InProcessChannel() { InProcessActor _optionalSourceActor = optionalSourceActor; EventLoop _optionalSourceEventLoop = optionalSourceEventLoop; ThreadPoolExecutor _optionalSourceExecutor = optionalSourceExecutor; @Override public void sendRequest( final OutgoingMessageContext<? extends RPCStruct, ? extends RPCStruct> originalMessage) throws RPCException { final IncomingMessage incomingMessage = new IncomingMessage(originalMessage, this, originalMessage.getRequestId(), (RPCStruct) originalMessage.getInput(), (RPCStruct) originalMessage.getOutput()); final Channel channel = this; Runnable callback = new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { try { dispatch(channel, incomingMessage); } catch (RPCException e) { LOG.error(CCStringUtils.stringifyException(e)); incomingMessage.setStatus(Status.Error_RPCFailed); incomingMessage.setErrorDesc(CCStringUtils.stringifyException(e)); try { sendResponse(incomingMessage); } catch (RPCException e1) { LOG.error(CCStringUtils.stringifyException(e1)); } } } }; if (_executor != null) { _executor.submit(callback); } else { _eventLoop.queueAsyncRunnable(callback); } } @SuppressWarnings("unchecked") @Override public void sendResponse(final IncomingMessageContext<? extends RPCStruct, ? extends RPCStruct> message) throws RPCException { Runnable closure = new Runnable() { @Override public void run() { final IncomingMessage localMessage = (IncomingMessage) message; if (localMessage._source.getCallback() != null) { localMessage._source.setOutput(message.getOutput()); localMessage._source.setStatus(message.getStatus()); localMessage._source.setErrorDesc(message.getErrorDesc()); localMessage._source.getCallback().requestComplete(localMessage._source); } } }; if (_optionalSourceActor != null) { if (_optionalSourceActor._executor != null) { _optionalSourceActor._executor.submit(closure); } else { _optionalSourceActor._eventLoop.queueAsyncRunnable(closure); } } else if (_optionalSourceEventLoop != null) { _optionalSourceEventLoop.queueAsyncRunnable(closure); } else if (_optionalSourceExecutor != null) { _optionalSourceExecutor.submit(closure); } else { closure.run(); } } @Override public InProcessActor getActor() { return InProcessActor.this; } }; } /** * Overload this method to handle message dispatches ... * * @param channel * @param message * @throws RPCException */ abstract public void dispatch(final Channel channel, final IncomingMessage message) throws RPCException; }
true
190c94e9701023919c48e699e422c7e2cb3f582e
Java
jw20082009/cutter
/library/src/main/java/com/wilbert/library/basic/entity/ActionEntity.java
UTF-8
1,015
2.515625
3
[]
no_license
package com.wilbert.library.basic.entity; import android.os.Parcel; /** * 后期动作{@link Actions}:egg:灵魂出窍,视频分裂,动感光波,幻觉 */ public class ActionEntity extends BaseEffectEntity { public Actions action; public ActionEntity() { } protected ActionEntity(Parcel in) { super(in); action = Actions.parseActions(in.readInt()); } public static final Creator<ActionEntity> CREATOR = new Creator<ActionEntity>() { @Override public ActionEntity createFromParcel(Parcel in) { return new ActionEntity(in); } @Override public ActionEntity[] newArray(int size) { return new ActionEntity[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); if (action != null) dest.writeInt(action.ordinal()); } }
true
9c9f7b73b91ce8f2fdd8ed1f7aeb39b38c3c7890
Java
suevip/orgwalkerljl-db
/orgwalkerljl-db-core/src/main/java/org/walkerljl/db/orm/entity/Database.java
UTF-8
1,199
2.234375
2
[]
no_license
/* * Copyright (c) 2010-2015 www.walkerljl.org All Rights Reserved. * The software source code all copyright belongs to the author, * without permission shall not be any reproduction and transmission. */ package org.walkerljl.db.orm.entity; import java.io.Serializable; import org.walkerljl.db.orm.enums.DatabaseType; /** * Database * * @author lijunlin<[email protected]> */ public class Database implements Serializable { private static final long serialVersionUID = 1L; /** 数据库类型*/ private DatabaseType type; /** 名称*/ private String name; /** 字符集*/ private String charset; /** 引擎*/ private String engine; public Database() {} public DatabaseType getType() { return type; } public void setType(DatabaseType type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCharset() { return charset; } public void setCharset(String charset) { this.charset = charset; } public String getEngine() { return engine; } public void setEngine(String engine) { this.engine = engine; } }
true
f91441e1792b0744a558c8f49ed95c1be765d7f5
Java
martinbiix/android_test_service
/src/com/test/serviceandroid/MyService.java
UTF-8
2,227
2.125
2
[]
no_license
package com.test.serviceandroid; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.IBinder; import android.widget.Toast; public class MyService extends Service{ private static MyService instance = null; public static boolean isRunning() { return instance != null; } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Toast.makeText(getApplicationContext(), "Servicio creado", Toast.LENGTH_LONG).show(); System.out.println( "Servicio creado"); instance=this; } @Override public void onDestroy() { Toast.makeText(getApplicationContext(), "Servicio destruido", Toast.LENGTH_LONG).show(); System.out.println( "Servicio destruido"); instance = null; } @Override public void onStart(Intent intent, int startid) { Toast.makeText(getApplicationContext(), "Servicio iniciado", Toast.LENGTH_LONG).show(); System.out.println( "Servicio iniciado"); lanzarNotificacion(); } void lanzarNotificacion(){ String ns = Context.NOTIFICATION_SERVICE; NotificationManager notManager = (NotificationManager) getSystemService(ns); //Configuramos la notificacion Notification notif = new Notification(android.R.drawable.ic_menu_agenda, "MyService", System.currentTimeMillis()); //Configuramos el Intent Context contexto = MyService.this; CharSequence titulo = "MyService Notification"; CharSequence descripcion = "Hora de visitar GarabatosLinux"; //Intent que se abrira al clickear la notificacion Intent resultIntent =new Intent(Intent.ACTION_VIEW, Uri.parse("http://garabatoslinux.net"));; PendingIntent contIntent = PendingIntent.getActivity(contexto, 0, resultIntent, 0); notif.setLatestEventInfo(contexto, titulo, descripcion, contIntent); notif.flags |= Notification.FLAG_AUTO_CANCEL; notif.defaults |= Notification.DEFAULT_VIBRATE; notManager.notify(1, notif); } }
true
d7f80118d14aa6b00d332183882b068e08528875
Java
chang19931127/DesignMode_Learn
/src/me/modedesign/behavior/chainofresponsibily/addsalary/CommonManager.java
GB18030
563
2.609375
3
[]
no_license
package me.modedesign.behavior.chainofresponsibily.addsalary; /** * * @author 43994897 */ public class CommonManager extends Manager { public CommonManager(String name) { super(name); } @Override public void requestApplication(Request request) { if (request.getRequestType() == "" && request.getNumber() <= 2) System.out.println(String.format("%s:%s : %d ׼", name, request.getRequestContent(), request.getNumber())); else { if (superior != null) { superior.requestApplication(request); } } } }
true
112c67a95734f2cbf74f4990e3151b84179e376c
Java
Outmanlmh/Java_HDdemo
/FMaven/src/main/java/com/neuedu/web/GetCookiesServlet.java
UTF-8
1,083
2.609375
3
[]
no_license
package com.neuedu.web; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author LiMingHang * @date2019.03.06 23:05. */ @WebServlet("/user/getcookie.do") public class GetCookiesServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie[] cookies = req.getCookies(); for (Cookie c:cookies ) { System.out.println(c.getName() + c.getValue()); } } public static Map<String,Cookie>getCookie(Cookie[]cookies){ Map<String,Cookie>maps = new HashMap<>(); if (cookies!=null){ for (Cookie c:cookies ) { maps.put(c.getName(),c); } } return maps; } }
true
f0df7312c0f7a80880489e9578d8ed31770497e1
Java
Aconic/JavaGroupCode
/src/com/aconic/lessons/ZeroXClassWork/FrameZX.java
UTF-8
689
2.53125
3
[]
no_license
package com.aconic.lessons.ZeroXClassWork; import javax.swing.*; import java.awt.*; import java.io.IOException; public class FrameZX extends JFrame { public FrameZX() throws IOException { setTitle("Game ZeroXing"); setLayout(null); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setBounds(200, 150, 407, 600); ClientCmd cmd = new ClientCmd(); JPanel pGame = new PanelZX(); JPanel pCmd = new PanelCmd(cmd); pGame.setBounds(0, 0, 400, 250); pCmd.setBounds(0, 250, 400, 120); pCmd.setBackground(Color.DARK_GRAY); add(pGame); add(pCmd); setVisible(true); } }
true
76e61e8ce69fe669deb90dba5579fe9e57caaf17
Java
ll905310073/S2SHweb
/物业管理/property/src/com/service/WuyeServiceImpl.java
UTF-8
966
1.90625
2
[]
no_license
package com.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dao.AdminDao; import com.dao.WuyeDao; import com.model.Admin; import com.model.User; import com.model.Wuye; import com.util.Page; import com.util.Results; @Service public class WuyeServiceImpl implements WuyeService{ @Resource private WuyeDao wuyeDao; //添加 public void save(Wuye wuye) { wuyeDao.save(wuye); } //列表 public Results companylist(Page page) { return wuyeDao.Listpages(page); } //查询 public Wuye querybyid(int id) { return wuyeDao.querybyid(id); } //修改 public void update(Wuye wuye) { wuyeDao.update(wuye); } //删除 public void delete(Wuye wuye) { wuyeDao.delete(wuye); } //查询用户 public User queryuser(int uid) { return wuyeDao.queryuser(uid); } //用户物业列表 public Results userwuyelist(Page page, int id) { return wuyeDao.userwuyelist(page,id); } }
true
8e65c6d311c34f3566ca0ea45692a7c2e8935794
Java
xinwei5/autoconfig
/config-core/src/main/java/com/github/autoconf/helper/ZookeeperUtil.java
UTF-8
6,220
2.53125
3
[]
no_license
package com.github.autoconf.helper; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import java.nio.charset.Charset; import java.util.List; /** * zookeeper工具类 * Created by lirui on 2015-09-29 11:05. */ public class ZookeeperUtil { public static final Charset UTF8 = Charset.forName("UTF-8"); public static final Charset GBK = Charset.forName("GBK"); private ZookeeperUtil() { } public static String newString(byte[] data) { return newString(data, UTF8); } public static String newString(byte[] data, Charset charset) { if (data == null) { return null; } return new String(data, charset); } public static byte[] newBytes(String s) { if (s == null) { return null; } return s.getBytes(UTF8); } public static byte[] newBytes(String s, Charset charset) { if (s == null) { return null; } return s.getBytes(charset); } public static String ensure(CuratorFramework client, String path) { try { client.create().creatingParentContainersIfNeeded().forPath(path); } catch (Exception e) { throw new RuntimeException("ensure(" + path + ")", e); } return path; } public static Stat exists(CuratorFramework client, String path) { try { return client.checkExists().forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("exists(" + path + ")", e); } return null; } public static Stat exists(CuratorFramework client, String path, Watcher watcher) { try { return client.checkExists().usingWatcher(watcher).forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("exists(" + path + ")", e); } return null; } public static void create(CuratorFramework client, String path) { try { client.create().creatingParentsIfNeeded().forPath(path); } catch (Exception e) { throw new RuntimeException("create(" + path + ")", e); } } public static void create(CuratorFramework client, String path, byte[] payload) { try { client.create().creatingParentsIfNeeded().forPath(path, payload); } catch (Exception e) { throw new RuntimeException("create(" + path + ")", e); } } public static void create(CuratorFramework client, String path, byte[] payload, CreateMode mode) { try { client.create().creatingParentsIfNeeded().withMode(mode).forPath(path, payload); } catch (Exception e) { throw new RuntimeException("create(" + path + ")", e); } } public static void create(CuratorFramework client, String path, byte[] payload, CreateMode mode, List<ACL> aclList) { try { client.create().creatingParentsIfNeeded().withMode(mode).withACL(aclList).forPath(path, payload); } catch (Exception e) { throw new RuntimeException("create(" + path + ")", e); } } public static void delete(CuratorFramework client, String path) { try { client.delete().deletingChildrenIfNeeded().forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("delete(" + path + ")", e); } } public static void guaranteedDelete(CuratorFramework client, String path) { try { client.delete().guaranteed().deletingChildrenIfNeeded().forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("guaranteedDelete(" + path + ")", e); } } public static byte[] getData(CuratorFramework client, String path) { try { return client.getData().forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("getData(" + path + ")", e); } return null; } public static byte[] getData(CuratorFramework client, String path, Watcher watcher) { try { return client.getData().usingWatcher(watcher).forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("getData(" + path + ")", e); } return null; } public static List<String> getChildren(CuratorFramework client, String path) { try { return client.getChildren().forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("getChildren(" + path + ")", e); } return null; } public static List<String> getChildren(CuratorFramework client, String path, Watcher watcher) { try { return client.getChildren().usingWatcher(watcher).forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("getChildren(" + path + ")", e); } return null; } public static void setData(CuratorFramework client, String path, byte[] payload) { try { client.setData().forPath(path, payload); } catch (Exception e) { throw new RuntimeException("setData(" + path + ")", e); } } public static void setDataAsync(CuratorFramework client, String path, byte[] payload) { try { client.setData().inBackground().forPath(path, payload); } catch (Exception e) { throw new RuntimeException("setDataAsync(" + path + ")", e); } } public static List<ACL> getACL(CuratorFramework client, String path) { try { return client.getACL().forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("getACL(" + path + ")", e); } return null; } public static void setACL(CuratorFramework client, String path, List<ACL> acls) { try { client.setACL().withACL(acls).forPath(path); } catch (KeeperException.NoNodeException ignored) { } catch (Exception e) { throw new RuntimeException("setACL(" + path + ")", e); } } }
true
46a07a56a1a4a8514da927597eb4aa550e170e99
Java
imloama/ncc-dev-tools
/src/com/yingling/extensions/listener/action/RetrenchAction.java
UTF-8
1,086
2.046875
2
[ "Apache-2.0" ]
permissive
package com.yingling.extensions.listener.action; import com.intellij.openapi.ui.Messages; import com.yingling.extensions.component.NccDevSettingDlg; import com.yingling.extensions.listener.AbstractButtonAction; import com.yingling.extensions.service.NccEnvSettingService; import com.yingling.libraries.listener.RetrenchModuleListener; import org.apache.commons.lang.StringUtils; import java.awt.event.ActionEvent; /** * 精简nc home */ public class RetrenchAction extends AbstractButtonAction { public RetrenchAction(NccDevSettingDlg dlg) { super(dlg); } @Override protected void doAction(ActionEvent event, NccDevSettingDlg dlg) { if (StringUtils.isBlank(dlg.getHomeText().getText()) && StringUtils.isBlank(NccEnvSettingService.getInstance().getNcHomePath())) { dlg.getNccSetTab().setSelectedIndex(0); Messages.showMessageDialog("Please set nchome first", "tips", Messages.getInformationIcon()); return; } RetrenchModuleListener.retrench(dlg.getHomeText().getText()); } }
true
407029786ac0c9f964e1b70d0a59c09b51c3f072
Java
our-graduation-project/bookmanager
/src/main/java/cn/hnist/bookmanager/controller/LabelController.java
UTF-8
3,500
2.265625
2
[]
no_license
package cn.hnist.bookmanager.controller; import cn.hnist.bookmanager.model.Label; import cn.hnist.bookmanager.service.LabelService; import cn.hnist.bookmanager.utils.APIResult; import com.alibaba.fastjson.JSONObject; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; /** * @author whg * @date 2019/12/11 19:47 **/ @Controller public class LabelController { @Autowired private LabelService labelService; /** * 跳入labellist页面 * @param page * @param limit * @return */ @RequestMapping("/toLabelList") public ModelAndView toLabelList(@RequestParam(value = "page" ,defaultValue = "0") int page, @RequestParam(value = "limit", defaultValue = "10") int limit){ System.out.println("page = " + page); System.out.println("limit = " + limit); PageInfo pageInfo = labelService.queryLabelByPage(page, limit); ModelAndView modelAndView = new ModelAndView("admin/labellist"); modelAndView.addObject( "pageInfo", pageInfo); return modelAndView; } /** * 跳入修改页面 * @param labelId * @return */ @RequestMapping("/toEditLabel") public ModelAndView toEditLabel(@RequestParam("labelId") int labelId){ Label label = labelService.selectLabelNameById(labelId); ModelAndView modelAndView = new ModelAndView("admin/labeledit"); modelAndView.addObject("label",label); return modelAndView; } /** * 修改标签信息 * @param label * @return */ @RequestMapping("/admin/editLabel") @ResponseBody public APIResult editLabel(@RequestBody Label label){ System.out.println("come in editLabel"); System.out.println("label = " + label); if(label == null || label.getLabelId() == null || label.getLabelName() == null){ return new APIResult("参数有误",false,400); } Integer id = labelService.selectLabelIdByName(label.getLabelName()); if(id != null && id > 0){ return new APIResult("此标签名已存在", false, 500); } Boolean aBoolean = labelService.updateLabel(label.getLabelId(),label.getLabelName()); return new APIResult(aBoolean,200); } @RequestMapping("/deleteLabel") @ResponseBody public APIResult deleteLabel(@RequestBody JSONObject jsonParam, HttpServletResponse response){ Boolean aBoolean = labelService.deleteLabel((Integer) jsonParam.get("labelId")); return new APIResult(aBoolean,200); } @RequestMapping("/admin/addLabel") @ResponseBody public APIResult addLabel(@RequestBody Label label){ if(label == null || label.getLabelName() == null){ return new APIResult("参数有误",false,400); } Boolean aBoolean = labelService.addLabel(label); return new APIResult(aBoolean,200); } }
true
0f34f8d1ac0b4cca899559fab0bf18359a6bc43c
Java
Rinze-ady/psikyo
/src/role/GirlBullet.java
UTF-8
1,087
3.046875
3
[]
no_license
package role; import frame.GameStartFrame; import roleEnemy.EnemyRole; import java.awt.*; /** * 女孩子弹类 */ public class GirlBullet extends BaseRole{ /**子弹图像*/ public static Image girlBulletImage; /** * 角色构造方法 * */ public GirlBullet() { super(GameStartFrame.girl.x + 10, GameStartFrame.girl.y + 10, 65, 15); this.roleImage = girlBulletImage; } @Override public void move() { this.x += 15; for (int i = 0; i < GameStartFrame.roleList.size(); i++){ BaseRole role = GameStartFrame.roleList.get(i); if (this.rect.intersects(role.rect)){ if (role instanceof EnemyRole){//子弹击中怪物 EnemyRole enemy = (EnemyRole) role; enemy.byHit(15); GameStartFrame.roleList.remove(this);//移除子弹对象 GameStartFrame.roleList.add(new Blast(this.x - 30, this.y)); } } } } }
true
bfdcfa1fb7dd18da36f7775c7942b3f9a9c44f6b
Java
shweta1122/Nagarro-Hybris-Training
/trainingfacades/src/com/nagarro/facades/populators/ProductDetailsPopulator.java
UTF-8
1,158
1.796875
2
[]
no_license
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. */ package com.nagarro.facades.populators; import de.hybris.platform.commercefacades.product.data.ProductData; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.enums.Gender; import de.hybris.platform.core.model.product.ProductModel; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import de.hybris.platform.servicelayer.dto.converter.Converter; import de.hybris.platform.variants.model.VariantProductModel; import com.nagarro.core.model.ApparelProductModel; import com.nagarro.facades.product.data.GenderData; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Required; /** * Populates {@link ProductData} with genders */ public class ProductDetailsPopulator implements Populator<ProductModel, ProductData> { @Override public void populate(final ProductModel source, final ProductData target) throws ConversionException { target.setWrapAvailable(source.getWrapAvailable()); } }
true
5618cd2d7fa2d1c78a51641d189144cb9a2b7438
Java
17639101203/zhiliao_hotel_applets_api
/src/main/java/com/zhiliao/hotel/service/ZlInvoiceService.java
UTF-8
2,031
1.757813
2
[]
no_license
package com.zhiliao.hotel.service; import com.zhiliao.hotel.common.PageInfoResult; import com.zhiliao.hotel.controller.invoice.params.InvoiceOrderVO; import com.zhiliao.hotel.controller.invoice.vo.InvoiceOrderToPhpVO; import com.zhiliao.hotel.controller.myAppointment.dto.InvoiceOrderDTO; import com.zhiliao.hotel.model.ZlInvoice; import com.zhiliao.hotel.model.ZlInvoiceOrder; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; public interface ZlInvoiceService { /** * 新增发票 * * @param Invoice 发票对象 */ Map<String, Object> addInvoice(ZlInvoice Invoice); /*** * 根据用户查询发票信息 * @param userid 用户ID * @return 发票对象集合 */ PageInfoResult<List<Map<String, Object>>> queryByUserID(Long userid, Integer pageNo, Integer pageSize); /** * 根据用户ID,发票删除发票抬头 * * @param invoiceid 发票ID */ void deleteInvoice(Integer invoiceid); /** * 查询发票详情 * * @param userid * @param invoiceid * @return */ Map<String, Object> findinvoicedetails(Long userid, Integer invoiceid); /** * 根据酒店ID查询开票二维码 * * @param hotelid * @return */ String findInvoiceQrCodeUrl(Integer hotelid); /** * 增加发票订单 * * @param zlInvoiceOrder */ void addinvoiceOrder(ZlInvoiceOrder zlInvoiceOrder); /** * 修改开票信息 * * @param zlInvoice */ void changeInvoice(ZlInvoice zlInvoice); /** * 查询开票订单详情 * * @param invoiceorderid * @return */ InvoiceOrderDTO findInvoiceOrderdetail(Long invoiceorderid); /** * 取消开票预约 * * @param invoiceorderid */ void cancelInvoiceOrder(Long invoiceorderid); void deleteInvoiceOrder(Long invoiceorderid); InvoiceOrderToPhpVO selectToPhp(Long invoiceorderid); }
true
24a426ade5c3a027c6ef5c7094f4c9f30a93c07b
Java
Moyuchen/WeiTitle
/app/src/main/java/com/bwie/test/Adapter/recycleAdapter.java
UTF-8
2,435
2.421875
2
[]
no_license
package com.bwie.test.Adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import com.bwie.test.Bean.NewsType; import com.bwie.test.R; import java.util.List; /** * User: 张亚博 * Date: 2017-09-05 14:33 * Description: */ public class recycleAdapter extends RecyclerView.Adapter<recycleAdapter.MyViewHolder> { private Context context; private List<NewsType> list; private OnRecycleViewItemClickedListener OnRecycleViewItemClickListener; public recycleAdapter(Context context, List<NewsType> list) { this.context = context; this.list = list; } /** * 创建viewholder,和view绑定 * @param parent * @param viewType * @return */ @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(context, R.layout.recycle_item, null); MyViewHolder myholder=new MyViewHolder(view); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { OnRecycleViewItemClickListener.onRecycleViewItem((Integer) view.getTag(),view); } }); return myholder; } /** * 处理逻辑 * @param holder * @param position */ @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.recy_tv.setText(list.get(position).newstype); holder.itemView.setTag(position); } @Override public int getItemCount() { return list.size(); } class MyViewHolder extends RecyclerView.ViewHolder { private final TextView recy_tv; private final CheckBox recy_checkb; public MyViewHolder(View itemView) { super(itemView); recy_tv = itemView.findViewById(R.id.recy_tv); recy_checkb = itemView.findViewById(R.id.recy_checkb); } } public void setOnRecycleViewItemClickListener(OnRecycleViewItemClickedListener onRecycleViewItemClickListener) { this.OnRecycleViewItemClickListener = onRecycleViewItemClickListener; } /* 自定义的回调接口 */ public interface OnRecycleViewItemClickedListener{ void onRecycleViewItem(int positon,View view); } }
true
bbfcc422b7f9f9f219229b01e203245a0af79417
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_00c63869d1ad8177374aa516c751d98ab80238a5/Space/2_00c63869d1ad8177374aa516c751d98ab80238a5_Space_s.java
UTF-8
4,925
3.21875
3
[]
no_license
package org.newdawn.slick.util.pathfinding.navmesh; import java.util.HashMap; /** * A quad space within a navigation mesh * * @author kevin */ public class Space { /** The x coordinate of the top corner of the space */ private float x; /** The y coordinate of the top corner of the space */ private float y; /** The width of the space */ private float width; /** The height of the space */ private float height; /** A map from spaces to the links that connect them to this space */ private HashMap links = new HashMap(); /** * Create a new space * * @param x The x coordinate of the top corner of the space * @param y The y coordinate of the top corner of the space * @param width The width of the space * @param height The height of the space */ public Space(float x, float y, float width, float height) { this.x = x; this.y = y; this.width = width; this.height = height; } /** * Get the width of the space * * @return The width of the space */ public float getWidth() { return width; } /** * Get the height of the space * * @return The height of the space */ public float getHeight() { return height; } /** * Get the x coordinate of the top corner of the space * * @return The x coordinate of the top corner of the space */ public float getX() { return x; } /** * Get the y coordinate of the top corner of the space * * @return The y coordinate of the top corner of the space */ public float getY() { return y; } /** * Link this space to another by creating a link and finding the point * at which the spaces link up * * @param other The other space to link to */ public void link(Space other) { // aligned vertical edges if ((x == other.x+other.width) || (x+width == other.x)) { float linkx = x; if (x+width == other.x) { linkx = x+width; } float top = Math.max(y, other.y); float bottom = Math.min(y+height, other.y+other.height); float linky = top + ((bottom-top)/2); links.put(other, new Link(linkx, linky, other)); } // aligned horizontal edges if ((y == other.y+other.height) || (y+height == other.y)) { float linky = y; if (y+height == other.y) { linky = y+height; } float left = Math.max(x, other.x); float right = Math.min(x+width, other.x+other.width); float linkx = left + ((right-left)/2); links.put(other, new Link(linkx, linky, other)); } } /** * Check if this space has an edge that is joined with another * * @param other The other space to check against * @return True if the spaces have a shared edge */ public boolean hasJoinedEdge(Space other) { // aligned vertical edges if ((x == other.x+other.width) || (x+width == other.x)) { if ((y >= other.y) && (y <= other.y + other.height)) { return true; } if ((y+height >= other.y) && (y+height <= other.y + other.height)) { return true; } } // aligned horizontal edges if ((y == other.y+other.height) || (y+height == other.y)) { if ((x >= other.x) && (x <= other.x + other.width)) { return true; } if ((x+width >= other.x) && (x+width <= other.x + other.width)) { return true; } } return false; } /** * Merge this space with another * * @param other The other space to merge with * @return The result space created by joining the two */ public Space merge(Space other) { float minx = Math.min(x, other.x); float miny = Math.min(y, other.y); return new Space(minx, miny, width+other.width, height+other.height); } /** * Check if the given space can be merged with this one. It must have * an adjacent edge and have the same height or width as this space. * * @param other The other space to be considered * @return True if the spaces can be joined together */ public boolean canMerge(Space other) { if (!hasJoinedEdge(other)) { return false; } if ((x == other.x) && (width == other.width)) { return true; } if ((y == other.y) && (height == other.height)) { return true; } return false; } /** * A link between this space and another * * @author kevin */ public class Link { /** The x coodinate of the joining point */ private float px; /** The y coordinate of the joining point */ private float py; /** The target space we'd be linking to */ private Space target; /** * Create a new link * * @param px The x coordinate of the linking point * @param py The y coordinate of the linking point * @param target The target space we're linking to */ public Link(float px, float py, Space target) { this.px = px; this.py = py; this.target = target; } } }
true
a1d15153558ce711b117a3b28897ff3bab3ca28a
Java
bbbar326/sample
/sample/src/main/java/science/bbbar326/scraping/App2.java
UTF-8
605
2.421875
2
[]
no_license
package science.bbbar326.scraping; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class App2 { public static void main(String[] args) throws Exception { Document document = Jsoup.connect("https://www.google.co.jp/search?q=沖縄 高級ホテル").get(); Elements elements = document.select("h3 a"); for (Element element : elements) { System.out.println("<<< " + element.text() + " >>>"); System.out.println(element.attr("href")); System.out.println("---------------"); } } }
true
640bd15f6335a2e93871709a8b998f78ecd5b842
Java
Sykoh-dev/LaboG_E
/src/main/java/MedicalAppointment/demo/modelsform/PatientCreateForm.java
UTF-8
903
2.40625
2
[]
no_license
package MedicalAppointment.demo.modelsform; import MedicalAppointment.demo.dataAccess.entity.Patient; import lombok.*; import org.hibernate.validator.constraints.Length; import org.springframework.validation.annotation.Validated; @Validated @Data public class PatientCreateForm { @Length(min = 2, max = 25) private String name; @Length(min = 2, max = 25) private String surname; @Length(min = 2, max = 25) private String adress; @Length(min = 2, max = 25) private String mail; @Length(min = 2, max = 25) private String dateOfBirth; public Patient mapToPatient() { Patient patient = new Patient(); patient.setId(0L); patient.setName(name); patient.setSurname(surname); patient.setAdress(adress); patient.setMail(mail); patient.setDateOfBirth(dateOfBirth); return patient; } }
true
3cb452e6016aa467c355d7ed55122c3cf23adf90
Java
djin/Tumpi
/tumpiApp/src/app/tumpi/servidor/conexion/SocketServidor.java
UTF-8
5,008
2.359375
2
[]
no_license
package app.tumpi.servidor.conexion; import android.os.AsyncTask; import android.util.Log; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.concurrent.TimeUnit; /** * * @author 66785270 */ public class SocketServidor { private Socket socket_server = null; // private InetAddress ip_server=InetAddress.getLocalHost(); // private int puerto=0; // private ThreadBuscarClientes thread_buscar_clientes=null; private DataInputStream input = null; private DataOutputStream output = null; // private ArrayList<Cliente> clientes=new ArrayList(); private ArrayList<String> clientes = new ArrayList(); private String nick = ""; private Thread thread_server; private ArrayList<ServerSocketListener> listeners = new ArrayList(); public SocketServidor(String ip, int port) throws IOException { // puerto=port; socket_server = new Socket(ip, port); if (socket_server.isConnected()) { input = new DataInputStream(socket_server.getInputStream()); output = new DataOutputStream(socket_server.getOutputStream()); } } public boolean isBound() { return socket_server.isBound(); } // public void startSearchClients(){ // thread_buscar_clientes=new ThreadBuscarClientes(); // thread_buscar_clientes.execute(); // } // public void finishSearchClients(){ // thread_buscar_clientes.cancel(true); // } public void enviarMensajeServer(String id_cliente, String mensaje) throws IOException { try { output.writeUTF("c:" + id_cliente + "|" + mensaje); } catch (IOException ex) { System.out.println("Error al enviar el mensaje al bridge: " + ex.toString()); } } public int getClientsCount() { return clientes.size(); } public boolean logIn(final String nick, final String uuid) throws Exception { AsyncTask<Void, Void, Boolean> thread_log = new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { try { output.writeUTF("s:log|" + nick + "|" + uuid); String resp = input.readUTF(); Log.i("Conexion", "Server: " + resp); if ("b:log|1".equals(resp)) { SocketServidor.this.nick = nick; return true; } return false; } catch (IOException ex) { Log.e("Conexion", "Error al mandar peticion login: " + ex.toString()); return false; } } }; return thread_log.execute().get(5, TimeUnit.SECONDS); } private void mensajeRecivido(String mensaje) { if ("b".equals(mensaje.split("\\:")[0])) { String tipo = mensaje.substring(mensaje.indexOf(":") + 1, mensaje.indexOf("|")); Log.i("Conexion", "Bridge: " + mensaje); if ("client_on".equals(tipo)) { clientes.add(mensaje.substring(mensaje.indexOf("|") + 1)); final String clientUUID = mensaje .substring(mensaje.indexOf("|") + 1); fireClientConnectedEvent(clientUUID); } else if ("client_off".equals(tipo)) { String id_cliente = mensaje.substring(mensaje.indexOf("|") + 1); clientes.remove(id_cliente); fireClientDisconnectedEvent(id_cliente); } } else { String id_cliente = mensaje.substring(0, mensaje.indexOf("|")); mensaje = mensaje.substring(mensaje.indexOf("|") + 1); fireMessageReceivedEvent(id_cliente, mensaje); } } public void startListenBridge() { thread_server = new Thread() { @Override public void run() { while (thread_server != null && socket_server.isConnected()) { String mensaje = ""; try { mensaje = input.readUTF(); mensajeRecivido(mensaje); } catch (IOException ex) { try { closeSocket(); fireMessageReceivedEvent("", "exit"); } catch (IOException ex1) { Log.e("Conexion", "Error al cerrar la conexion con el bridge: " + ex); } thread_server = null; } } } }; thread_server.start(); } public void closeSocket() throws IOException { // finishSearchClients(); // for(Cliente cliente : clientes){ // cliente.enviarMensaje("exit"); // cliente.finishListenClient(); // } if (!socket_server.isClosed()) { output.writeUTF("s:exit"); thread_server = null; socket_server.close(); } } public void addServerSocketListener(ServerSocketListener listener) { listeners.add(listener); } public void removeServerSocketListener(ServerSocketListener listener) { listeners.remove(listener); } public void fireClientConnectedEvent(String uuid) { for (ServerSocketListener listener : listeners) { listener.onClientConnected(uuid); } } public void fireClientDisconnectedEvent(String id) { for (ServerSocketListener listener : listeners) { listener.onClientDisconnected(id); } } public void fireMessageReceivedEvent(String id, String message) { for (ServerSocketListener listener : listeners) { listener.onMessageReceived(id, message); } } }
true
78eaf21bccb3c7ffc5e59ffb1c87be929ac9cb60
Java
premkumartak/SpringDemo
/src/main/java/com/example/demo/PersonRowMapper.java
UTF-8
573
2.46875
2
[]
no_license
package com.example.demo; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.example.model.User; public class PersonRowMapper implements RowMapper<User> { public User mapRow(ResultSet resultSet, int arg1) throws SQLException { User person = new User(); person.setFirst_name(resultSet.getString(1)); person.setLast_name(resultSet.getString(2)); person.setEmail(resultSet.getString(3)); person.setPassword(resultSet.getString(4)); return person; } }
true
d39b7ca40d94ce5a393abf1306d349870f707c49
Java
dafrito/Riviera
/src/script/proxies/FauxTemplate_Scenario.java
UTF-8
5,334
2.375
2
[]
no_license
package script.proxies; import java.util.Collections; import java.util.LinkedList; import java.util.List; import asset.Scenario; import asset.Terrestrial; import inspect.Inspectable; import logging.Logs; import script.Conversions; import script.ScriptConvertible; import script.ScriptEnvironment; import script.exceptions.ScriptException; import script.parsing.Referenced; import script.parsing.ScriptKeywordType; import script.values.RiffScriptFunction; import script.values.ScriptTemplate; import script.values.ScriptTemplate_Abstract; import script.values.ScriptValue; import script.values.ScriptValueType; import script.values.ScriptValue_Faux; @Inspectable public class FauxTemplate_Scenario extends FauxTemplate implements ScriptConvertible<Scenario> { public static final String SCENARIOSTRING = "Scenario"; private Scenario scenario; public FauxTemplate_Scenario(ScriptEnvironment env) { super(env, ScriptValueType.createType(env, SCENARIOSTRING), ScriptValueType.getObjectType(env), new LinkedList<ScriptValueType>(), false); } public FauxTemplate_Scenario(ScriptEnvironment env, ScriptValueType type) { super(env, type); this.scenario = new Scenario(env, new Terrestrial(1)); } @Override public Scenario convert(ScriptEnvironment env) { return this.scenario; } // Function bodies are contained via a series of if statements in execute // Template will be null if the object is exactly of this type and is constructing, and thus must be created then @Override public ScriptValue execute(Referenced ref, String name, List<ScriptValue> params, ScriptTemplate_Abstract rawTemplate) throws ScriptException { assert Logs.openNode("Faux Template Executions", "Executing scenario faux template function (" + RiffScriptFunction.getDisplayableFunctionName(name) + ")"); FauxTemplate_Scenario template = (FauxTemplate_Scenario) rawTemplate; ScriptValue returning; assert Logs.addSnapNode("Template provided", template); assert Logs.addSnapNode("Parameters provided", params); if (name == null || name.equals("")) { if (template == null) { template = (FauxTemplate_Scenario) this.createObject(ref, template); } switch (params.size()) { case 1: template.getScenario().setTerrestrial(Conversions.getTerrestrial(this.getEnvironment(), params.get(0))); case 0: assert Logs.closeNode(); return template; } } else if (name.equals("getTerrestrial")) { returning = Conversions.wrapTerrestrial(ref.getEnvironment(), template.getScenario().getTerrestrial()); assert Logs.closeNode(); return returning; } else if (name.equals("setTerrestrial")) { template.getScenario().setTerrestrial(Conversions.getTerrestrial(this.getEnvironment(), params.get(0))); assert Logs.closeNode(); return null; } else if (name.equals("getScheduler")) { returning = Conversions.wrapScheduler(this.getEnvironment(), template.getScenario().getScheduler()); assert Logs.closeNode(); return returning; } returning = this.getExtendedFauxClass().execute(ref, name, params, template); assert Logs.closeNode(); return returning; } @Inspectable public Scenario getScenario() { return this.scenario; } // addFauxFunction(name,ScriptValueType type,List<ScriptValue_Abstract>params,ScriptKeywordType permission,boolean isAbstract) // All functions must be defined here. All function bodies are defined in 'execute'. @Override public void initialize() throws ScriptException { assert Logs.openNode("Faux Template Initializations", "Initializing scenario faux template"); this.addConstructor(this.getType()); List<ScriptValue> fxnParams = new LinkedList<ScriptValue>(); fxnParams.add(new ScriptValue_Faux(this.getEnvironment(), ScriptValueType.createType(this.getEnvironment(), FauxTemplate_Terrestrial.TERRESTRIALSTRING))); this.addConstructor(this.getType(), fxnParams); this.disableFullCreation(); this.getExtendedClass().initialize(); this.addFauxFunction("getName", ScriptValueType.STRING, Collections.<ScriptValue> emptyList(), ScriptKeywordType.PUBLIC, false, false); fxnParams = new LinkedList<ScriptValue>(); fxnParams.add(new ScriptValue_Faux(this.getEnvironment(), ScriptValueType.STRING)); this.addFauxFunction("setName", ScriptValueType.VOID, fxnParams, ScriptKeywordType.PUBLIC, false, false); this.addFauxFunction("getTerrestrial", ScriptValueType.createType(this.getEnvironment(), FauxTemplate_Terrestrial.TERRESTRIALSTRING), Collections.<ScriptValue> emptyList(), ScriptKeywordType.PUBLIC, false, false); fxnParams = new LinkedList<ScriptValue>(); fxnParams.add(new ScriptValue_Faux(this.getEnvironment(), ScriptValueType.createType(this.getEnvironment(), FauxTemplate_Terrestrial.TERRESTRIALSTRING))); this.addFauxFunction("setTerrestrial", ScriptValueType.VOID, fxnParams, ScriptKeywordType.PUBLIC, false, false); this.addFauxFunction("getScheduler", ScriptValueType.createType(this.getEnvironment(), FauxTemplate_Scheduler.SCHEDULERSTRING), Collections.<ScriptValue> emptyList(), ScriptKeywordType.PUBLIC, false, false); assert Logs.closeNode(); } // Define default constructor here @Override public ScriptTemplate instantiateTemplate() { return new FauxTemplate_Scenario(this.getEnvironment(), this.getType()); } public void setScenario(Scenario scenario) { this.scenario = scenario; } }
true
7a2c4e50def7b49acce11b08005a72adbcbb69d7
Java
zhongxingyu/Seer
/Diff-Raw-Data/17/17_9af7143493ec5ea2c5037ac13dfa03eaf79eb353/MainActivity/17_9af7143493ec5ea2c5037ac13dfa03eaf79eb353_MainActivity_s.java
UTF-8
3,991
1.828125
2
[]
no_license
package ovgu.gruppe1.ehskapp; import java.io.FileNotFoundException; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getBaseContext()); String usercode = preferences.getString("usercode", ""); Editor edit = preferences.edit(); if (usercode.length() != 0) { String data = usercode + ".csv"; if (true) { edit.clear(); edit.commit(); } } if (usercode.length() == 0) { Intent popupIntent = new Intent(this, UserCodeActivity.class); startActivity(popupIntent); } Button btn_usercode = (Button) findViewById(R.id.btn_usercode); btn_usercode.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent popupIntent = new Intent(MainActivity.this, UserCodeActivity.class); startActivity(popupIntent); } }); Button btn_preferences = (Button) findViewById(R.id.btn_preferences); btn_preferences.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /*String[] str1 = { "Code", "Datum", "Alarmzeit", "Antwortzeit", "Abbruch", "Kontakte", "Stunden", "Minuten" }; String[] str2 = { "lbrht", "22.06.2013", "21:23", "21:24", "0", "0", "0", "0" }; try { CSVWriter.writeLine(str1, Environment.getExternalStorageDirectory().getPath()+"/Probandencode.csv"); CSVWriter.writeLine(str2, Environment.getExternalStorageDirectory().getPath()+"/Probandencode.csv"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Toast.makeText(getApplicationContext(), "External SD card not mounted", Toast.LENGTH_LONG).show(); e.printStackTrace(); }*/ // // Intent intent = new Intent(MainActivity.this, // QuickPrefsActivity.class); // startActivity(intent); } }); Button btn_popup = (Button) findViewById(R.id.btn_popup); btn_popup.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent popupIntent = new Intent(MainActivity.this, TimeChooserActivity.class); startActivity(popupIntent); } }); Button btn_questions = (Button) findViewById(R.id.btn_questions); btn_questions.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent popupIntent = new Intent(MainActivity.this, QuestionsActivity.class); startActivity(popupIntent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } /*public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menuitem_preferences: Intent intentPreferences = new Intent(MainActivity.this, QuickPrefsActivity.class); startActivity(intentPreferences); return true; case R.id.menuitem_popup: Intent intentPopup = new Intent(MainActivity.this, PopupActivity.class); startActivity(intentPopup); return true; } return super.onOptionsItemSelected(item); } */ }
true
b3c63bebd02c6af11e4960aa0ffc6c73a0589174
Java
shishanksingh2015/movie
/app/src/main/java/com/shishank/android/BasePresenter.java
UTF-8
324
1.820313
2
[ "Apache-2.0" ]
permissive
package com.shishank.android; import com.shishank.android.api.ApiService; import javax.inject.Inject; /** * @author shishank */ public class BasePresenter { @Inject protected ApiService apiService; protected BasePresenter() { BaseApplication.getInstance().getApiComponent().inject(this); } }
true
63cdfe3550d22e815a1b2940477bd7f2c08919ae
Java
cshuig/rosette
/src/main/java/se/leafcoders/rosette/controller/ResourceTypeController.java
UTF-8
2,464
2.21875
2
[]
no_license
package se.leafcoders.rosette.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import se.leafcoders.rosette.model.resource.ResourceType; import se.leafcoders.rosette.service.ResourceTypeService; @Controller public class ResourceTypeController extends AbstractController { @Autowired private ResourceTypeService resourceTypeService; @RequestMapping(value = "resourceTypes/{key}", method = RequestMethod.GET, produces = "application/json") @ResponseBody public ResourceType getResourceType(@PathVariable String key) { return resourceTypeService.read(key); } @RequestMapping(value = "resourceTypes", method = RequestMethod.GET, produces = "application/json") @ResponseBody public List<ResourceType> getResourceTypes(@RequestParam(value = "groupId", required = false) String groupId, HttpServletRequest request, HttpServletResponse response) { Query query = new Query().with(new Sort(new Sort.Order(Sort.Direction.ASC, "name"))); return resourceTypeService.readMany(query); } // ResourceType must contain the attribute 'type' that equals any string specified in ResourceType @RequestMapping(value = "resourceTypes", method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @ResponseBody public ResourceType postResourceType(@RequestBody ResourceType resourceType, HttpServletResponse response) { return resourceTypeService.create(resourceType, response); } // ResourceType must contain the attribute 'type' that equals any string specified in ResourceType @RequestMapping(value = "resourceTypes/{key}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json") public void putResourceType(@PathVariable String key, @RequestBody ResourceType resourceType, HttpServletResponse response) { resourceTypeService.update(key, resourceType, response); } @RequestMapping(value = "resourceTypes/{key}", method = RequestMethod.DELETE, produces = "application/json") public void deleteResourceType(@PathVariable String key, HttpServletResponse response) { resourceTypeService.delete(key, response); } }
true
f741a56cf35286ef24dd45be9a3ce75ae7f57799
Java
767455399/ClownFish
/app/src/main/java/com/example/administrator/clownfish/Car.java
UTF-8
555
2.671875
3
[]
no_license
package com.example.administrator.clownfish; /** * 项目名称:ClownFish * 类描述: * 创建人:WangQing * 创建时间:2016/5/23 14:18 * 修改人:WangQing * 修改时间:2016/5/23 14:18 * 修改备注: */ public class Car { private String carColor; private static Car car = new Car(); private Car(){}; public static Car getCar(){ return car; } public void setCarColor(String color){ this.carColor=color; } public void getCarColor(){ this.carColor=carColor; } }
true
1bdd1c1f3d387c2718182b93966d58c3adf101a0
Java
roflinasuha/250663-STIW3054-A182-A1
/src/CalculateEffort.java
UTF-8
637
2.5
2
[]
no_license
public class CalculateEffort { public static double ManHours1(double UCP) { double ucp = UCP; double er1 =20; double manHours1 = ucp * er1; return manHours1; } public static double ManHours2(double UCP) { double ucp = UCP; double er2 =28; double manHours2 = ucp * er2; return manHours2; } public static double adjustManHour(double ManHours2) { double manH = ManHours2 ; double adjust = (1.0 + 05/100)* manH ; return adjust; } public static double Report(double adjustManHour) { double adj= adjustManHour ; double report = adj + 940; return report; } }
true
c8358af1b3c9491a3ec6650075f627753606e1bf
Java
RyanTech/NagaRepos
/src/jp/co/rakuten/android/basket/common/util/StringValidator.java
UTF-8
2,029
3.15625
3
[ "Apache-2.0" ]
permissive
package jp.co.rakuten.android.basket.common.util; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author ts-nana.furuike * */ public class StringValidator { /** * 数値のみの値かチェックします。 * * @param value * 検査値 * @return true 数値のみ false 数値以外の値がある */ public static boolean isOnlyNumeric(String value) { if (StringUtils.isEmpty(value)){ return true; }else{ return patternMatcher(value, "[0-9]*"); } } /** * 指定された値が指定されたパターンと一致するかチェックします。 * * @param value * 検査値 * @param patternStr * 指定パターン * @return true 一致する false 一致しない */ private static boolean patternMatcher(String value, String patternStr) { Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(value); return matcher.matches(); } /** * 文字列のみの値かチェックします。 * * @param value * 検査値 * @return true 機種依存文字を含む false 機種依存文字を含まない */ public static boolean containsOutOfRangeCharacter(String value) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < value.length(); i++) { sb.append(String.format("\\u%04X", Character.codePointAt(value, i))); } String test = sb.toString(); if (StringUtils.isEmpty(test)){ return false; } for (int i = 0; i < test.length(); i++){ if (isOutOfRangeCharactor(test.charAt(i)) == true){ return true; } } return false; } /** * 指定文字が機種依存文字か否かを返します。 * * @param c * 検査文字 * @return true 機種依存文字 false 通常文字 */ private static boolean isOutOfRangeCharactor(char c) { return c == '\uFFFD'; } }
true
3983966a53227cd8f54d95150b8d42aaa2058eb0
Java
HyesungKo/CmpE133
/src/main/Main.java
UTF-8
1,463
2.59375
3
[]
no_license
package main; /** * * @author David */ import javafx.application.Application; import javafx.application.Platform; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.WindowEvent; public class Main extends Application { public static final int PREF_WIDTH = 550; public static final int PREF_HEIGHT = 350; public static final int MIN_WIDTH = 300; public static final int MIN_HEIGHT = 350; public static final double OPACITY = 1; public static final String APP_TITLE = "CarPool System"; public static void main(String[] args) { launch(args); int a; } @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle(APP_TITLE); primaryStage.setOpacity(OPACITY); primaryStage.setMinWidth(MIN_WIDTH); primaryStage.setMinHeight(MIN_HEIGHT); primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent t) { Platform.exit(); System.exit(0); } }); Parent root = FXMLLoader.load(getClass().getResource("/view/LoginScene.fxml")); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); } }
true
31b7fe8c3d5fc84dcfa1cf33702b30549e54e6fd
Java
MLogica/Spring-Repository
/MusicStoreForm/src/main/java/aish/vaishno/musicstoreform/service/IMusicService.java
UTF-8
277
1.75
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package aish.vaishno.musicstoreform.service; /** * * @author Aishu */ public interface IMusicService { String play(); String pause(); String stop(); }
true
6b012f6fbb6a1373d8f585c60dfe788d44789f0a
Java
tharakadileepa/Hibernate-project
/src/lk/udarabattery/newproj/business/custom/impl/OrderBOimpl.java
UTF-8
3,762
2.234375
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 lk.udarabattery.newproj.business.custom.impl; import java.math.BigDecimal; import java.sql.Connection; import lk.udarabattery.newproj.buisness.custom.OrderBO; import lk.udarabattery.newproj.dao.DAOFactory; import lk.udarabattery.newproj.dao.custom.BuyingOrderDAO; import lk.udarabattery.newproj.dao.custom.BuyingOrderDetailDAO; import lk.udarabattery.newproj.dao.custom.CustomerDAO; import lk.udarabattery.newproj.database.DBconnection; import lk.udarabattery.newproj.database.HibernateUtil; import lk.udarabattery.newproj.dto.BuyingOrderDTO; import lk.udarabattery.newproj.dto.BuyingOrderDetailDTO; import lk.udarabattery.newproj.entity.BuyingOrder; import lk.udarabattery.newproj.entity.BuyingOrderDetail; import lk.udarabattery.newproj.entity.Customer; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; /** * * @author THARAKA */ public class OrderBOimpl implements OrderBO { private BuyingOrderDAO buyingOrderDAO; private BuyingOrderDetailDAO buyingOrderDetailDAO; private CustomerDAO customerDAO; private SessionFactory sessionFactory; public OrderBOimpl() { this.buyingOrderDAO= (BuyingOrderDAO) DAOFactory.getInstance().getDAO(DAOFactory.DAOTypes.BUYINGORDER); this.buyingOrderDetailDAO= (BuyingOrderDetailDAO) DAOFactory.getInstance().getDAO(DAOFactory.DAOTypes.BUYINGORDERDETAIL); this.customerDAO= (CustomerDAO) DAOFactory.getInstance().getDAO(DAOFactory.DAOTypes.CUSTOMER); sessionFactory = HibernateUtil.getSessionFactory(); } @Override public boolean placeorder(BuyingOrderDTO bo, BuyingOrderDetailDTO bod) throws Exception { try (Session session=sessionFactory.openSession()){ buyingOrderDAO.setSession(session); buyingOrderDetailDAO.setSession(session); customerDAO.setSession(session); session.beginTransaction(); Customer customer = customerDAO.findID(bo.getCusid()); BuyingOrder buyingOrder=new BuyingOrder(bo.getOrdid(),bo.getOrddate(),customer); buyingOrderDAO.save(buyingOrder); BuyingOrderDetail buyingOrderDetail = new BuyingOrderDetail(bod.getBcode(),bod.getOrdid(),bod.getBprice()); buyingOrderDetailDAO.save(buyingOrderDetail); session.getTransaction().commit(); return true; }/*catch ( HibernateException exp){ return false; }*/ // Connection con=null; // try{ // con = DBconnection.getInstance().getConnection(); // con.setAutoCommit(false); // BuyingOrderDTO bb=new BuyingOrderDTO(bo.getOrdid(), bo.getCusid(), bo.getOrddate()); // boolean result1 = bOImpl.saveBuyingOrder(bb); // // if (result1 == true) { // // BuyingOrderDetailDTO detailDTO=new BuyingOrderDetailDTO(bod.getBcode(), bod.getOrdid(),bod.getBprice()); // boolean result2 = bOdImpl.saveBuyingOrderDetail(detailDTO); // // if (result2) { // con.commit(); // return true; // } // else{ // con.rollback(); // return result2; // } // // } else { // con.rollback(); // return false; // // } // // } catch (Exception e) { // con.rollback(); // throw e; // } finally { // // con.setAutoCommit(true); // // } // } }
true
696b179eeeaa0fe495509bde317fcd407c3f2a7e
Java
tejaswinisimha/HMS_Auto
/Reusables/reusableFunctions/inventory/ItemMaster.java
UTF-8
4,469
2.3125
2
[]
no_license
package reusableFunctions.inventory; import org.openqa.selenium.WebDriver; import GenericFunctions.DbFunctions; import GenericFunctions.EnvironmentSetup; import keywords.SeleniumActions; import keywords.SeleniumVerifications; import seleniumWebUIFunctions.KeywordSelectionLibrary; import seleniumWebUIFunctions.VerificationFunctions; public class ItemMaster { WebDriver driver = null; KeywordSelectionLibrary executeStep; VerificationFunctions verifications; String AutomationID; String DataSet; public ItemMaster() { } /** * Use this * @param AutomationID */ public ItemMaster(KeywordSelectionLibrary execStep,VerificationFunctions verifications){ this.executeStep = execStep; this.verifications = verifications; } public void AddItem(String lineItemId){ executeStep.performAction(SeleniumActions.Click, "","StoresAddNewItem"); verifications.verify(SeleniumVerifications.Appears, "","AddStoresItemHeader",true); EnvironmentSetup.LineItemIdForExec = lineItemId; EnvironmentSetup.lineItemCount =0; System.out.println("LineItemIdForExec :: "+ EnvironmentSetup.LineItemIdForExec); EnvironmentSetup.UseLineItem = true; DbFunctions dbFunction = new DbFunctions(); int rowCount = dbFunction.getRowCount(this.executeStep.getDataSet()); System.out.println("Row Count for " + EnvironmentSetup.LineItemIdForExec + "is :: " + rowCount); for(int i=1; i<=rowCount; i++){ EnvironmentSetup.UseLineItem = true; executeStep.performAction(SeleniumActions.Enter, "AddStoresItemName", "AddStoresItemNameField"); verifications.verify(SeleniumVerifications.Entered, "AddStoresItemName","AddStoresItemNameField",false); executeStep.performAction(SeleniumActions.Enter, "AddStoresShorterName", "AddStoresShorterNameField"); verifications.verify(SeleniumVerifications.Entered, "AddStoresShorterName","AddStoresShorterNameField",false); executeStep.performAction(SeleniumActions.Enter, "AddStoresManufacturer", "AddStoresManufacturerField"); verifications.verify(SeleniumVerifications.Appears, "","AddStoresManufacturerResultsList",false); executeStep.performAction(SeleniumActions.Click, "","AddStoresManufacturerResultsList"); verifications.verify(SeleniumVerifications.Entered, "AddStoresManufacturer","AddStoresManufacturerField",false); executeStep.performAction(SeleniumActions.Select, "AddStoresCategory", "AddStoresCategoryField"); verifications.verify(SeleniumVerifications.Selected, "AddStoresCategory","AddStoresCategoryField",false); executeStep.performAction(SeleniumActions.Select, "UnitUOM", "AddStoreItemUnitUOM"); verifications.verify(SeleniumVerifications.Selected, "UnitUOM","AddStoreItemUnitUOM",true); executeStep.performAction(SeleniumActions.Select, "PackageUOM", "AddStoreItemPackageUOM"); verifications.verify(SeleniumVerifications.Selected, "PackageUOM","AddStoreItemPackageUOM",true); executeStep.performAction(SeleniumActions.Select, "AddItemServiceGroup", "AddItemServiceGroupField"); verifications.verify(SeleniumVerifications.Selected, "AddItemServiceGroup","AddItemServiceGroupField",false); executeStep.performAction(SeleniumActions.Select, "AddItemServiceSubGroup", "AddItemServiceSubGroupField"); verifications.verify(SeleniumVerifications.Selected, "AddItemServiceSubGroup","AddItemServiceSubGroupField",false); executeStep.performAction(SeleniumActions.Enter, "MaxCostPriceSet","MaxCostPriceTextbox"); verifications.verify(SeleniumVerifications.Appears, "MaxCostPriceSet","MaxCostPriceTextbox",true); executeStep.performAction(SeleniumActions.Clear, "","AddItemTaxPercentageField"); executeStep.performAction(SeleniumActions.Enter, "AddItemTaxPercentage","AddItemTaxPercentageField"); verifications.verify(SeleniumVerifications.Appears, "AddItemTaxPercentage","AddItemTaxPercentageField",true); executeStep.performAction(SeleniumActions.Select, "AddItemTaxBasis", "AddItemTaxBasisField"); verifications.verify(SeleniumVerifications.Selected, "AddItemTaxBasis","AddItemTaxBasisField",true); executeStep.performAction(SeleniumActions.Click, "","AddItemSaveButton"); verifications.verify(SeleniumVerifications.Appears, "","AddStoreItem",true); executeStep.performAction(SeleniumActions.Click, "","AddStoreItem"); verifications.verify(SeleniumVerifications.Appears, "","AddItemSaveButton",true); EnvironmentSetup.lineItemCount++; } EnvironmentSetup.lineItemCount =0; EnvironmentSetup.UseLineItem = false; } }
true
59bbb1efe48bf0c217cd6d4e531e9fdcbf42d166
Java
kuali/rice
/rice-middleware/impl/src/main/java/org/kuali/rice/kew/notes/dao/impl/NoteDAOJpa.java
UTF-8
1,342
2.0625
2
[ "Artistic-1.0", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "EPL-1.0", "CPL-1.0", "LGPL-2.1-or-later", "BSD-3-Clause", "LGPL-3.0-only", "ECL-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-jdom", "LicenseRef-scancode-freemarker", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla" ]
permissive
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kew.notes.dao.impl; import org.kuali.rice.kew.notes.dao.NoteDAO; import javax.persistence.EntityManager; import javax.persistence.Query; import java.util.List; public class NoteDAOJpa implements NoteDAO { EntityManager entityManager; public List getNotesByDocumentId(String documentId) { Query query = entityManager.createNamedQuery("KewNote.FindNoteByDocumentId"); query.setParameter("documentId", documentId); return (List) query.getResultList(); } public EntityManager getEntityManager() { return this.entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } }
true
80365e8a33b353492b9eb868988b78af8b29d64d
Java
BibaboTech/react-native-fast-image
/android/src/main/java/vn/bibabo/so5/imageprocessors/BFilterPack.java
UTF-8
12,550
2.359375
2
[ "MIT", "Apache-2.0" ]
permissive
package vn.bibabo.so5.imageprocessors; import android.content.Context; import com.zomato.photofilters.geometry.Point; import java.util.ArrayList; import java.util.List; /** * Originally created by @author Varun on 01/07/15. * <p> * Added filters by @author Ravi Tamada on 29/11/17. * Added multiple filters, the filter names were inspired from * various image filters apps */ public final class BFilterPack { private BFilterPack() { } /*** * the filter pack, * @param context * @return list of filters */ public static List<BFilter> getFilterPack(Context context) { List<BFilter> filters = new ArrayList<>(); filters.add(getAweStruckVibeFilter(context)); filters.add(getClarendon(context)); filters.add(getOldManFilter(context)); filters.add(getMarsFilter(context)); filters.add(getRiseFilter(context)); filters.add(getAprilFilter(context)); filters.add(getAmazonFilter(context)); filters.add(getStarLitFilter(context)); filters.add(getNightWhisperFilter(context)); filters.add(getLimeStutterFilter(context)); filters.add(getHaanFilter(context)); filters.add(getBlueMessFilter(context)); filters.add(getAdeleFilter(context)); filters.add(getCruzFilter(context)); filters.add(getMetropolis(context)); filters.add(getAudreyFilter(context)); return filters; } public static BFilter getStarLitFilter(Context context) { Point[] rgbKnots; rgbKnots = new Point[8]; rgbKnots[0] = new Point(0, 0); rgbKnots[1] = new Point(34, 6); rgbKnots[2] = new Point(69, 23); rgbKnots[3] = new Point(100, 58); rgbKnots[4] = new Point(150, 154); rgbKnots[5] = new Point(176, 196); rgbKnots[6] = new Point(207, 233); rgbKnots[7] = new Point(255, 255); BFilter filter = new BFilter(); //filter.setName(context.getString(R.string.starlit)); filter.addBSubFilter(new BToneCurveSubFilter(rgbKnots, null, null, null)); return filter; } public static BFilter getBlueMessFilter(Context context) { Point[] redKnots; redKnots = new Point[8]; redKnots[0] = new Point(0, 0); redKnots[1] = new Point(86, 34); redKnots[2] = new Point(117, 41); redKnots[3] = new Point(146, 80); redKnots[4] = new Point(170, 151); redKnots[5] = new Point(200, 214); redKnots[6] = new Point(225, 242); redKnots[7] = new Point(255, 255); BFilter filter = new BFilter(); //filter.setName(context.getString(R.string.bluemess)); filter.addBSubFilter(new BToneCurveSubFilter(null, redKnots, null, null)); filter.addBSubFilter(new BBrightnessSubFilter(30)); filter.addBSubFilter(new BContrastSubFilter(1f)); return filter; } public static BFilter getAweStruckVibeFilter(Context context) { Point[] rgbKnots; Point[] redKnots; Point[] greenKnots; Point[] blueKnots; rgbKnots = new Point[5]; rgbKnots[0] = new Point(0, 0); rgbKnots[1] = new Point(80, 43); rgbKnots[2] = new Point(149, 102); rgbKnots[3] = new Point(201, 173); rgbKnots[4] = new Point(255, 255); redKnots = new Point[5]; redKnots[0] = new Point(0, 0); redKnots[1] = new Point(125, 147); redKnots[2] = new Point(177, 199); redKnots[3] = new Point(213, 228); redKnots[4] = new Point(255, 255); greenKnots = new Point[6]; greenKnots[0] = new Point(0, 0); greenKnots[1] = new Point(57, 76); greenKnots[2] = new Point(103, 130); greenKnots[3] = new Point(167, 192); greenKnots[4] = new Point(211, 229); greenKnots[5] = new Point(255, 255); blueKnots = new Point[7]; blueKnots[0] = new Point(0, 0); blueKnots[1] = new Point(38, 62); blueKnots[2] = new Point(75, 112); blueKnots[3] = new Point(116, 158); blueKnots[4] = new Point(171, 204); blueKnots[5] = new Point(212, 233); blueKnots[6] = new Point(255, 255); BFilter filter = new BFilter(); //filter.setName(context.getString(R.string.struck)); filter.addBSubFilter(new BToneCurveSubFilter(rgbKnots, redKnots, greenKnots, blueKnots)); return filter; } public static BFilter getLimeStutterFilter(Context context) { Point[] blueKnots; blueKnots = new Point[3]; blueKnots[0] = new Point(0, 0); blueKnots[1] = new Point(165, 114); blueKnots[2] = new Point(255, 255); BFilter filter = new BFilter(); //filter.setName(context.getString(R.string.lime)); filter.addBSubFilter(new BToneCurveSubFilter(null, null, null, blueKnots)); return filter; } public static BFilter getNightWhisperFilter(Context context) { Point[] rgbKnots; Point[] redKnots; Point[] greenKnots; Point[] blueKnots; rgbKnots = new Point[3]; rgbKnots[0] = new Point(0, 0); rgbKnots[1] = new Point(174, 109); rgbKnots[2] = new Point(255, 255); redKnots = new Point[4]; redKnots[0] = new Point(0, 0); redKnots[1] = new Point(70, 114); redKnots[2] = new Point(157, 145); redKnots[3] = new Point(255, 255); greenKnots = new Point[3]; greenKnots[0] = new Point(0, 0); greenKnots[1] = new Point(109, 138); greenKnots[2] = new Point(255, 255); blueKnots = new Point[3]; blueKnots[0] = new Point(0, 0); blueKnots[1] = new Point(113, 152); blueKnots[2] = new Point(255, 255); BFilter filter = new BFilter(); //filter.setName(context.getString(R.string.whisper)); filter.addBSubFilter(new BContrastSubFilter(1.5f)); filter.addBSubFilter(new BToneCurveSubFilter(rgbKnots, redKnots, greenKnots, blueKnots)); return filter; } public static BFilter getAmazonFilter(Context context) { Point[] blueKnots; blueKnots = new Point[6]; blueKnots[0] = new Point(0, 0); blueKnots[1] = new Point(11, 40); blueKnots[2] = new Point(36, 99); blueKnots[3] = new Point(86, 151); blueKnots[4] = new Point(167, 209); blueKnots[5] = new Point(255, 255); BFilter filter = new BFilter();//context.getString(R.string.amazon)); filter.addBSubFilter(new BContrastSubFilter(1.2f)); filter.addBSubFilter(new BToneCurveSubFilter(null, null, null, blueKnots)); return filter; } public static BFilter getAdeleFilter(Context context) { BFilter filter = new BFilter();//context.getString(R.string.adele)); filter.addBSubFilter(new BSaturationSubFilter(-100f)); return filter; } public static BFilter getCruzFilter(Context context) { BFilter filter = new BFilter();//context.getString(R.string.cruz)); filter.addBSubFilter(new BSaturationSubFilter(-100f)); filter.addBSubFilter(new BContrastSubFilter(1.3f)); filter.addBSubFilter(new BBrightnessSubFilter(20)); return filter; } public static BFilter getMetropolis(Context context) { BFilter filter = new BFilter();//context.getString(R.string.metropolis)); filter.addBSubFilter(new BSaturationSubFilter(-1f)); filter.addBSubFilter(new BContrastSubFilter(1.7f)); filter.addBSubFilter(new BBrightnessSubFilter(70)); return filter; } public static BFilter getAudreyFilter(Context context) { BFilter filter = new BFilter();//context.getString(R.string.audrey)); Point[] redKnots; redKnots = new Point[3]; redKnots[0] = new Point(0, 0); redKnots[1] = new Point(124, 138); redKnots[2] = new Point(255, 255); filter.addBSubFilter(new BSaturationSubFilter(-100f)); filter.addBSubFilter(new BContrastSubFilter(1.3f)); filter.addBSubFilter(new BBrightnessSubFilter(20)); filter.addBSubFilter(new BToneCurveSubFilter(null, redKnots, null, null)); return filter; } public static BFilter getRiseFilter(Context context) { Point[] blueKnots; Point[] redKnots; blueKnots = new Point[4]; blueKnots[0] = new Point(0, 0); blueKnots[1] = new Point(39, 70); blueKnots[2] = new Point(150, 200); blueKnots[3] = new Point(255, 255); redKnots = new Point[4]; redKnots[0] = new Point(0, 0); redKnots[1] = new Point(45, 64); redKnots[2] = new Point(170, 190); redKnots[3] = new Point(255, 255); BFilter filter = new BFilter();//context.getString(R.string.rise)); filter.addBSubFilter(new BContrastSubFilter(1.9f)); filter.addBSubFilter(new BBrightnessSubFilter(60)); filter.addBSubFilter(new BVignetteSubFilter(context, 200)); filter.addBSubFilter(new BToneCurveSubFilter(null, redKnots, null, blueKnots)); return filter; } public static BFilter getMarsFilter(Context context) { BFilter filter = new BFilter();//context.getString(R.string.mars)); filter.addBSubFilter(new BContrastSubFilter(1.5f)); filter.addBSubFilter(new BBrightnessSubFilter(10)); return filter; } public static BFilter getAprilFilter(Context context) { Point[] blueKnots; Point[] redKnots; blueKnots = new Point[4]; blueKnots[0] = new Point(0, 0); blueKnots[1] = new Point(39, 70); blueKnots[2] = new Point(150, 200); blueKnots[3] = new Point(255, 255); redKnots = new Point[4]; redKnots[0] = new Point(0, 0); redKnots[1] = new Point(45, 64); redKnots[2] = new Point(170, 190); redKnots[3] = new Point(255, 255); BFilter filter = new BFilter();//context.getString(R.string.april)); filter.addBSubFilter(new BContrastSubFilter(1.5f)); filter.addBSubFilter(new BBrightnessSubFilter(5)); filter.addBSubFilter(new BVignetteSubFilter(context, 150)); filter.addBSubFilter(new BToneCurveSubFilter(null, redKnots, null, blueKnots)); return filter; } public static BFilter getHaanFilter(Context context) { Point[] greenKnots; greenKnots = new Point[3]; greenKnots[0] = new Point(0, 0); greenKnots[1] = new Point(113, 142); greenKnots[2] = new Point(255, 255); BFilter filter = new BFilter();//context.getString(R.string.haan)); filter.addBSubFilter(new BContrastSubFilter(1.3f)); filter.addBSubFilter(new BBrightnessSubFilter(60)); filter.addBSubFilter(new BVignetteSubFilter(context, 200)); filter.addBSubFilter(new BToneCurveSubFilter(null, null, greenKnots, null)); return filter; } public static BFilter getOldManFilter(Context context) { BFilter filter = new BFilter();//context.getString(R.string.oldman)); filter.addBSubFilter(new BBrightnessSubFilter(30)); filter.addBSubFilter(new BSaturationSubFilter(0.8f)); filter.addBSubFilter(new BContrastSubFilter(1.3f)); filter.addBSubFilter(new BVignetteSubFilter(context, 100)); filter.addBSubFilter(new BColorOverlaySubFilter(100, .2f, .2f, .1f)); return filter; } public static BFilter getClarendon(Context context) { Point[] redKnots; Point[] greenKnots; Point[] blueKnots; redKnots = new Point[4]; redKnots[0] = new Point(0, 0); redKnots[1] = new Point(56, 68); redKnots[2] = new Point(196, 206); redKnots[3] = new Point(255, 255); greenKnots = new Point[4]; greenKnots[0] = new Point(0, 0); greenKnots[1] = new Point(46, 77); greenKnots[2] = new Point(160, 200); greenKnots[3] = new Point(255, 255); blueKnots = new Point[4]; blueKnots[0] = new Point(0, 0); blueKnots[1] = new Point(33, 86); blueKnots[2] = new Point(126, 220); blueKnots[3] = new Point(255, 255); BFilter filter = new BFilter();//context.getString(R.string.clarendon)); filter.addBSubFilter(new BContrastSubFilter(1.5f)); filter.addBSubFilter(new BBrightnessSubFilter(-10)); filter.addBSubFilter(new BToneCurveSubFilter(null, redKnots, greenKnots, blueKnots)); return filter; } }
true
536b95c518327a70ac3de5a55d258723defe39c2
Java
striveprince/strive
/app/src/main/java/com/cutv/ningbo/data/util/des/DES.java
UTF-8
5,010
2.640625
3
[]
no_license
package com.cutv.ningbo.data.util.des; import java.io.IOException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; public class DES { private byte[] desKey; // public static final String mykey = "cutv$^#$%#@$^&ZZ&*"; public static final String key = "T@V"; public static final String DKDBKEY = "dkdb6102"; public DES(String desKey) { this.desKey = desKey.getBytes(); } public byte[] desEncrypt(byte[] plainText) throws Exception { SecureRandom sr = new SecureRandom(); byte rawKeyData[] = desKey; DESKeySpec dks = new DESKeySpec(rawKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key, sr); byte data[] = plainText; byte encryptedData[] = cipher.doFinal(data); return encryptedData; } public byte[] desDecrypt(byte[] encryptText) throws Exception { SecureRandom sr = new SecureRandom(); byte rawKeyData[] = desKey; DESKeySpec dks = new DESKeySpec(rawKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, key, sr); byte encryptedData[] = encryptText; byte decryptedData[] = cipher.doFinal(encryptedData); return decryptedData; } public static byte[] desEncrypt(byte[] plainText,String keytime) throws Exception { SecureRandom sr = new SecureRandom(); byte rawKeyData[] =(DES.key+keytime).getBytes(); DESKeySpec dks = new DESKeySpec(rawKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key, sr); byte data[] = plainText; byte encryptedData[] = cipher.doFinal(data); return encryptedData; } public String encrypt(String input){ return encrypt(input.getBytes()); } public String encrypt(byte[] input){ try{ return base64Encode(desEncrypt(input)); }catch (Exception e){ e.printStackTrace(); } return null; } public static String encrypt(String input, String keytime) throws Exception { return base64Encode(desEncrypt(input.getBytes(),keytime)); } public String decrypt(String input) throws Exception { byte[] result = base64Decode(input); return new String(desDecrypt(result)); } public static String base64Encode(byte[] s) { if (s == null) return null; BASE64Encoder b = new BASE64Encoder(); return b.encode(s); } public static byte[] base64Decode(String s) throws IOException { if (s == null) return null; BASE64Decoder decoder = new BASE64Decoder(); byte[] b = decoder.decodeBuffer(s); return b; } public static byte[] desDecrypt(byte[] encryptText,String keytime) throws Exception { SecureRandom sr = new SecureRandom(); DESKeySpec dks = new DESKeySpec(keytime.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, key, sr); byte encryptedData[] = encryptText; byte decryptedData[] = cipher.doFinal(encryptedData); return decryptedData; } /*public static byte[] desCrypto(byte[] datasource, String key) { try { SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(key.getBytes()); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 SecretKeyFactory keyFactory = SecretKeyFactory.getNingInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getNingInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, random); // 现在,获取数据并加密 // 正式执行加密操作 return cipher.doFinal(datasource); } catch (Throwable e) { e.printStackTrace(); } return null; }*/ /* public static void main(String[] args) throws Exception { String key = "abcdefgh"; String input = "a"; DES crypt = new DES(key); System.out.println("Encode:" + crypt.encrypt(input)); System.out.println("Decode:" + crypt.decrypt(crypt.encrypt(input))); } */ }
true
c1f21885936f655349cc53d165338eb983083f77
Java
Razhan/Jump
/app/src/main/java/com/example/ranzhang/myapplication/Business/ChartBLL.java
UTF-8
3,046
2.6875
3
[]
no_license
package com.example.ranzhang.myapplication.Business; import android.content.Context; import android.graphics.Color; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import java.util.ArrayList; /** * Created by ran.zhang on 9/16/15. */ public class ChartBLL { private LineChart mChart; private Context mContext; public ChartBLL(LineChart chart, Context context) { if(chart == null || context == null) { return; } this.mChart = chart; this.mContext = context; initChart(); initChartData(); } public void clearData() { LineData data = mChart.getData(); data.clearValues(); initChart(); initChartData(); mChart.invalidate(); } private void initChart() { mChart.setDrawGridBackground(true); mChart.getAxisLeft().setDrawGridLines(true); mChart.getAxisRight().setEnabled(false); mChart.getXAxis().setDrawGridLines(true); mChart.getXAxis().setDrawAxisLine(true); mChart.setDescription(""); mChart.invalidate(); } private void initChartData() { ArrayList<String> xVals = new ArrayList<String>(); ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>(); addDataSet(ColorTemplate.getHoloBlue(), "Origin", dataSets); addDataSet(ColorTemplate.JOYFUL_COLORS[0], "LowPass", dataSets); // addDataSet(ColorTemplate.JOYFUL_COLORS[1], "Mean", dataSets); // addDataSet(ColorTemplate.JOYFUL_COLORS[3], "Median", dataSets); LineData data = new LineData(xVals, dataSets); data.setValueTextColor(Color.WHITE); data.setValueTextSize(9f); mChart.setData(data); } private void addDataSet(int color, String description, ArrayList<LineDataSet> dataSets) { ArrayList<Entry> yVals = new ArrayList<Entry>(); LineDataSet set = new LineDataSet(yVals, description); set.setAxisDependency(YAxis.AxisDependency.LEFT); set.setColor(color); set.setLineWidth(2f); set.setFillAlpha(65); set.setDrawCircleHole(false); set.setDrawCircles(false); set.setDrawValues(false); set.setHighlightEnabled(false); dataSets.add(set); } public void addEntry(float a, int index) { LineData data = mChart.getData(); LineDataSet set = data.getDataSetByIndex(index); int count = data.getXValCount(); if(count == set.getEntryCount()) { data.addXValue(set.getEntryCount() + ""); } data.addEntry(new Entry(a, set.getEntryCount()), index); mChart.notifyDataSetChanged(); mChart.moveViewTo(data.getXValCount() - 10, a, YAxis.AxisDependency.LEFT); } }
true
03716f5b35f1fe6f0577dab683ce27016c6f161d
Java
boyvita/java_labs
/Lab4/src/ru/billing/stocklist/ItemCatalog.java
UTF-8
1,712
3.03125
3
[]
no_license
package ru.billing.stocklist; import javafx.util.Pair; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; // id add() item get(id) item[] get(price, category) remove id[] public class ItemCatalog { private HashMap<Integer, GenericItem> catalog = new HashMap<Integer, GenericItem>(); private HashMap<Pair<Float, Category>, HashMap<Integer, GenericItem>> catalogPairs = new HashMap<Pair<Float, Category>, HashMap<Integer, GenericItem>>(); private Integer IDLast = 0; public void addItem(GenericItem item) { catalog.put(this.IDLast, item); HashMap<Integer, GenericItem> list = catalogPairs.get(new Pair(item.price, item.category)); if (list != null) { list.put(this.IDLast, item); } else { list = new HashMap<Integer, GenericItem>(); list.add(item); catalogPairs.put(new Pair(item.price, item.category), list); } } public GenericItem get(Integer id) { GenericItem item = catalog.get(id); if (item != null) { return item; } else { return null; } } public ArrayList<GenericItem> get(float price, Category category) { ArrayList<GenericItem> list = catalogPairs.get(new Pair<Float, Category>(price, category)); if (list != null) { return list; } else { return null; } } public void remove(int id) throws Exception { if (!catalog.containsKey(id)) { throw new Exception("There isn't that id"); } else { catalog.remove(id); } } }
true
55b939d27445aed65fd1b07ac1d972afffcb2dfb
Java
tmznf963/SIST-E
/0808/src/InheritanceDemo1.java
UHC
679
4.03125
4
[]
no_license
public class InheritanceDemo1 { public static void main(String[] args) { Derived d = new Derived("Ballpen",1000); } } class Base { String name; public Base(String name) { System.out.println("θ "+name); } } class Derived extends Base { int price; public Derived(String name , int price) {//ڽ θ ⺻() ȣѴ. //super();// super(name); //Ϲ ޼ҵ ȿ Ұ. ȿ . ׻ ù° this.price = price; System.out.println("ڽ "+price); } } //this(), super() Ұ == ù ٿ ־ ϴ
true
a87eb1fd6413b6aa3d0810bcdfb53a1d65a51b1c
Java
opus-research/RefDetector
/src/main/java/com/sdmetrics/model/XMITrigger.java
UTF-8
3,968
2.609375
3
[]
no_license
/* * SDMetrics Open Core for UML design measurement * Copyright (c) 2002-2011 Juergen Wuest * To contact the author, see <http://www.sdmetrics.com/Contact.html>. * * This file is part of the SDMetrics Open Core. * * SDMetrics Open Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * SDMetrics Open Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SDMetrics Open Core. If not, see <http://www.gnu.org/licenses/>. * */ package com.sdmetrics.model; /** Stores information for one trigger of an XMITransformation. */ class XMITrigger { /** Enumerates the types of triggers. */ static enum TriggerType { /** Trigger "constant". */ CONSTANT(true, false), /** Trigger "attrval". */ ATTRVAL(true, false), /** Trigger "cattrval". */ CATTRVAL(true, true), /** Trigger "ctext". */ CTEXT(false, true), /** Trigger "gcattrval". */ GCATTRVAL(true, true), /** Trigger "ignore". */ IGNORE(false, false), /** Trigger "xmi2assoc". */ XMI2ASSOC(true, false), /** Deprecated trigger "reflist". */ REFLIST(true, true); /** Indicates if the trigger require the "attr" attribute to be set. */ final boolean requiresAttr; /** Indicates if the trigger require the "src" attribute to be set. */ final boolean requiresSrc; private TriggerType(boolean requiresAttr, boolean requiresSrc) { this.requiresAttr = requiresAttr; this.requiresSrc = requiresSrc; } /** * Sets trigger names to lower case for output. */ @Override public String toString() { return name().toLowerCase(); } } /** Value of the name attribute of this trigger. */ String name; /** The type of trigger (attrval, ctext, ...) */ TriggerType type; /** The XMI element that holds the information for this trigger. */ String src; /** The relevant attribute of the XMI element that holds the information. */ String attr; /** Name of an attribute storing back links to a referencing element. */ String linkback; /** * Create a new trigger. * * @param attributeName The name of the metamodel element attribute for * which this trigger is defined. * @param triggerType The type of trigger. * @param srcElement The XMI element that holds the information for this * trigger. * @param srcAttribute The relevant attribute of the XMI element that holds * the information. * @param linkBackAttribute For cross-reference attributes: the link back * attribute. * @throws IllegalArgumentException Unknown trigger kind or required * attributes were missing. */ XMITrigger(String attributeName, String triggerType, String srcElement, String srcAttribute, String linkBackAttribute) { name = attributeName; src = srcElement; attr = srcAttribute; linkback = linkBackAttribute; type = null; try { type = TriggerType.valueOf(triggerType.toUpperCase()); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException("Unknown trigger type '" + triggerType + "'."); } if (type.requiresAttr && srcAttribute == null) throw new IllegalArgumentException( "Attribute 'attr' must be specified for triggers of type '" + triggerType + "'."); if (type.requiresSrc && srcElement == null) throw new IllegalArgumentException( "Attribute 'src' must be specified for triggers of type '" + triggerType + "'."); } }
true
dcbab9d2208a1d0d1a288611476d03b62b50a5fb
Java
ikuboo/addingcode
/src/main/java/com/ikuboo/guava/future/ExecutorServiceDemo1.java
UTF-8
838
3.046875
3
[]
no_license
package com.ikuboo.guava.future; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @author [email protected] * 2018/1/21. */ public class ExecutorServiceDemo1 { public static void main(String[] args) throws InterruptedException { final Object lock = new Object(); ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); executorService.scheduleAtFixedRate(new MyRun(), 1, 5, TimeUnit.SECONDS); TimeUnit.SECONDS.sleep(30); executorService.shutdown(); System.out.println("shutdow"); System.out.println(executorService.isShutdown()); } } class MyRun implements Runnable{ @Override public void run() { System.out.print("."); } }
true
62b9d9f8279ec96954979977121ad70fc00653d3
Java
wb1992321/PictureSelector
/pictureselector/src/main/java/cn/wang/img/selector/views/PictureStagger.java
UTF-8
1,294
2.34375
2
[]
no_license
package cn.wang.img.selector.views; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; /** * author : wangshuai Created on 2017/5/16 * email : [email protected] */ public class PictureStagger extends GridLayoutManager.SpanSizeLookup { public static final int TYPE_PICTURE = 9999999; public static final int TYPE_DATE_DAY = 9999998; private RecyclerView.Adapter adapter = null; private int columnCount = 0; public PictureStagger(RecyclerView.Adapter adapter, int columnCount) { this.adapter = adapter; this.columnCount = columnCount; } @Override public int getSpanSize(int position) { int type = adapter.getItemViewType(position); switch (type) { case TYPE_PICTURE: return 1; case TYPE_DATE_DAY: return getColumnCount(); default: return 1; } } public RecyclerView.Adapter getAdapter() { return adapter; } public void setAdapter(RecyclerView.Adapter adapter) { this.adapter = adapter; } public int getColumnCount() { return columnCount; } public void setColumnCount(int columnCount) { this.columnCount = columnCount; } }
true
708462e78835d570db2763b0b9a1babbdd9f71bc
Java
Ivan19981305/Netcracker-2021-Georgiev
/Дз к 16.04/Задание 1/Main.java
UTF-8
1,375
2.859375
3
[]
no_license
package ivge; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; public class Main { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Menu menu = new Menu(); while (true) menu.action(); /* Добавить пункт меню. Изменить порядок пунктов меню. Добавить пункт меню. Новый пункт. Добавить пункт меню. Изменить порядок пунктов меню. Новый пункт. Изменить порядок пунктов меню. в порядке добавления. в порядке использования. в порядке добавления Некорректная команда Добавить пункт меню. Изменить порядок пунктов меню. Новый пункт. Изменить порядок пунктов меню. в порядке добавления. в порядке использования. в порядке использования. Добавить пункт меню. Новый пункт. Изменить порядок пунктов меню. */ } }
true
0e0ab08274f501a385b6b5f1aaba65550dac1c79
Java
Oroles/Hlin-PasswordManager
/Phone/app/src/main/java/com/example/oroles/hlin/Controllers/CommandManagerController.java
UTF-8
1,008
2.8125
3
[ "MIT" ]
permissive
package com.example.oroles.hlin.Controllers; import com.example.oroles.hlin.InterfacesControllers.ICommandManager; import com.example.oroles.hlin.InterfacesControllers.IStore; import java.util.ArrayList; public class CommandManagerController implements ICommandManager { private IStore mStore; private ArrayList<Integer> mCommands; public CommandManagerController(IStore store) { mStore = store; mCommands = new ArrayList<>(); } @Override public void addCommand(int commandId) { mCommands.add(0, (int) commandId); } @Override public boolean existCommand(int commandId) { return -1 != mCommands.indexOf(Integer.valueOf(commandId)); } @Override public void removeAll(int commandId) { int index = 0; while ((index = mCommands.indexOf(Integer.valueOf(commandId))) != -1) { mCommands.remove(index); } } @Override public void removeAll() { mCommands.clear(); } }
true
c77143f5d8a78144cb71eaa20f19247021d2dd1e
Java
hoangpham1997/ChanDoi
/Project/ebweb2019/src/main/java/vn/softdreams/ebweb/service/util/DateUtil.java
UTF-8
7,301
2.484375
2
[]
no_license
package vn.softdreams.ebweb.service.util; import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.IsoFields; import java.util.Locale; import java.util.Objects; public class DateUtil { public static final String C_YYYY = "yyyy"; public static final String C_MM = "MM"; public static final String C_DD = "dd"; public static final String C_DDMMYYYY = "ddMMyyyy"; public static final String C_DD_MM_YYYY = "dd/MM/yyyy"; public static final String C_D_MM_YYYY = "d/MM/yyyy"; public static final String C_DD_M_YYYY = "dd/M/yyyy"; public static final String C_D_M_YYYY = "d/M/yyyy"; public static final String C_DDaMMaYYYY = "dd-MM-yyyy"; public static final String C_DaMMaYYYY = "d-MM-yyyy"; public static final String C_DDaMaYYYY = "dd-M-yyyy"; public static final String C_DaMaYYYY = "d-M-yyyy"; public static final String C_MMDDYYYY = "yyyyMMdd"; public static final String C_YYYYMM = "yyyyMM"; public static final String C_YYYYMMDD_HHMMSS = "yyyyMMddHHmmss"; public static final String C_YYYY_MM_DD_HHMMSS = "yyyy-MM-dd HH:mm:ss"; public static final String C_YYYY_MM_DD_HHMM = "yyyy-MM-dd HH:mm"; public static final String C_DD_MM_YYYY_HHMM = "dd/MM/yyyy HH:mm"; public static final String C_YYYY_MM_DD = "YYYY-MM-DD"; /** * @author haivv * * Chuyển đổi định dạng ngày tháng từ LocalDate sang String * * @param date ngày tháng kiểu LocalDate cần đổi * @param pattern định dạng ngày tháng muốn chuyển * @return ngày tháng kiểu String theo định dạng */ public static String getStrByLocalDate(LocalDate date, String pattern) { if (Objects.isNull(date)) { return ""; } DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); return date.format(dateTimeFormatter); } /** * @author haivv * * Chuyển đổi định dạng ngày tháng từ LocalDateTime sang String * * @param date ngày tháng kiểu LocalDateTime cần đổi * @param pattern định dạng ngày tháng muốn chuyển * @return ngày tháng kiểu String theo định dạng */ public static String getStrByLocalDateTime(LocalDateTime date, String pattern) { if (Objects.isNull(date)) { return ""; } DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); return date.format(dateTimeFormatter); } /** * @author haivv * * Chuyển đổi ngày tháng từ String sang LocalDateTime theo pattern * * @param date ngày tháng kiểu String * @param pattern định dạng ngày tháng truyển vào * @return ngày tháng theo kiểu LocalDateTime hoặc null nếu ngày truyền vào null */ public static LocalDateTime getLocalDateTimeFromString(String date, String pattern) { if (StringUtils.isBlank(date)) { return null; } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); try { return LocalDateTime.parse(date, formatter); } catch (Exception ex) { } return null; } /** * @author haivv * * Chuyển đổi ngày tháng từ String sang LocalDate theo pattern * * @param date ngày tháng kiểu String * @param pattern định dạng ngày tháng truyển vào * @return ngày tháng theo kiểu LocalDate hoặc null nếu ngày truyền vào null */ public static LocalDate getLocalDateFromString(String date, String pattern) { if (StringUtils.isBlank(date)) { return null; } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); try { return LocalDate.parse(date, formatter); } catch (Exception ex) { } return null; } /** * @author haivv * * Chuyển đổi ngày tháng từ String sang Instant theo pattern * * @param date ngày tháng kiểu String * @param pattern định dạng ngày tháng truyền vào * @return ngày tháng theo kiểu Instant hoặc null nếu date truyền vào không đúng */ public static Instant getInstantFromString(String date, String pattern) { if (StringUtils.isNotBlank(date)) { LocalDateTime localDateTime = getLocalDateTimeFromString(date, pattern); if (Objects.nonNull(localDateTime)) { return localDateTime.toInstant(ZoneOffset.UTC); } return null; } return null; } /** * @author haivv * * Chuyển đổi ngày tháng từ String sang chuẩn dd/MM/yyyy theo pattern * * @param date ngày tháng kiểu String * @param pattern định dạng ngày tháng truyền vào * @return ngày tháng theo chuẩn dd/MM/yyyy hoặc null nếu date truyền vào không đúng */ public static String formatStandardDateFromString(String date, String pattern, String toPattern) { if (StringUtils.isNotBlank(date)) { LocalDate localDate = getLocalDateFromString(date, pattern); if (Objects.nonNull(localDate)) { if (Strings.isNullOrEmpty(toPattern)) { return getStrByLocalDate(localDate, C_DDMMYYYY); } else { return getStrByLocalDate(localDate, toPattern); } } return null; } return null; } /** * @author haivv * * Chuyển đổi định dạng ngày tháng từ Instant sang String * * @param date ngày tháng kiểu LocalDate cần đổi * @param pattern định dạng ngày tháng muốn chuyển * @return ngày tháng kiểu String theo định dạng */ public static String getStrByInstant(Instant date, String pattern) { if (Objects.isNull(date)) { return ""; } DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern) .withLocale(Locale.getDefault()) .withZone(ZoneId.systemDefault()); return dateTimeFormatter.format(date); } public static String getQuarterOfYear(String date) { if (Strings.isNullOrEmpty(date)) { return ""; } if (date.length() == 6) { date += "01"; } return date.substring(0, 4) + LocalDate.parse(date, DateTimeFormatter.ofPattern(C_DDMMYYYY)).get(IsoFields.QUARTER_OF_YEAR); } public static String plusQuarter(String date) { if (Strings.isNullOrEmpty(date) && date.length() != 5) { return ""; } String month = (date.substring(4).equalsIgnoreCase("4") ? "" : "0") + Integer.parseInt(date.substring(4)) * 3; date = date.substring(0, 4) + month + "01"; LocalDate newDate = LocalDate.parse(date, DateTimeFormatter.ofPattern(C_DDMMYYYY)).plusMonths(3); return newDate.format(DateTimeFormatter.ofPattern(C_YYYY)) + newDate.get(IsoFields.QUARTER_OF_YEAR); } }
true
ced7c6af97853b61bf4c4de3f0b5825e5b1110f9
Java
EmmaStonePB/Scripts
/src/com/emmastone/rs3/scripts/esminer/tasks/banking/OpenBank.java
UTF-8
627
2.015625
2
[]
no_license
package com.emmastone.rs3.scripts.esminer.tasks.banking; import org.powerbot.script.methods.MethodContext; import com.emmastone.rs3.scripts.esminer.data.Location; import com.emmastone.rs3.scripts.framework.Task; public class OpenBank extends Task { public OpenBank(MethodContext ctx) { super(ctx); } @Override public boolean activate() { return ctx.backpack.select().count() == 28; } @Override public void execute() { if (ctx.bank.isInViewport()) { if (ctx.bank.open()) { ctx.bank.depositInventory(); ctx.bank.close(); } } else { Location.VARROCK_EAST_MINE.walkToBank(ctx); } } }
true
e41c98ff7155585b8ff660d54938cc17881d37e7
Java
lqf7F/cmfz
/src/main/java/com/baizhi/dao/ChapterDao.java
UTF-8
1,242
2.140625
2
[]
no_license
package com.baizhi.dao; import com.baizhi.entity.Chapter; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface ChapterDao { @Select("select id,title,size,timesize,url,album_id albumId from chapter where album_id=#{aId} limit #{start},#{rows}\n") public List<Chapter> queryByPage(@Param("start") Integer start, @Param("rows") Integer rows, @Param("aId") String albumId); @Select("select count(id) from chapter where album_id=#{aId}\n") public Integer getCount(String aId); @Insert("insert into chapter values (#{id},#{title},#{size},#{timesize},#{url},#{albumId})\n") public void add(Chapter chapter); @Update("update chapter set url=#{url},size=#{size},timesize=#{timesize} where id=#{id}\n") public void updateUrl(Chapter chapter); public void deleteChapter(String[] ids); @Select("select id,title,size,timesize,url,album_id albumId from chapter") public List<Chapter> selectAll(); @Select("select id,title,size,timesize,url,album_id albumId from chapter where id=#{id}") public Chapter selectById(String id); }
true
c27590d9c258a78a729b684a4a182d76a72ba3f5
Java
yuexiaoguang/tomcat8.5
/src/javax/servlet/jsp/JspContext.java
UTF-8
6,955
2.546875
3
[]
no_license
package javax.servlet.jsp; import java.util.Enumeration; import javax.el.ELContext; /** * <p> * <code>JspContext</code>作为PageContext类的基类,并抽象出所有并不特定于servlet的信息. * 允许在一个request/response Servlet的上下文外面使用Simple Tag Extension. * <p> * JspContext 提供许多工具到page/component作者和网页实现人员, 包括: * <ul> * <li>一个单一的API来管理不同作用域的命名空间 * <li>一种机制来获得输出 JspWriter * <li>向脚本环境公开页面指令属性的机制 * </ul> * * <p><B>用于容器生成代码的方法</B> * <p> * 下列方法启用<B>management of nested</B> JspWriter 流来实现Tag Extensions: <code>pushBody()</code>和<code>popBody()</code> * * <p><B>JSP作者的方法</B> * <p> * 一些方法提供<B>uniform access</B>对表示范围的不同对象. 实现必须使用与该范围相对应的底层机制, 因此信息可以在底层环境(e.g. Servlets)和JSP 页面之间来回传递. * 这些方法是: * <code>setAttribute()</code>, <code>getAttribute()</code>, * <code>findAttribute()</code>, <code>removeAttribute()</code>, * <code>getAttributesScope()</code>, <code>getAttributeNamesInScope()</code>. * * <p> * 下列方法提供<B>convenient access</B>给隐式对象: * <code>getOut()</code> * * <p> * 下列方法提供<B>programmatic access</b> 给Expression Language 计算器: * <code>getExpressionEvaluator()</code>, <code>getVariableResolver()</code> */ public abstract class JspContext { /** * (用于子类构造函数的调用, 通常是隐式的.) */ public JspContext() { // NOOP by default } /** * 用页面范围语义注册指定的名称和值. * 如果传过来的值是<code>null</code>, 和调用<code>removeAttribute( name, PageContext.PAGE_SCOPE )</code>效果一样. * * @param name 要设置的属性的名称 * @param value 与名称相关联的值, 或者null. * @throws NullPointerException 如果名称是 null */ public abstract void setAttribute(String name, Object value); /** * 用适当的范围语义注册指定的名称和值. * 如果传过来的值是<code>null</code>, 等同于调用<code>removeAttribute( name, scope )</code>. * * @param name 要设置的属性的名称 * @param value 与名称相关联的对象, 或者null * @param scope 将名称/对象关联的范围 * * @throws NullPointerException 如果名称是 null * @throws IllegalArgumentException 如果范围无效 * @throws IllegalStateException 如果范围是PageContext.SESSION_SCOPE, 但请求的页面不参与会话,或者会话已失效. */ public abstract void setAttribute(String name, Object value, int scope); /** * 返回与页面范围中的名称相关联的对象,或者null. * * @param name 要获取的属性的名称 * @return 与页面范围中的名称相关联的对象, 或者null. * * @throws NullPointerException 如果名称是null */ public abstract Object getAttribute(String name); /** * 返回指定的范围内与名称关联的对象, 或者null. * * @param name 要设置的属性的名称 * @param scope 将名称/对象关联的范围 * @return 与指定范围内的名称关联的对象,或者 null. * * @throws NullPointerException 如果名称是null * @throws IllegalArgumentException 如果范围无效 * @throws IllegalStateException 如果范围是PageContext.SESSION_SCOPE, 但请求的页面不参与会话,或者会话已失效. */ public abstract Object getAttribute(String name, int scope); /** * 按顺序搜索页面、请求、会话(如果有效)和应用程序范围中的命名属性,并返回相关联的值,或者null. * * @param name 要搜索的属性的名称 * @return 关联的值或null * @throws NullPointerException 如果名称是null */ public abstract Object findAttribute(String name); /** * 从所有范围中移除与给定名称关联的对象引用. 如果没有这样的对象,什么也不做. * * @param name 要删除的对象的名称. * @throws NullPointerException 如果名称是null */ public abstract void removeAttribute(String name); /** * 在给定范围内移除与指定名称相关联的对象引用. 如果没有这样的对象,什么也不做. * * @param name 要删除的对象的名称. * @param scope 要查找的范围. * @throws IllegalArgumentException 如果范围无效 * @throws IllegalStateException 如果范围是PageContext.SESSION_SCOPE, 但请求的页面不参与会话,或者会话已失效. * @throws NullPointerException 如果名称是null */ public abstract void removeAttribute(String name, int scope); /** * 获取定义给定属性的范围. * * @param name 返回范围的属性的名称 * @return 与指定的名称相关联的对象的作用域,或 0 * @throws NullPointerException 如果名称是null */ public abstract int getAttributesScope(String name); /** * 枚举给定范围内的所有属性. * * @param scope 枚举所有属性的范围 * @return 指定范围内所有属性名称的枚举 * @throws IllegalArgumentException 如果范围无效 * @throws IllegalStateException 如果范围是PageContext.SESSION_SCOPE, 但请求的页面不参与会话,或者会话已失效. */ public abstract Enumeration<String> getAttributeNamesInScope(int scope); /** * out对象(JspWriter)的当前值. * * @return 客户端响应使用的当前JspWriter流 */ public abstract JspWriter getOut(); public abstract ELContext getELContext(); /** * 返回一个新的JspWriter对象. * 保存当前"out" JspWriter, 并更新JspContext的页面范围属性命名空间中的"out"属性的值. * <p>返回的JspWriter要实现所有的方法和行为好像无缓冲. 更具体地说: * </p> * <ul> * <li>clear()必须抛出一个IOException</li> * <li>clearBuffer()什么都不做</li> * <li>getBufferSize()总是返回 0</li> * <li>getRemaining()总是返回 0</li> * </ul> * * @param writer 返回的JspWriter发送输出的Writer. * @return 写入给定Writer的新的JspWriter. * @since 2.0 */ public JspWriter pushBody( java.io.Writer writer ) { return null; // XXX to implement } /** * 返回之前pushBody()保存的JspWriter "out", 并更新JspContext的页面范围属性命名空间中的"out"属性的值. * * @return 保存的JspWriter. */ public JspWriter popBody() { return null; // XXX to implement } }
true
9ba55f48f0dcf7686a086d5956859378eff2bb58
Java
smshen/sky-batch
/src/main/java/com/usee/sky/batch/processor/MessagesItemProcessor.java
UTF-8
519
2.34375
2
[]
no_license
package com.usee.sky.batch.processor; import org.springframework.batch.item.ItemProcessor; import org.springframework.stereotype.Component; import com.usee.sky.model.Message; import com.usee.sky.model.User; @Component("messageProcessor") public class MessagesItemProcessor implements ItemProcessor<User, Message> { public Message process(User user) throws Exception { Message m = new Message(); m.setContent("Hello " + user.getName() + ",please pay promptly at the end of this month."); return m; } }
true
9f0eaeeecd7fcf2a19a415c38523feb39fe0f5aa
Java
HiEvi/javaTest
/src/everyday/three/RectCover.java
UTF-8
697
3.984375
4
[]
no_license
package everyday.three; /** * 题目描述 * 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法? * n 1 2 3 4 * 方法数 1 2 3 5 * 解决思想:我的:由于宽度不变,都是2,则长度可以看成由1或2组成,问题就变成了n可以有多少种1或2组成的方法 */ public class RectCover { public int RectCover(int n) { if (n==0 || n==1 || n==2) { return n; } int a = 2, b = 1; for (int i=3; i<=n; ++i) { a = a + b; b = a - b; } return a; } }
true
4ba528e176bc4337f90677260f0df23ea0a19770
Java
huangwei-github/yau_ksxt
/.svn/pristine/4b/4ba528e176bc4337f90677260f0df23ea0a19770.svn-base
UTF-8
973
1.859375
2
[]
no_license
package com.lanou.service.impl; import com.github.pagehelper.PageHelper; import com.lanou.dao.INoticeMapper; import com.lanou.entity.pojo.TbNotice; import com.lanou.service.INoticeService; import com.lanou.util.PageSplitor; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class NoticeService implements INoticeService { @Autowired private SqlSessionFactory sqlSessionFactory; @Autowired private INoticeMapper noticeMapper; public List<TbNotice> findTopNotice(PageSplitor splitor) { SqlSession session = sqlSessionFactory.openSession(); PageHelper.startPage(splitor.getPageNum(),splitor.getPageSize()); List<TbNotice> noticeList = session.selectList("com.lanou.dao.INoticeMapper.selectAll"); return noticeList; } }
true
1833a5c5e6fd571f9e3e3709ad372fac983b3bc6
Java
yh1993/Treasure
/app/src/main/java/com/dell/treasure/rank/TaskRankActivity.java
UTF-8
9,249
1.898438
2
[]
no_license
package com.dell.treasure.rank; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.TextView; import android.widget.Toast; import com.dell.treasure.R; import com.dell.treasure.service.UserInfo; import com.dell.treasure.share.BaseActivity; import com.dell.treasure.support.CurrentUser; import com.dell.treasure.support.NetUtil; import com.orhanobut.logger.Logger; import net.sf.json.JSONArray; import org.ksoap2.SoapFault; import java.util.ArrayList; import java.util.List; /** * Created by yh on 2017/11/20. */ public class TaskRankActivity extends BaseActivity { private RecyclerView mRecyclerView; private ArrayList<TaskRankItem> mTaskItems; private TaskRankAdapter adapter = null; private ProgressDialog mProgressDialog; private int flag = 0; private TextView money_text; private String userId; private String userName; private String taskId; private String money; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.fragment_main_rank); userName = CurrentUser.getOnlyUser().getUsername(); userId = CurrentUser.getOnlyUser().getUserId(); mTaskItems = new ArrayList<TaskRankItem>(); mRecyclerView=(RecyclerView) findViewById(R.id.recylerView); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setHasFixedSize(true); money_text = (TextView) findViewById(R.id.money_text); taskId = getIntent().getStringExtra("TaskId"); new getTaskRankTask().execute(); startService(new Intent(this, UserInfo.class)); } class getTaskRankTask extends AsyncTask<Void ,Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); mProgressDialog = new ProgressDialog(TaskRankActivity.this); mProgressDialog.setMessage("刷新中.."); mProgressDialog.setIndeterminate(false); mProgressDialog.setCancelable(true); mProgressDialog.show(); } @Override protected Void doInBackground(Void... params) { String json = null; try { money = NetUtil.getTaskReward(userId,taskId); } catch (SoapFault | NullPointerException soapFault) { soapFault.printStackTrace(); } try { json = NetUtil.TaskPartInfo(taskId); } catch (SoapFault | NullPointerException soapFault) { soapFault.printStackTrace(); } if (json == null || money == null){ flag = 1; }else { mTaskItems.clear(); JSONArray user_json = JSONArray.fromObject(json); List<ArrayList<String>> list = JSONArray.toList(user_json,ArrayList.class); int size = list.size(); for(int i = 0; i< size;i++){ JSONArray user = JSONArray.fromObject(list.get(i)); List<String> item = JSONArray.toList(user,ArrayList.class); String mUserName = item.get(0); String mtime = item.get(1); String mlength = item.get(2); String mfind = item.get(3); String mRegisNum = item.get(4); String mReward = item.get(5); TaskRankItem mTaskItem = new TaskRankItem(mUserName,mtime,mlength,mfind,mRegisNum,mReward); Log.d("result", "task item: "+mTaskItem.toString()); mTaskItems.add(mTaskItem); } // JSONArray user_json = JSONArray.fromObject(json); // List list = (List) JSONArray.toCollection(user_json, TaskRankItem.class); // Iterator it = list.iterator(); // while(it.hasNext()){ // TaskRankItem item = (TaskRankItem) it.next(); // if(item.getUserName().equals(userName)){ // mTaskItems.add(item); // break; // } // } // mTaskItems.addAll(list); } return null; } @Override protected void onPostExecute(Void aVoid) { if(flag == 1){ Toast.makeText(TaskRankActivity.this,"数据获取失败,请尝试重新进入该界面",Toast.LENGTH_LONG).show(); }else { money_text.setText(money+"元"); TaskRankActivity.this.runOnUiThread(new Runnable() { @Override public void run() { adapter = new TaskRankAdapter(TaskRankActivity.this, mTaskItems); mRecyclerView.setAdapter(adapter); } }); } mProgressDialog.dismiss(); } } class TaskRankAdapter extends RecyclerView.Adapter<TaskRankAdapter.MyViewHolder>{ private Context context; private List<TaskRankItem> list; public TaskRankAdapter(Context context, List<TaskRankItem> list){ this.context = context; this.list = list; } @Override public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { return new MyViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_main_rank_item, viewGroup,false)); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { final int i = position; MyViewHolder myViewHolder = (MyViewHolder) holder; if(i%2!=0){ myViewHolder.getRoot().setBackgroundColor(Color.argb(255,223,223,223)); } String netName= mTaskItems.get(i).getUserName(); myViewHolder.getNameText().setText(netName); if(netName.equals(userName)){ myViewHolder.getNameText().setBackgroundColor(Color.argb(255,0,150,255)); myViewHolder.getNameText().setTextColor(Color.WHITE); }else{ myViewHolder.getNameText().setBackgroundColor(Color.TRANSPARENT); myViewHolder.getNameText().setTextColor(Color.BLACK); } myViewHolder.getTimeText().setText(mTaskItems.get(i).gettime()); myViewHolder.getLengthText().setText(mTaskItems.get(i).getlength()); myViewHolder.getFindText().setText(mTaskItems.get(i).getfind()); myViewHolder.getRegisNumText().setText(mTaskItems.get(i).getRegisNum()); myViewHolder.getRewardText().setText(mTaskItems.get(i).getReward()); // myViewHolder.getmMoneyText().setText(mTaskItems.get(i).getmMoney()); } @Override public int getItemCount() { return (null != list ? list.size() : 0); } class MyViewHolder extends RecyclerView.ViewHolder { private View mRoot; private TextView mNameText; private TextView mTimeText; private TextView mLengthText; private TextView mFindText; private TextView mRegisNumText; private TextView mRewardText; // private TextView mMoneyText; public MyViewHolder(View root) { super(root); mRoot = root; mNameText = (TextView) root.findViewById(R.id.item_name_text); mTimeText = (TextView) root.findViewById(R.id.item_time_text); mLengthText = (TextView) root.findViewById(R.id.item_length_text); mFindText = (TextView) root.findViewById(R.id.item_find_text); mRegisNumText = (TextView)root.findViewById(R.id.item_regisNum_text); mRewardText = (TextView)root.findViewById(R.id.item_reward_text); // mMoneyText = (TextView) root.findViewById(R.id.item_money); } public TextView getNameText() { return mNameText; } public TextView getTimeText() { return mTimeText; } public TextView getLengthText() { return mLengthText; } public TextView getFindText() { return mFindText; } public View getRoot() { return mRoot; } public TextView getRegisNumText() { return mRegisNumText; } public TextView getRewardText() { return mRewardText; } // public TextView getmMoneyText() {return mMoneyText;} } } }
true
6ecbd0266f8bfd05ec58d49b1250000c76bd09ca
Java
longlivetmj/roadrunner
/src/main/java/com/tmj/tms/utility/DateFormatter.java
UTF-8
24,956
3.234375
3
[]
no_license
package com.tmj.tms.utility; import java.text.Format; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Month; import java.util.*; import java.util.concurrent.TimeUnit; public class DateFormatter { private Format formatter; private NumberFormatter numberFormatter = new NumberFormatter(); public static Date getStartOfTheDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } public static Date getEndOfTheDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } public static String getTimeDifferenceSigned(Date dateOne, Date dateTwo) { String diff = ""; Calendar calendar = Calendar.getInstance(); if (dateOne == null || dateTwo == null) { return diff; } else { calendar.setTime(dateOne); int year1 = calendar.get(Calendar.YEAR); calendar.setTime(dateTwo); int year2 = calendar.get(Calendar.YEAR); if (year1 == 1900 || year2 == 1900) { return diff; } else { long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime()); diff = String.format("%d h %d m", TimeUnit.MILLISECONDS.toHours(timeDiff), TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff))); if ((dateOne.getTime() - dateTwo.getTime()) < 0) { diff = "- " + diff; } } } return diff; } public static String getTimeDifferenceSpecial(Date dateOne, Date dateTwo) { String diff = ""; Calendar calendar = Calendar.getInstance(); if (dateOne == null || dateTwo == null) { return diff; } else { calendar.setTime(dateOne); int year1 = calendar.get(Calendar.YEAR); calendar.setTime(dateTwo); int year2 = calendar.get(Calendar.YEAR); if (year1 == 1900 || year2 == 1900) { return diff; } else { long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime()); diff = String.format("%d d %d h", TimeUnit.MILLISECONDS.toDays(timeDiff), TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.HOURS.toHours(TimeUnit.MILLISECONDS.toHours(timeDiff))); } } return diff; } public static String getTimeDifference(Date dateOne, Date dateTwo) { String diff = ""; Calendar calendar = Calendar.getInstance(); if (dateOne == null || dateTwo == null) { return diff; } else { calendar.setTime(dateOne); int year1 = calendar.get(Calendar.YEAR); calendar.setTime(dateTwo); int year2 = calendar.get(Calendar.YEAR); if (year1 == 1900 || year2 == 1900) { return diff; } else { long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime()); diff = String.format("%d h %d m", TimeUnit.MILLISECONDS.toHours(timeDiff), TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff))); } } return diff; } public static long getTimeDifferenceLong(Date dateOne, Date dateTwo) { long diff = 0; Calendar calendar = Calendar.getInstance(); if (dateOne == null || dateTwo == null) { return diff; } else { calendar.setTime(dateOne); int year1 = calendar.get(Calendar.YEAR); calendar.setTime(dateTwo); int year2 = calendar.get(Calendar.YEAR); if (year1 == 1900 || year2 == 1900) { return diff; } else { diff = Math.abs(dateOne.getTime() - dateTwo.getTime()); } } return diff; } public static String calculateDemurrageTime(Date dateOne, Date dateTwo) { String returnString = ""; long timeGap = DateFormatter.getTimeDifferenceLong(dateOne, dateTwo); long basicTime = 86400000; if (timeGap > basicTime) { returnString = convertMillisecondsToHoursAndMin(timeGap - basicTime); } return returnString; } public static long calculateDemurrageTimeLong(Date dateOne, Date dateTwo) { long timeGap = DateFormatter.getTimeDifferenceLong(dateOne, dateTwo); long basicTime = 86400000; if (timeGap > basicTime) { return (timeGap - basicTime); } else { return 0; } } public static String percentageOfTwoLongValues(long divisor, long divider) { return new NumberFormatter().convertToTwoDigits(Double.longBitsToDouble(divisor * 100) / Double.longBitsToDouble(divider)); } public static String convertMillisecondsToHoursAndMin(long diff) { String format; format = String.format("%d h %d m", TimeUnit.MILLISECONDS.toHours(diff), TimeUnit.MILLISECONDS.toMinutes(diff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(diff))); return format; } public static boolean getOnTimePlacedStatus(Date dateOne, Date dateTwo) { boolean status = false; Calendar calendar = Calendar.getInstance(); if (dateOne == null || dateTwo == null) { return status; } else { calendar.setTime(dateOne); int year1 = calendar.get(Calendar.YEAR); calendar.setTime(dateTwo); int year2 = calendar.get(Calendar.YEAR); if (year1 == 1900 || year2 == 1900) { return status; } else { DateFormatter dateFormatter = new DateFormatter(); Date dateTwoPlusThirty = dateFormatter.addMinutesToDate(dateTwo, 30); if ((dateOne.getTime() <= dateTwoPlusThirty.getTime())) { status = true; } } } return status; } public static String replaceSquareBrackets(String string) { return string.replaceAll("\\[", "").replaceAll("\\]", ""); } public static void main(String[] args) throws ParseException { DateFormatter dateFormatter = new DateFormatter(); Date start = dateFormatter.convertToDateLongWebService("2018-01-05 11:30 am"); Date end = dateFormatter.convertToDateLongWebService("2018-01-06 10:30 am"); System.out.println(">>>>>>>>>>" + DateFormatter.getDateDiff(start, end, TimeUnit.HOURS)); } public static String convertMinutesToHumanReadable(Integer totalMinutes) { String format; format = String.format("%d h %d m", TimeUnit.MINUTES.toHours(totalMinutes), TimeUnit.MINUTES.toMinutes(totalMinutes) - TimeUnit.HOURS.toMinutes(TimeUnit.MINUTES.toHours(totalMinutes))); return format; } public static Date getStartOfLastMonth() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); calendar.set(Calendar.DAY_OF_MONTH, 1); return DateFormatter.getStartOfTheDay(calendar.getTime()); } public static Date getLastDayOfMonth(Integer year, Integer month) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.DAY_OF_MONTH, -1); return DateFormatter.getStartOfTheDay(calendar.getTime()); } public static Date getEndOfLastMonth() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.DAY_OF_MONTH, -1); return DateFormatter.getEndOfTheDay(calendar.getTime()); } public static String getMonth(Integer month) { String monthName = ""; try { monthName = Month.of(month).name(); } catch (Exception e) { System.out.println("Month Convertion Errror"); } return monthName; } public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) { long diffInMillies = date2.getTime() - date1.getTime(); return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS); } public static Integer getMonthOfDate(Date date) { Integer month = null; try { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); month = calendar.get(Calendar.MONTH); } catch (Exception e) { e.printStackTrace(); } return month; } public static Date getStartOfThisMonth() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 1); return DateFormatter.getStartOfTheDay(calendar.getTime()); } public static Date getEndOfThisMonth() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); calendar.add(Calendar.DAY_OF_MONTH, -1); return DateFormatter.getEndOfTheDay(calendar.getTime()); } public String returnSortFormattedDate(Date date) { String formattedDate = null; try { formatter = new SimpleDateFormat("yyyy-MM-dd"); formattedDate = formatter.format(date); } catch (Exception e) { System.out.println(e.getMessage()); } return formattedDate; } public String returnLongFormattedDateTime(Date date) { String formattedDate = null; try { if (date != null) { formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm a"); formattedDate = formatter.format(date); } else { formattedDate = ""; } } catch (Exception e) { System.out.println(e.getMessage()); } return formattedDate; } public String returnLongFormattedDateTime24(Date date) { String formattedDate = null; try { formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); formattedDate = formatter.format(date); } catch (Exception e) { System.out.println(e.getMessage()); } return formattedDate; } public Date convertToDate(String dateString) { Date date = null; try { date = new SimpleDateFormat("dd/MM/yyyy").parse(dateString); } catch (Exception e) { e.printStackTrace(); } return date; } public Date convertToDateSpecial(String dateString) { Date date = null; try { date = new SimpleDateFormat("yyyy-MM-dd").parse(dateString); } catch (Exception e) { e.printStackTrace(); } return date; } public String returnFormattedDateIncito(Date date) { String formattedDate = ""; try { formatter = new SimpleDateFormat("yyyy-MM-dd"); formattedDate = formatter.format(date); } catch (Exception e) { e.printStackTrace(); } return formattedDate; } public String returnFormattedDateGeneral(Date date) { String formattedDate = ""; try { formatter = new SimpleDateFormat("dd/MM/yyyy"); formattedDate = formatter.format(date); } catch (Exception e) { e.printStackTrace(); } return formattedDate; } public String returnFormattedDate(Date date) { String formattedDate = ""; try { formatter = new SimpleDateFormat("dd MMMM, yyyy"); formattedDate = formatter.format(date); } catch (Exception e) { e.printStackTrace(); } return formattedDate; } public Date convertToDateLong(String dateString) { Date date = null; try { date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString); } catch (Exception e) { e.printStackTrace(); } return date; } public Date convertToDateLongWebService(String dateString) { Date date = null; try { date = new SimpleDateFormat("yyyy-MM-dd hh:mm a").parse(dateString); } catch (Exception e) { e.printStackTrace(); } return date; } public Date convertToDateDayEnd(String dateString) { Date date = null; try { date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(dateString); } catch (Exception e) { e.printStackTrace(); } return date; } public Date getBaseDateForSql() { String dateString = "1900-01-01"; Date date = null; try { date = new SimpleDateFormat("yyyy-MM-dd").parse(dateString); } catch (Exception e) { e.printStackTrace(); } return date; } public String getTimeSpendInFactory(Date arrivedAtFactory, Date departedFromFactory) { String time = ""; Long diff = DateFormatter.getTimeDifferenceLong(arrivedAtFactory, departedFromFactory); Double diffInHours = diff.doubleValue() / 3600000; time = numberFormatter.convertToTwoDecimal(diffInHours); return time; } public String getTimeSpendInYard(Date arrivedAtYard, Date departedFromYard) { String time = ""; Long diff = DateFormatter.getTimeDifferenceLong(arrivedAtYard, departedFromYard); Double diffInHours = diff.doubleValue() / 3600000; time = numberFormatter.convertToTwoDecimal(diffInHours); return time; } public String getTravellingTime(Date departedFromFactory, Date arrivedAtYard) { String time = ""; Long diff = DateFormatter.getTimeDifferenceLong(departedFromFactory, arrivedAtYard); Double diffInHours = diff.doubleValue() / 3600000; time = numberFormatter.convertToTwoDecimal(diffInHours); return time; } public String getChargeableDemmuraageHours(Date AED_AET, Date ACD_ACT) { String time = ""; Long diff = DateFormatter.calculateDemurrageTimeLong(AED_AET, ACD_ACT); if (diff.equals(0)) { time = "0.0"; } else { Double diffInHours = diff.doubleValue() / 3600000; time = numberFormatter.convertToTwoDecimal(diffInHours); } return time; } public Date changeDateToTomorrow(Date enteredDate, Date comparisonDate) { Calendar toDay = Calendar.getInstance(); int dayOfYear = toDay.get(Calendar.DAY_OF_YEAR); Calendar enteredCal = Calendar.getInstance(); enteredCal.setTime(enteredDate); enteredCal.set(Calendar.DAY_OF_YEAR, dayOfYear + 1); enteredCal.set(Calendar.YEAR, toDay.get(Calendar.YEAR)); if (comparisonDate.after(enteredCal.getTime())) { enteredCal.add(Calendar.DAY_OF_YEAR, 1); } return enteredCal.getTime(); } public boolean isTheDateToday(Date searchDate) { boolean flag; Calendar today = Calendar.getInstance(); today.set(Calendar.HOUR_OF_DAY, 00); today.set(Calendar.MINUTE, 00); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); Date getTodayDate = today.getTime(); Integer difference = getTodayDate.compareTo(searchDate); if (difference == 0) { flag = true; } else { flag = false; } return flag; } public Date convertToDateDotFormat(String dateString) throws ParseException { return new SimpleDateFormat("dd.MM.yyyy").parse(dateString); } public Date convertToDateLongWithTime(String dateString) throws ParseException { return new SimpleDateFormat("dd.MM.yyyy HH:mm").parse(dateString); } public Date addMinutesToDate(Date date, int minutes) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MINUTE, minutes); return calendar.getTime(); } public String returnSortFormattedDateSpecial(Date date) { String formattedDate = null; try { formatter = new SimpleDateFormat("dd/MM/yyyy"); formattedDate = formatter.format(date); } catch (Exception e) { e.printStackTrace(); } return formattedDate; } public String returnYearAndMonthName() { String formattedDate = null; try { Date today = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM - YYYY"); formattedDate = dateFormat.format(today); } catch (Exception e) { e.printStackTrace(); } return formattedDate; } public String returnFormattedDateTime(Date date) { String formattedDate = null; try { formatter = new SimpleDateFormat("dd/MM/yy hh:mm a"); formattedDate = formatter.format(date); } catch (Exception e) { e.printStackTrace(); } return formattedDate; } public String getFormattedTimePortion(Date collectionTime) { String formattedTime = null; try { formatter = new SimpleDateFormat("hh:mm a"); formattedTime = formatter.format(collectionTime); } catch (Exception e) { e.printStackTrace(); } return formattedTime; } public Map<Integer, String> getDaysOfWeek() { Map<Integer, String> weekMap = new HashMap<Integer, String>() {{ put(1, "Sunday"); put(2, "Monday"); put(3, "Tuesday"); put(4, "Wednesday"); put(5, "Thursday"); put(6, "Friday"); put(7, "Saturday"); }}; return weekMap; } public Integer getDayOfWeekFromDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_WEEK); } public Integer getMinutesBetweenTwoTime(Date deliveryDate, Date arrivalDate) { Integer timeInMin = 0; long timeGap = DateFormatter.getTimeDifferenceLong(deliveryDate, arrivalDate); if (timeGap == 0) { timeInMin = 0; } else { Double diffInHours = Math.ceil(timeGap / 60000.0); timeInMin = diffInHours.intValue(); } return timeInMin; } public Date getAmendedTimeFromArrivalTime(Date deliveryDate, Date arrivalDate) { DateFormatter dateFormatter = new DateFormatter(); Integer timeInMin = dateFormatter.getMinutesBetweenTwoTime(deliveryDate, arrivalDate); Date tomorrowDate = dateFormatter.changeDateToTomorrow(arrivalDate, new Date()); return dateFormatter.addMinutesToDate(tomorrowDate, timeInMin); } public Date addNDaysToADate(int n, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DATE, n); return calendar.getTime(); } public Date addMonthsToADate(int n, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, n); return calendar.getTime(); } public Date setHourAndMinute(String hourAndMinute, Date date) { String[] hourAndMinuteArray = hourAndMinute.split(":"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourAndMinuteArray[0])); calendar.set(Calendar.MINUTE, Integer.parseInt(hourAndMinuteArray[1])); return calendar.getTime(); } public Integer getCurrentWeekNo() { Integer weekNo = 0; try { Calendar cal = Calendar.getInstance(); weekNo = cal.get(Calendar.WEEK_OF_YEAR); } catch (Exception e) { e.printStackTrace(); } return weekNo; } public String dateRangeFromWeekNo(Integer weekNo) { String dateRange = ""; try { Calendar cal = Calendar.getInstance(); cal.set(Calendar.WEEK_OF_YEAR, weekNo); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); String startDate = this.returnSortFormattedDate(cal.getTime()); cal.add(Calendar.DATE, 6); String endDate = this.returnSortFormattedDate(cal.getTime()); dateRange = startDate + " to " + endDate; } catch (Exception e) { e.printStackTrace(); } return dateRange; } public Date getDateByWeekNoDayOfWeek(Integer weekNo, Integer dayOfWeek) { Date date = null; try { Calendar cal = Calendar.getInstance(); if (dayOfWeek == 1) { cal.set(Calendar.WEEK_OF_YEAR, weekNo + 1); cal.set(Calendar.DAY_OF_WEEK, dayOfWeek); } else { cal.set(Calendar.WEEK_OF_YEAR, weekNo); cal.set(Calendar.DAY_OF_WEEK, dayOfWeek); } cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); date = cal.getTime(); } catch (Exception e) { e.printStackTrace(); } return date; } public List<String> dateListFromWeekNo(Integer weekNo) { List<String> dateList = new ArrayList<String>(); try { Calendar cal = Calendar.getInstance(); cal.set(Calendar.WEEK_OF_YEAR, weekNo); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); dateList.add(this.returnSortFormattedDate(cal.getTime())); for (int i = 0; i < 6; i++) { cal.add(Calendar.DATE, 1); dateList.add(this.returnSortFormattedDate(cal.getTime())); } } catch (Exception e) { e.printStackTrace(); } return dateList; } public Date changeDate(Date arrivalDate, Date arrivalTime) { Calendar calendar = Calendar.getInstance(); calendar.setTime(arrivalDate); Calendar arrivalTimeCalendar = Calendar.getInstance(); arrivalTimeCalendar.setTime(arrivalDate); calendar.set(Calendar.HOUR_OF_DAY, arrivalTimeCalendar.get(Calendar.HOUR_OF_DAY)); calendar.set(Calendar.MINUTE, arrivalTimeCalendar.get(Calendar.MINUTE)); return calendar.getTime(); } public Date changeDateToAnother(Date originalDate, Date newDate) { Date amendedDate = null; try { Calendar originalCalender = Calendar.getInstance(); originalCalender.setTime(originalDate); Calendar newDateCalender = Calendar.getInstance(); newDateCalender.setTime(newDate); originalCalender.set(Calendar.MONTH, newDateCalender.get(Calendar.MONTH)); originalCalender.set(Calendar.DAY_OF_MONTH, newDateCalender.get(Calendar.DAY_OF_MONTH)); amendedDate = originalCalender.getTime(); } catch (Exception e) { e.printStackTrace(); } return amendedDate; } public String dayOfWeek(Date date) { String dayOfWeek = ""; try { SimpleDateFormat formatter = new SimpleDateFormat("EEEE"); dayOfWeek = formatter.format(date); } catch (Exception e) { System.out.println("Parse Exception"); } return dayOfWeek; } public boolean currentTimeBetweenTwoHours(int from, int to) { Date date = new Date(); Calendar c = Calendar.getInstance(); c.setTime(date); int t = c.get(Calendar.HOUR_OF_DAY) * 100 + c.get(Calendar.MINUTE); boolean isBetween = to > from && t >= from && t <= to || to < from && (t >= from || t <= to); return isBetween; } public String getCurrentMonthName() { String formattedDate = null; try { Date today = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("MMM"); formattedDate = dateFormat.format(today); } catch (Exception e) { e.printStackTrace(); } return formattedDate; } }
true
973a573a5ad5826e9e1ef04cfe5c9c5ca37f1f96
Java
MohdImranulHoqueLimon/product-list-vuejs
/src/main/java/com/vuejs/practice/User.java
UTF-8
249
1.765625
2
[]
no_license
package com.vuejs.practice; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { int id; String name; int age; String profession; }
true
9fd120eb1bc2d08d7a2b49b8831c0124a6bbf4f8
Java
littlehorse1019/std-arrow
/src/main/java/com/std/framework/model/orm/MapRule.java
GB18030
394
1.773438
2
[]
no_license
package com.std.framework.model.orm; /** * @author Luox ORMMAPING ӳӿ */ public interface MapRule { public String objMapTab (String className) throws Exception; public String objMapCol (String fieldName) throws Exception; public String tabMapObj (String className) throws Exception; public String colMapObj (String fieldName) throws Exception; }
true
7e02489c8c7cb2b5d92cba80abac7ad3232447a8
Java
ty2009137128/speczoo2
/src/com/graduation/filter/RequestInterceptor.java
UTF-8
1,163
2.28125
2
[]
no_license
package com.graduation.filter; import com.graduation.model.User; import com.graduation.web.SessionContext; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; //没有起作用,不知道为什么,改为在Systemcontextfilter中处理 public class RequestInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); String sessionId = request.getParameter("sessionId"); if (null != sessionId && !"".equals(sessionId.trim())) { session = SessionContext.getSession(sessionId); } User loginUser = (User) session.getAttribute("loginUser"); if (null == loginUser) { response.sendRedirect(request.getContextPath() + "/user/login"); return false; } return super.preHandle(request, response, handler); } }
true
98f3fa60840cbecfe26d6c63a59d46548a63aae9
Java
noormoha/DCCast
/dccast/graphTheory/steinLib/STPTranslator.java
UTF-8
10,598
2.96875
3
[ "MIT" ]
permissive
package graphTheory.steinLib; import graphTheory.graph.Arc; import graphTheory.graph.DirectedGraph; import graphTheory.graph.UndirectedGraph; import graphTheory.instances.steiner.classic.SteinerDirectedInstance; import graphTheory.instances.steiner.classic.SteinerInstance; import graphTheory.instances.steiner.classic.SteinerUndirectedInstance; import graphTheory.utils.FileManager; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * This class contains static method to translate .stp files into a * {@link SteinerInstance}, directed or not, and to translate a * {@link SteinerInstance} into a .stp file. * * @author Watel Dimitri * */ public class STPTranslator { /** * Return the {@link SteinerDirectedInstance} or the * {@link SteinerUndirectedInstance} conresponding to the .stp file in * input. If the file describes a graph containing directed arcs and * undirected edges, then this method returns null. * * @param nomFic * path of the file describing the instance we want to build. * @return * @throws STPTranslationException */ public static SteinerInstance translateFile(String nomFic) throws STPTranslationException { FileManager f = new FileManager(); f.openRead(nomFic); String s; int lineNumber = 0; s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.EMPTY_FILE, nomFic, lineNumber, null); } s = s.toLowerCase(); // On vérifie que le fichier est au bon format if (!s.contains("33d32945")) { throw new STPTranslationException( STPTranslationExceptionEnum.BAD_FORMAT_CODE, nomFic, lineNumber, s); } // On saute l'espace réservé aux commentaires. while (!s.contains("section graph")) { s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.NO_SECTION_GRAPH, nomFic, lineNumber, s); } s = s.toLowerCase(); } // On récupère le nombre de noeuds. s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.EMPTY_SECTION_GRAPH, nomFic, lineNumber, s); } s = s.toLowerCase(); s = s.trim(); Pattern p = Pattern.compile("nodes +(\\d+)"); Matcher m = p.matcher(s); if (!m.matches()) throw new STPTranslationException( STPTranslationExceptionEnum.NODE_NUMBER_BAD_FORMAT, nomFic, lineNumber, s); // On récupère le nombre d'arcs s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.EDGE_NUMBER_BAD_FORMAT, nomFic, lineNumber, s); } s = s.toLowerCase(); s = s.trim(); p = Pattern.compile("(edges|arcs) +(\\d+)"); m = p.matcher(s); boolean isDirected; int noe; char letter; SteinerInstance g; if (m.matches()) { isDirected = m.group(1).equals("arcs"); if (isDirected) { DirectedGraph dg = new DirectedGraph(); g = new SteinerDirectedInstance(dg); letter = 'a'; } else { UndirectedGraph ug = new UndirectedGraph(); g = new SteinerUndirectedInstance(ug); letter = 'e'; } noe = Integer.valueOf(m.group(2)); } else { throw new STPTranslationException( STPTranslationExceptionEnum.EDGE_NUMBER_BAD_FORMAT, nomFic, lineNumber, s); } s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.NO_SECTION_GRAPH_CONTENT, nomFic, lineNumber, s); } s = s.toLowerCase(); s = s.trim(); while (s.equals("")) { s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.NO_SECTION_GRAPH_CONTENT, nomFic, lineNumber, s); } s = s.toLowerCase(); s = s.trim(); } p = Pattern.compile(letter + " +(\\d+) +(\\d+) +(\\d+)"); int cost; Integer n1, n2; while (!s.equals("end")) { m = p.matcher(s); if (m.matches()) { n1 = Integer.valueOf(m.group(1)); n2 = Integer.valueOf(m.group(2)); cost = Integer.valueOf(m.group(3)); if (!g.getGraph().contains(n1)) g.getGraph().addVertice(n1); if (!g.getGraph().contains(n2)) g.getGraph().addVertice(n2); Arc a; if (isDirected) a = g.getGraph().addDirectedEdge(n1, n2); else a = g.getGraph().addUndirectedEdge(n1, n2); g.setCost(a, cost); } else { throw new STPTranslationException( STPTranslationExceptionEnum.EDGE_DESCRIPTION_BAD_FORMAT, nomFic, lineNumber, s); } s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.FILE_ENDED_BEFORE_EOF_SG, nomFic, lineNumber, s); } s = s.toLowerCase(); s = s.trim(); noe--; } if (noe != 0) { throw new STPTranslationException( STPTranslationExceptionEnum.INCOHERENT_NB_EDGES, nomFic, lineNumber, s); } // On saute jusqu'aux terminaux while (!s.contains("section terminals")) { s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.NO_SECTION_TERM, nomFic, lineNumber, s); } s = s.toLowerCase(); } s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.EMPTY_SECTION_TERM, nomFic, lineNumber, s); } s = s.toLowerCase(); p = Pattern.compile("terminals +(\\d+)"); m = p.matcher(s); int not; int size = g.getGraph().getNumberOfVertices(); if (m.matches()) { not = Integer.valueOf(m.group(1)); if (not > size || not <= 0) { throw new STPTranslationException( STPTranslationExceptionEnum.STRANGE_NB_TERM, nomFic, lineNumber, s); } } else { throw new STPTranslationException( STPTranslationExceptionEnum.TERMINALS_NUMBER_BAD_FORMAT, nomFic, lineNumber, s); } boolean rootSet = false; s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.NO_SECTION_TERM_CONTENT, nomFic, lineNumber, s); } s = s.toLowerCase(); s = s.trim(); p = Pattern.compile("(t +(\\d+))|(root +(\\d+))"); while (!s.equals("end")) { m = p.matcher(s); if (m.matches()) { if (m.group(3) != null) { if (rootSet || !isDirected) { throw new STPTranslationException( STPTranslationExceptionEnum.TOO_MUCH_ROOT_SET, nomFic, lineNumber, s); } else { rootSet = true; ((SteinerDirectedInstance) g).setRoot(Integer.valueOf(m .group(4))); } } else { n1 = Integer.valueOf(m.group(2)); g.setRequired(n1, true); not--; } } else { throw new STPTranslationException( STPTranslationExceptionEnum.TERMINALS_DESC_BAD_FORMAT, nomFic, lineNumber, s); } s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.FILE_ENDED_BEFORE_EOF_ST, nomFic, lineNumber, s); } s = s.toLowerCase(); } if (not != 0) { throw new STPTranslationException( STPTranslationExceptionEnum.INCOHERENT_NB_TERMS, nomFic, lineNumber, s); } // On saute l'espace reservé aux coordonnées while (!s.contains("eof")) { s = f.readLine(); lineNumber++; if (s == null) { throw new STPTranslationException( STPTranslationExceptionEnum.FILE_ENDED_BEFORE_EOF, nomFic, lineNumber, s); } s = s.toLowerCase(); } return g; } /** * * Return the {@link SteinerDirectedInstance} conresponding to the .stp file * in input. If the file describes a graph containing undirected edges, then * this method returns null. * * @param nomFic * path of the file describing the instance we want to build. * @return * @throws STPTranslationException */ public static SteinerDirectedInstance translateDirectedFile(String nomFic) throws STPTranslationException { SteinerInstance g = translateFile(nomFic); if (g == null || g instanceof SteinerUndirectedInstance) return null; else return (SteinerDirectedInstance) g; } /** * * Return the {@link SteinerUndirectedInstance} conresponding to the .stp * file in input. If the file describes a graph containing directed arcs, * then this method returns null. * * @param nomFic * path of the file describing the instance we want to build. * @return * @throws STPTranslationException */ public static SteinerUndirectedInstance translateUndirectedFile( String nomFic) throws STPTranslationException { SteinerInstance g = translateFile(nomFic); if (g == null || g instanceof SteinerDirectedInstance) return null; else return (SteinerUndirectedInstance) g; } /** * Translate the Steiner instance g into a .stp file, which path is nomFic. * * @param g * @param nomFic */ public static void translateSteinerGraph(SteinerInstance g, String nomFic) { translateSteinerGraph(g, nomFic, ""); } /** * Translate the Steiner instance g into a .stp file, which path is nomFic. * Associate the instance to the name given in parameter in the file. * * @param g * @param nomFic */ public static void translateSteinerGraph(SteinerInstance g, String nomFic, String name) { boolean isDirected = g instanceof SteinerDirectedInstance; FileManager f = new FileManager(); f.openErase(nomFic); f.writeln("33d32945 STP File, STP Format Version 1.0"); f.writeln(); f.writeln("SECTION Comment"); f.writeln("Name \"" + name + "\""); f.writeln("Creator \"Dimitri Watel\""); f.writeln("Remark \"\""); f.writeln("END"); f.writeln(); f.writeln("SECTION Graph"); f.writeln("Nodes " + g.getGraph().getNumberOfVertices()); f.writeln((isDirected ? "Arcs" : "Edges") + " " + g.getGraph().getNumberOfEdges()); Iterator<Arc> it = g.getGraph().getEdgesIterator(); Arc a; while (it.hasNext()) { a = it.next(); f.writeln((isDirected ? 'A' : 'E') + " " + a.getInput() + " " + a.getOutput() + " " + g.getCost(a)); } f.writeln("END"); f.writeln(); f.writeln("SECTION Terminals"); f.writeln("Terminals " + g.getNumberOfRequiredVertices()); if (isDirected) { f.writeln("Root " + ((SteinerDirectedInstance) g).getRoot()); } Iterator<Integer> it2 = g.getRequiredVerticesIterator(); Integer n; while (it2.hasNext()) { n = it2.next(); f.writeln("T " + n); } f.writeln("END"); f.writeln(); f.writeln("EOF"); f.closeWrite(); } }
true
96b8a65bca1937c4bb0c050f74d11896f450320e
Java
mariza1991/learning
/firsttest/src/test/java/tests/newTests/pageObject/pages/Index.java
UTF-8
997
2.4375
2
[]
no_license
package tests.newTests.pageObject.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.Select; public class Index extends PageObject { @FindBy(name="fromPort") WebElement fromPortSelect; @FindBy(name="toPort") WebElement toPortSelect; @FindBy(css="input.btn.btn-primary") WebElement submitButton; public Index(WebDriver driver){ super(driver); } public boolean isInitialized() { driver.get("http://blazedemo.com/index.php"); return fromPortSelect.isDisplayed(); } public void chooseFlight(String from, String to) { Select selectFrom = new Select(fromPortSelect); selectFrom.selectByValue(from); Select selectTo = new Select(toPortSelect); selectTo.selectByValue(to); } public Reserve submit(){ submitButton.click(); return new Reserve(driver); } }
true
6bf48a42bfb9fc2595e2082c85e6767a8329100a
Java
silcab/tfgSactt
/SACTT-GUI/src/editorConsultaIntegrada.java
WINDOWS-1250
15,735
1.96875
2
[]
no_license
import java.awt.BorderLayout; import java.awt.Container; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.DefaultEditorKit; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.JMenuItem; import Area.area; import Categoria.categoria; import ConexionBBDD.conexion; import IdPalabra.idPalabra; import OtrasFunciones.consulta; import RasgoContenido.rasgocontenido; import javax.swing.JInternalFrame; import javax.swing.JDesktopPane; public class editorConsultaIntegrada extends JFrame { private Action openAction = new OpenAction(); private Action saveAction = new SaveAction(); private Action LanzarConsultaGUI = new LanzarConsultaGUI(this); JTextComponent textComp; private Hashtable actionHash = new Hashtable(); public static void main(String[] args) { editorConsultaIntegrada editor = new editorConsultaIntegrada(); editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); editor.setVisible(true); } // Create an editor. public editorConsultaIntegrada() { super("Swing Editor"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("SACTT Text Editor"); textComp = createTextComponent(); makeActionsPretty(); Container content = getContentPane(); getContentPane().setLayout(null); content.add(textComp); setJMenuBar(createMenuBar()); setSize(624, 506); } // Create the JTextComponent subclass. protected JTextComponent createTextComponent() { JTextArea ta = new JTextArea(); ta.setBounds(0, 0, 606, 435); ta.setLineWrap(true); return ta; } // Add icons and friendly names to actions we care about. protected void makeActionsPretty() { Action a; a = textComp.getActionMap().get(DefaultEditorKit.cutAction); a.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif")); a.putValue(Action.NAME, "Cut"); a = textComp.getActionMap().get(DefaultEditorKit.copyAction); a.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif")); a.putValue(Action.NAME, "Copy"); a = textComp.getActionMap().get(DefaultEditorKit.pasteAction); a.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif")); a.putValue(Action.NAME, "Paste"); a = textComp.getActionMap().get(DefaultEditorKit.selectAllAction); a.putValue(Action.NAME, "Select All"); } // Create a simple JToolBar with some buttons. /*protected JToolBar createToolBar() { }*/ // Create a JMenuBar with file & edit menus. protected JMenuBar createMenuBar() { JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("Archivo"); JMenu edit = new JMenu("Editar"); menubar.add(file); menubar.add(edit); JMenuItem menuItem = file.add(getOpenAction()); menuItem.setText("Abrir"); JMenuItem menuItem_1 = file.add(getSaveAction()); menuItem_1.setText("Guardar"); JMenuItem menuItem_2 = file.add(new ExitAction()); menuItem_2.setText("Salir"); JMenuItem mntmCortarAlPortapapeles = edit.add(textComp.getActionMap().get(DefaultEditorKit.cutAction)); mntmCortarAlPortapapeles.setText("Cortar al portapapeles"); JMenuItem menuItem_4 = edit.add(textComp.getActionMap().get(DefaultEditorKit.copyAction)); menuItem_4.setText("Copiar al portapapeles"); JMenuItem menuItem_3 = edit.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction)); menuItem_3.setText("Pegar"); JMenuItem menuItem_5 = edit.add(textComp.getActionMap().get(DefaultEditorKit.selectAllAction)); menuItem_5.setText("Seleccionar todo"); JMenu mnSactt = new JMenu("SACTT"); JMenuItem menuItemSACTT = mnSactt.add(getConsultaGUI()); menuItemSACTT.setText("Consulta"); menubar.add(mnSactt); return menubar; } protected Action getConsultaGUI() { return LanzarConsultaGUI; } // Subclass can override to use a different open action. protected Action getOpenAction() { return openAction; } // Subclass can override to use a different save action. protected Action getSaveAction() { return saveAction; } protected JTextComponent getTextComponent() { return textComp; } // ********** ACTION INNER CLASSES ********** // // A very simple exit action public class ExitAction extends AbstractAction { public ExitAction() { super("Exit"); } public void actionPerformed(ActionEvent ev) { System.exit(0); } } // An action that opens an existing file class OpenAction extends AbstractAction { public OpenAction() { super("Open", new ImageIcon("icons/open.gif")); } // Query user for a filename and attempt to open and read the file into // the // text component. public void actionPerformed(ActionEvent ev) { JFileChooser chooser = new JFileChooser(); if (chooser.showOpenDialog(editorConsultaIntegrada.this) != JFileChooser.APPROVE_OPTION) return; File file = chooser.getSelectedFile(); if (file == null) return; FileReader reader = null; try { reader = new FileReader(file); textComp.read(reader, null); } catch (IOException ex) { JOptionPane.showMessageDialog(editorConsultaIntegrada.this, "Archivo no encontrado", "ERROR", JOptionPane.ERROR_MESSAGE); } finally { if (reader != null) { try { reader.close(); } catch (IOException x) { } } } } } // An action that saves the document to a file class SaveAction extends AbstractAction { public SaveAction() { super("Save", new ImageIcon("icons/save.gif")); } // Query user for a filename and attempt to open and write the text // component's content to the file. public void actionPerformed(ActionEvent ev) { JFileChooser chooser = new JFileChooser(); if (chooser.showSaveDialog(editorConsultaIntegrada.this) != JFileChooser.APPROVE_OPTION) return; File file = chooser.getSelectedFile(); if (file == null) return; FileWriter writer = null; try { writer = new FileWriter(file); textComp.write(writer); } catch (IOException ex) { JOptionPane.showMessageDialog(editorConsultaIntegrada.this, "No se guard el archivo", "ERROR", JOptionPane.ERROR_MESSAGE); } finally { if (writer != null) { try { writer.close(); } catch (IOException x) { } } } } } class LanzarConsultaGUI extends AbstractAction { editorConsultaIntegrada editor; public LanzarConsultaGUI(editorConsultaIntegrada edi){editor = edi;} @Override public void actionPerformed(ActionEvent e) { try { conexion miconexion = new conexion(); miconexion.iniciarBBDD(); consultaGUIEditor consult = new consultaGUIEditor(miconexion.getMiConexion(), editor ); consult.frmConsulta.setVisible(true); } catch (InstantiationException | IllegalAccessException e1) { e1.printStackTrace(); } } } public void appendString(String pal){ //JTextComponent tC = new JTextField("Initial Text"); Document doc = textComp.getDocument(); try { Caret crt = textComp.getCaret(); doc.insertString(/*doc.getLength()*/crt.getDot(), pal, null); } catch (BadLocationException e) { e.printStackTrace(); }; } } class consultaGUIEditor{ JFrame frmConsulta; static Connection _conn; String seleccionado; editorConsultaIntegrada editor; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { conexion miconexion=new conexion(); miconexion.iniciarBBDD(); consultaGUI window = new consultaGUI(miconexion.getMiConexion()); window.frmConsulta.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. * @throws IllegalAccessException * @throws InstantiationException */ public consultaGUIEditor(Connection conn, editorConsultaIntegrada edi) throws InstantiationException, IllegalAccessException { _conn = conn; initialize(); editor = edi; } /** * Initialize the contents of the frame. * @throws IllegalAccessException * @throws InstantiationException */ private void initialize() throws InstantiationException, IllegalAccessException { //final conexion miconexion=new conexion(); //try { //} catch (InstantiationException | IllegalAccessException e) { // TODO Auto-generated catch block //e.printStackTrace(); // } //miconexion.iniciarBBDD(); frmConsulta = new JFrame(); frmConsulta.setTitle("Consulta"); frmConsulta.setBounds(100, 100, 583, 396); frmConsulta.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); final JComboBox comboCats = new JComboBox(); comboCats.setBounds(350, 55, 94, 22); frmConsulta.getContentPane().setLayout(null); final JComboBox comboAreas = new JComboBox(); comboAreas.setBounds(85, 55, 94, 22); frmConsulta.getContentPane().add(comboAreas); final String[] prueba = {""}; final JList list = new JList(prueba); list.setBounds(1, 1, 244, 73); list.setEnabled(false); frmConsulta.getContentPane().add(list); area a = new area(); ArrayList<idPalabra> areas = area.devolverAreas(_conn); comboAreas.addItem(" "); for(int i=0; i<areas.size(); i++){ comboAreas.addItem(areas.get(i).getPalabra()); } ItemListener itemListener = new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { if (comboAreas.getSelectedIndex() > 0){ comboCats.setEnabled(true); categoria c = new categoria(); ArrayList<idPalabra> cats = new ArrayList<idPalabra>(); cats = c.consultarCategoriasConArea(comboAreas.getSelectedItem().toString(), _conn); comboCats.removeAllItems(); comboCats.addItem(" "); comboCats.setEnabled(true); for(int i=0; i<cats.size(); i++){ comboCats.addItem(cats.get(i).getPalabra()); } }else{comboCats.setEnabled(false);} } }; comboAreas.addItemListener(itemListener); comboCats.setEnabled(false); frmConsulta.getContentPane().add(comboCats); JScrollPane scrollPane = new JScrollPane(list); scrollPane.setBounds(85, 156, 246, 75); frmConsulta.getContentPane().add(scrollPane); JScrollPane scrollPane2 = new JScrollPane(); scrollPane2.setBounds(85, 263, 246, 75); frmConsulta.getContentPane().add(scrollPane2); final JList listResul = new JList(); scrollPane2.setViewportView(listResul); listResul.setEnabled(false); listResul.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { JList listResul = (JList)evt.getSource(); if (evt.getClickCount() > 1) { // Double-click int index = listResul.locationToIndex(evt.getPoint()); Object selec = listResul.getSelectedValue(); editor.appendString(selec.toString()); frmConsulta.dispose(); } } }); ItemListener itemListener2 = new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { if ((comboCats.getSelectedIndex() > 0) && (comboCats.isEnabled()) && (comboAreas.isEnabled())){ ArrayList<String> misRasgos = new ArrayList<String>(); list.setEnabled(true); rasgocontenido r = new rasgocontenido(); categoria c = new categoria(); int indCat; try { indCat = c.consultarUnaCategoriaArea(_conn, comboAreas.getSelectedItem().toString(), comboCats.getSelectedItem().toString()); misRasgos = r.consultaRasgosCat(_conn, indCat); } catch (SQLException e) { e.printStackTrace(); } list.removeAll(); list.setListData(misRasgos.toArray()); }else{comboCats.setEnabled(false);} } }; comboCats.addItemListener(itemListener2); final JButton btnConsultar = new JButton("Consultar"); btnConsultar.setBounds(380, 153, 97, 49); btnConsultar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { List listRasgos = list.getSelectedValuesList(); ArrayList<String> rsgs = new ArrayList<String>(); ArrayList<String> resul = new ArrayList<String>(); for (int i=0; i<listRasgos.size(); i++){ rsgs.add((String) listRasgos.get(i)); } consulta c = new consulta(rsgs,comboAreas.getSelectedItem().toString(), comboCats.getSelectedItem().toString() ); c.rasgosAIndices(_conn); resul = c.consultar(_conn); //textArea.setEnabled(true); //textArea.setText(""); listResul.setEnabled(true); listResul.removeAll(); listResul.setListData(resul.toArray()); /*for (int i=0; i<resul.size(); i++){ textArea.append(resul.get(i)); textArea.append("\n"); }*/ } }); btnConsultar.setEnabled(false); frmConsulta.getContentPane().add(btnConsultar); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent evt) { /*if (evt.getValueIsAdjusting()) return; System.out.println("Selected from " + evt.getFirstIndex() + " to " + evt.getLastIndex());*/ int[] indices = list.getSelectedIndices(); if ((indices.length >0) && (comboCats.isEnabled()) && (comboAreas.isEnabled())){ btnConsultar.setEnabled(true); }else{btnConsultar.setEnabled(false);} } }); JLabel lblSeleccioneUnrea = new JLabel("Seleccione un \u00E1rea"); lblSeleccioneUnrea.setFont(new Font("Tahoma", Font.BOLD, 15)); lblSeleccioneUnrea.setBounds(60, 30, 151, 16); frmConsulta.getContentPane().add(lblSeleccioneUnrea); JLabel lblNewLabel = new JLabel("Seleccione una categor\u00EDa"); lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15)); lblNewLabel.setBounds(327, 26, 199, 20); frmConsulta.getContentPane().add(lblNewLabel); JLabel lblRasgos = new JLabel("Seleccione al menos un rasgo"); lblRasgos.setFont(new Font("Tahoma", Font.BOLD, 15)); lblRasgos.setBounds(59, 108, 296, 22); frmConsulta.getContentPane().add(lblRasgos); JLabel lblMantengaPulsadoCtrl = new JLabel("Mantenga pulsado CTRL para selecci\u00F3n m\u00FAltiple"); lblMantengaPulsadoCtrl.setFont(new Font("Tahoma", Font.PLAIN, 15)); lblMantengaPulsadoCtrl.setBounds(60, 127, 370, 22); frmConsulta.getContentPane().add(lblMantengaPulsadoCtrl); JLabel labelResul = new JLabel("Resultado(s) de la consulta:"); labelResul.setFont(new Font("Tahoma", Font.PLAIN, 15)); labelResul.setBounds(60, 244, 222, 16); frmConsulta.getContentPane().add(labelResul); } }
true
e884b4fbb7a323b38912436024901d0932cdaa40
Java
taoboy/HZQ-Cloud
/hzq-system-service/system-api/src/main/java/com/hzqing/system/api/dto/serve/ServeDto.java
UTF-8
992
1.726563
2
[ "Apache-2.0" ]
permissive
package com.hzqing.system.api.dto.serve; import com.hzqing.common.core.service.dto.BaseDto; import lombok.Data; import lombok.experimental.Accessors; import java.time.LocalDateTime; /** * <p> * 服务管理表 * </p> * * @author hzqing * @since 2019-08-13 */ @Data @Accessors(chain = true) public class ServeDto extends BaseDto { private static final long serialVersionUID = 1L; /** * 主键 */ private String id; /** * 服务名称 */ private String name; /** * 服务状态 */ private String status; /** * 权限标示 */ private String permission; /** * 创建人id */ private String createBy; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新人id */ private String updateBy; /** * 更新时间 */ private LocalDateTime updateTime; }
true
e4ed95fabd2ab9f2b17f3b68efcb7ca3cd602278
Java
talspektor/DesignPatterns
/src/p02/abstractFactory/PrinterType.java
UTF-8
77
2.109375
2
[]
no_license
package p02.abstractFactory; public enum PrinterType { PLAIN_TEXT, HTML; }
true
db00887ab0145075ec7fdc9ee6d97030d25d365c
Java
letimome/CustomDiff
/src/main/java/customs/controllers/alluvial/Alluvial_Feature_Product_Packages.java
UTF-8
4,959
2.0625
2
[]
no_license
package customs.controllers.alluvial; import java.util.ArrayList; import java.util.Iterator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import customs.models.Churn_CoreAssetsAndFeaturesByPR; import customs.models.Churn_CoreAssetsAndFeaturesByPRDao; import customs.models.Churn_Features_ComponentPackages; import customs.models.Churn_Features_ComponentPackagesDao; import customs.models.ComponentPackage; import customs.models.ComponentPackageDao; import customs.models.CoreAsset; import customs.models.CoreAssetDao; import customs.models.CoreassetsAndFeatures; import customs.models.CoreassetsAndFeaturesDao; import customs.models.Feature; import customs.models.FeatureDao; import customs.models.ProductRelease; import customs.models.ProductReleaseDao; @Controller public class Alluvial_Feature_Product_Packages { @Autowired private Churn_Features_ComponentPackagesDao featuresPackagesDao; @Autowired private ProductReleaseDao prDao; @Autowired private CoreassetsAndFeaturesDao caFeaturesDao; @Autowired private FeatureDao fDao; @Autowired private CoreAssetDao caDao; @Autowired private ComponentPackageDao componentDao; @Autowired private Churn_CoreAssetsAndFeaturesByPRDao churnCAforPrDao; private String pathToResource = "./src/main/resources/static/"; @RequestMapping("diff_feature_and_product_packages") public String getTreeMapForProductRelease( @RequestParam(value="idproductrelease", required=true) int idproductrelease, @RequestParam(value="idfeature", required=true) String idfeature, Model model){ System.out.println("The productrelease: "+idproductrelease); ProductRelease pr = prDao.getProductReleaseByIdproductrelease(idproductrelease); Feature f = fDao.getFeatureByIdfeature(idfeature); String csvheader="source,target,value,idparentfeature,idpackage,idproductrelease,idfeature"; String csvContent = computeCustomizationsForPRFeaturePackages(pr,f); customs.utils.FileUtils.writeToFile(pathToResource+"alluvial.csv",csvheader+csvContent);//path and test// + csvInitialPaths model.addAttribute("pr",pr.getName()); model.addAttribute("idproductrelease", idproductrelease); model.addAttribute("idfeature", idfeature); model.addAttribute("idparentfeature", f.getIdparent()); model.addAttribute("maintitle", "Which packages is '"+pr.getName()+"' customizing?"); model.addAttribute("difftitle", "diff(Baseline-v1.0, "+pr.getName()+")"); customs.utils.NavigationMapGenerator.generateNavigationMapForProductSide("features","core-asset","Expression",pr.getName()); return "alluvials/diff_feature_and_product_packages"; } private String computeCustomizationsForPRFeaturePackages(ProductRelease pr, Feature f) { String csvContent=""; Iterator<Churn_Features_ComponentPackages> it = featuresPackagesDao.getCustomsByIdproductrelease(pr.getId_productrelease()).iterator(); Churn_Features_ComponentPackages custom; ArrayList<Integer> customizedPackages = new ArrayList<Integer>(); while(it.hasNext()) { custom = it.next();// String csvheader="source,target,value,idparentfeature,idpackage,idproductrelease"; if ( f.getIdfeature().equals(custom.getIdfeature())) { customizedPackages.add(custom.getIdpackage()); csvContent = csvContent.concat("\n"+custom.getPackage_name()+" ["+f.getIdfeature()+"]"+"," + custom.getPackage_name()+" ["+pr.getName()+"]," +custom.getChurn()+","+custom.getIdparentfeature()+","+custom.getIdpackage()+"," +custom.getIdproductrelease()+","+custom.getIdfeature()); } } csvContent = csvContent +computeCSVForNotCustomizedFeaturePackages(pr, f, customizedPackages); return csvContent; } private String computeCSVForNotCustomizedPRPackages(ProductRelease pr, Feature f, ArrayList<Integer> customizedPackages) { String csvContent=""; return csvContent; } private String computeCSVForNotCustomizedFeaturePackages(ProductRelease pr, Feature f, ArrayList<Integer> customizedPackages) { String csvContent=""; Iterator<CoreassetsAndFeatures> it = caFeaturesDao.getFeatureCoreAssetsByIdfeature(f.getIdfeature()).iterator(); CoreassetsAndFeatures caf; ArrayList<Integer> listpackages = new ArrayList<Integer>(); ComponentPackage pack; while(it.hasNext()) { caf = it.next(); if(!customizedPackages.contains(caf.getIdpackage()) && (!listpackages.contains(caf.getIdpackage()))) { listpackages.add(caf.getIdpackage()); pack=componentDao.getComponentPackageByIdpackage(caf.getIdpackage()); csvContent = csvContent.concat("\n"+pack.getName()+",NOT_CUSTOMIZED,0.2"); } } return csvContent; } }
true
79ad99f5fef8617825caa15ee8d2576dc9a76ae3
Java
kenne12/PDSD_PRCDS_MONITORING
/src/java/entities/ActiviteRegionElementCout.java
UTF-8
4,703
1.90625
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 entities; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlRootElement; /** * * @author USER */ @Entity @Table(name = "activite_region_element_cout") @XmlRootElement @NamedQueries({ @NamedQuery(name = "ActiviteRegionElementCout.findAll", query = "SELECT a FROM ActiviteRegionElementCout a"), @NamedQuery(name = "ActiviteRegionElementCout.findByIdactiviteRegionElementCout", query = "SELECT a FROM ActiviteRegionElementCout a WHERE a.idactiviteRegionElementCout = :idactiviteRegionElementCout"), @NamedQuery(name = "ActiviteRegionElementCout.findByCoutunitaire", query = "SELECT a FROM ActiviteRegionElementCout a WHERE a.coutunitaire = :coutunitaire"), @NamedQuery(name = "ActiviteRegionElementCout.findByQte", query = "SELECT a FROM ActiviteRegionElementCout a WHERE a.qte = :qte"), @NamedQuery(name = "ActiviteRegionElementCout.findByNbreJr", query = "SELECT a FROM ActiviteRegionElementCout a WHERE a.nbreJr = :nbreJr")}) public class ActiviteRegionElementCout implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "idactivite_region_element_cout") private Long idactiviteRegionElementCout; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation private Double coutunitaire; private Double qte; @Column(name = "nbre_jr") private Double nbreJr; @JoinColumn(name = "idactivite_region", referencedColumnName = "idactivite_region") @ManyToOne(fetch = FetchType.LAZY) private ActiviteRegion idactiviteRegion; @JoinColumn(name = "idelementcout", referencedColumnName = "idelement_cout") @ManyToOne(fetch = FetchType.LAZY) private ElementCout idelementcout; public ActiviteRegionElementCout() { } public ActiviteRegionElementCout(Long idactiviteRegionElementCout) { this.idactiviteRegionElementCout = idactiviteRegionElementCout; } public Long getIdactiviteRegionElementCout() { return idactiviteRegionElementCout; } public void setIdactiviteRegionElementCout(Long idactiviteRegionElementCout) { this.idactiviteRegionElementCout = idactiviteRegionElementCout; } public Double getCoutunitaire() { return coutunitaire; } public void setCoutunitaire(Double coutunitaire) { this.coutunitaire = coutunitaire; } public Double getQte() { return qte; } public void setQte(Double qte) { this.qte = qte; } public Double getNbreJr() { return nbreJr; } public void setNbreJr(Double nbreJr) { this.nbreJr = nbreJr; } public ActiviteRegion getIdactiviteRegion() { return idactiviteRegion; } public void setIdactiviteRegion(ActiviteRegion idactiviteRegion) { this.idactiviteRegion = idactiviteRegion; } public ElementCout getIdelementcout() { return idelementcout; } public void setIdelementcout(ElementCout idelementcout) { this.idelementcout = idelementcout; } @Override public int hashCode() { int hash = 0; hash += (idactiviteRegionElementCout != null ? idactiviteRegionElementCout.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ActiviteRegionElementCout)) { return false; } ActiviteRegionElementCout other = (ActiviteRegionElementCout) object; if ((this.idactiviteRegionElementCout == null && other.idactiviteRegionElementCout != null) || (this.idactiviteRegionElementCout != null && !this.idactiviteRegionElementCout.equals(other.idactiviteRegionElementCout))) { return false; } return true; } @Override public String toString() { return "entities.ActiviteRegionElementCout[ idactiviteRegionElementCout=" + idactiviteRegionElementCout + " ]"; } }
true
132c790da26e1e5c825b6a6e43a8bbeb24f9de1d
Java
aksasha13/Tetris-Java
/src/tetrisBlocks/TShape.java
UTF-8
196
1.773438
2
[]
no_license
package tetrisBlocks; import tetris.TetrisBlock; public class TShape extends TetrisBlock { public TShape() { super(new int [][]{{1,1,1}, {0,1,0}}); } }
true