hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
e43ef21296449dc5b8a14cfb2b330f3e990af088
875
/******************************************************************************* * Copyright (c) 2018 Politecnico di Torino and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 *******************************************************************************/ package it.polito.verigraph.tosca.converter.grpc; public class ToscaGrpcUtils { /** Default configuration for a Tosca NodeTemplate non compliant with Verigraph types*/ public static final String defaultConfID = new String(""); public static final String defaultDescr = new String("Default Configuration"); public static final String defaultConfig = new String("[]"); }
46.052632
92
0.601143
69b241a106a546f13a4829a91dbf3fe0df7c33e0
78
@tech.jhipster.lite.SharedKernel package tech.jhipster.lite.generator.readme;
26
44
0.846154
739f4ac5a4d24f8b956cfc2c987be5baf603cddc
1,238
/* * Owned by aizuddindeyn * Visit https://gitlab.com/group-bear/mouse-automation */ package com.aizuddindeyn.mouse; import java.util.Timer; /** * @author aizuddindeyn * @date 11/7/2020 */ class MouseInstance { private static final MouseInstance INSTANCE = new MouseInstance(); private Timer timer; private boolean started = false; private MouseInstance() { // Singleton } static MouseInstance getInstance() { return INSTANCE; } synchronized void start() { timer = new Timer(); MouseUtils.log("Timer started"); started = true; timer.schedule(new MouseTask(timer, INSTANCE), 1500L); } synchronized void stop() { timer.cancel(); started = false; MouseUtils.log("Timer stopped"); } void execute() { try { int index = MouseRandom.getSecureRandom().nextInt(MouseMoveEnum.getEnumMap().size()); MouseMoveEnum enums = MouseMoveEnum.values()[index]; MouseMoveEnum.getEnumMap().get(enums).move(); } catch (Exception ex) { MouseUtils.logErr(ex.getMessage()); } } synchronized boolean isStarted() { return started; } }
21.344828
97
0.606624
dda7438b222f1c69bcbaaf11cd9db1488df3a398
131
package examples.ontology.ontologyServer; import jade.content.AgentAction; public class GetTime implements AgentAction { }
18.714286
46
0.793893
205800734cecdea2b57044dbdb2beb3570975fae
486
package com.autohome.frostmourne.monitor.model.message.ding; import java.util.List; public class DingAt { private Boolean isAtAll; private List<String> atMobiles; public Boolean getAtAll() { return isAtAll; } public void setAtAll(Boolean atAll) { isAtAll = atAll; } public List<String> getAtMobiles() { return atMobiles; } public void setAtMobiles(List<String> atMobiles) { this.atMobiles = atMobiles; } }
18
60
0.650206
98dd5c9fa48207a373fd28691d928252a8d8e577
967
package com.micro.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import lombok.Data; /** * 分享-接收人 * @author Administrator * */ @Table(name="disk_share_friends", indexes = { @Index(columnList = "shareid"), @Index(columnList = "userid"), } ) @Entity @Data public class DiskShareFriends { @Id @GenericGenerator(name = "uuid",strategy = "uuid") @GeneratedValue(generator = "uuid") @Column(name="id",columnDefinition="VARCHAR(50)") private String id; @Column(name="shareid",columnDefinition="VARCHAR(50)") private String shareid; @Column(name="userid",columnDefinition="VARCHAR(50)") private String userid; @Column(name="username",columnDefinition="VARCHAR(50)") private String username; }
22.488372
57
0.715615
afea47e00ca1417e885f3de96e575f3920e287b4
10,365
package br.com.chatredes.controller; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Observable; import br.com.chatredes.app.AppCliente; import br.com.chatredes.model.MensagemGlobal; import br.com.chatredes.model.UsuarioPublico; import br.com.chatredes.view.DialogoDtlMsgPublica; import br.com.chatredes.view.DialogoPrivado; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.layout.Pane; import jdk.nashorn.internal.runtime.ListAdapter; /** * @author Mael Santos * */ public class ControleCliente extends Controle{ @FXML private Button btnSair; @FXML private Label lblNome; @FXML private Label lblStatus; @FXML private Label lblDigitando; @FXML private TextField tfdMensagem; @FXML private Button btnEnviar; @FXML private ListView<MensagemGlobal> msgList; @FXML private ListView<UsuarioPublico> userList; private Pane loginCliente; private DialogoPrivado dialogo; private UsuarioPublico usuarioLogado; private MensagemGlobal mensagemSelecionada; private boolean scrollUser = true, scrollMsg = true; @Override public void init() { msgList.addEventFilter(ScrollEvent.ANY, (e) ->{ //get every scroll event if(e.getTextDeltaY() > 0){ //set Scroll event to false when the user scrolls up scrollMsg = false; } }); userList.addEventFilter(ScrollEvent.ANY, (e) ->{ //get every scroll event if(e.getTextDeltaY() > 0){ //set Scroll event to false when the user scrolls up scrollUser = false; } }); dialogo = DialogoPrivado.getInstance(); userList.getItems().clear(); msgList.getItems().clear(); Cliente.getInstance().protocoloGetUSERS(); Cliente.getInstance().protocoloGetMSG(); lblStatus.setText("Online"); userList.setOnMouseClicked(e -> { if (e.getClickCount() > 1) if (userList.getSelectionModel().getSelectedItem() != null) { dialogo.show(usuarioLogado, userList.getSelectionModel().getSelectedItem()); } }); msgList.setOnMouseClicked(e -> { if (e.getClickCount() > 1) if (msgList.getSelectionModel().getSelectedItem() != null) { cliente.protocoloGetVISU(msgList.getSelectionModel().getSelectedItem().getId()); mensagemSelecionada = msgList.getSelectionModel().getSelectedItem(); } }); } @FXML void clickAction(ActionEvent event) { Object obj = event.getSource();//componente que disparou a ação if(obj == btnEnviar) { enviarMensagem(); } else if(obj == btnSair) { cliente.protocoloLOGOUT(LocalDateTime.now()); notificacao.mensagemAguarde(); userList.getItems().clear(); msgList.getItems().clear(); try { if(loginCliente == null) loginCliente = FXMLLoader.load(getClass().getClassLoader().getResource("br/com/chatredes/view/LoginCliente.fxml")); AppCliente.changeStage(loginCliente); notificacao.mensagemSucesso(); usuarioLogado = null; } catch (IOException e) { e.printStackTrace(); } } } @FXML void inputAction(KeyEvent event) { if (event.getCode() == KeyCode.ENTER) { if(!tfdMensagem.getText().trim().equals("")) enviarMensagem(); } else { cliente.protocoloDIGIT(); } } @FXML void outputAction(KeyEvent event) { cliente.protocoloNDIGIT(); } private void enviarMensagem() { String msg = tfdMensagem.getText().trim(); if(msg.length() > 0) { cliente.protocoloMSG(LocalDateTime.now(),tfdMensagem.getText()); tfdMensagem.setText(""); } } /** * M�todo respons�vel por tratar a valida��o de visualiza��o de mensagens, * atrav�s da entrada de mouse em um dos campos de IO de texto(Tela de visualiza��o de * mensagens e entrada para envio). Assim, quando um dos respectivos campos * entra em foco, � sub-entendido que as mensagens foram visualizadas. * @param event evento de entrada de mouse em componente. */ @FXML void focoEmCampoTexto(MouseEvent event) { for(MensagemGlobal msgg : msgList.getItems()) { // a mensagem n�o foi enviada pelo cliente logado e ainda n�o foi visualizada if(!msgg.getLoginRemetente().equals(usuarioLogado.getLogin()) && msgg.getHoraVizualizado() == null) { cliente.protocoloVISU(msgg.getId()); } } } @Override public void update(Observable o, Object arg) { String[] respostaServidor = (String[]) arg; System.out.println(respostaServidor[0]); if(respostaServidor[0].equals("LOGIN")){ if(respostaServidor[1].equals("02 SUC")) { try { for(UsuarioPublico p : userList.getItems()) { System.out.println(p.getLogin()); if(p.getLogin().equals(respostaServidor[2])) { userList.getItems().remove(p); p.setEstado("online"); p.setUltimoLogin(LocalDateTime.now()); userList.getItems().add(p); System.out.println("Estado do Usuario Atualizado: "+p.getNome()); } } } catch (Exception e) { } } } if(respostaServidor[0].equals("LOGOUT")){ if(respostaServidor[1].equals("04 EFE")) { try { for(UsuarioPublico p : userList.getItems()) { System.out.println(p.getLogin()); if(p.getLogin().equals(respostaServidor[2])) { userList.getItems().remove(p); p.setEstado("offline"); p.setUltimoLogin(LocalDateTime.now()); userList.getItems().add(p); System.out.println("Estado do Usuario Atualizado: "+p.getNome()); } } } catch (Exception e) { } } else notificacao.mensagemErro(); } else if(respostaServidor[0].equals("USERS")) { if(respostaServidor[1].equals("02 SUC")) { for(int i = 2; i<respostaServidor.length ; i++) { userList.getItems().add(converterStringEmUsuarioPublico(respostaServidor[i])); } if(scrollUser) userList.scrollTo(userList.getItems().size() -1 ); } else notificacao.mensagemErro(); }else if(respostaServidor[0].equals("MSG")) { if(respostaServidor[1].equals("02 SUC")) { for(int i = 2; i<respostaServidor.length ; i++) { msgList.getItems().add(converterStringEmMensagemGlobal(respostaServidor[i])); } }else if(respostaServidor[1].equals("04 EFE") && respostaServidor[2].equals("GLOBAL")) { System.out.println("recebi mensagem"); msgList.getItems().add(converterStringEmMensagemGlobal(respostaServidor[3])); } if(scrollMsg) msgList.scrollTo(msgList.getItems().size() -1 ); else notificacao.mensagemErro(); }else if(respostaServidor[0].equals("VISU")) { try{ Long mensagemId = Long.parseLong(respostaServidor[2]); LocalDateTime horarioVisualizado = LocalDateTime.parse(respostaServidor[3], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); if(respostaServidor[1].equals("02 SUC")) { for(MensagemGlobal msgg : msgList.getItems()) { if(msgg.getId() == mensagemId) { msgList.getItems().remove(msgg); msgg.setHoraVizualizado(horarioVisualizado); msgList.getItems().add(msgg); } } }else if(respostaServidor[1].equals("03 EXE")){ // caso ocorreu erro deve-se tentar novamente atualizar o estado da mensagem para visualizado. cliente.protocoloVISU(mensagemId, horarioVisualizado); } else notificacao.mensagemErro(); }catch(Exception e){ // se der exe��o significa que o retorno n tem hora ou id de mensagem, ou seja � uma resposta para detelhes de visualiaz��o e n�o edi��o de estado de mensagem if(respostaServidor[1].equals("02 SUC")) { System.err.println("confirmando que mensagem visualizada"); List<String> detalhes = new ArrayList<>(); for(int i = 2 ; i < respostaServidor.length; i ++) detalhes.add(respostaServidor[i]); System.err.println("detalhes retornado "+ detalhes); if(mensagemSelecionada!= null) DialogoDtlMsgPublica.getInstance().show(mensagemSelecionada.getNomeRemetente()+" / "+mensagemSelecionada.getLoginRemetente() , mensagemSelecionada.getMensagem(), mensagemSelecionada.getHorarioEnvio(),detalhes); mensagemSelecionada = null; } else notificacao.mensagemErro(); } } else if(respostaServidor[0].equals("DIGIT/ 02 SUC")) { if(respostaServidor.length < 3) lblDigitando.setText(respostaServidor[1]+" está digitando"); } else if(respostaServidor[0].equals("NDIGIT/ 02 SUC")) { if(respostaServidor.length < 3) lblDigitando.setText(""); } } private MensagemGlobal converterStringEmMensagemGlobal(String linha) { String[] atributosMsg = linha.split(";"); return new MensagemGlobal( Long.parseLong(atributosMsg[0])/*id*/, atributosMsg[1]/*nomeRemetente*/, atributosMsg[2]/*loginRemetente*/, ((!atributosMsg[3].equals("null"))?LocalDateTime.parse(atributosMsg[3],DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")): null)/*horarioEnvio*/, atributosMsg[4]/*mensagem*/, ((!atributosMsg[5].equals("null"))?LocalDateTime.parse(atributosMsg[5],DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")): null)/*horaVizualizado*/, atributosMsg[6]/*loginDestinatario*/); } private UsuarioPublico converterStringEmUsuarioPublico(String linha) { String[] atributosUser = linha.split(";"); return new UsuarioPublico(atributosUser[0], atributosUser[1],((!atributosUser[2].equals("null"))?LocalDateTime.parse(atributosUser[2], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")): null), atributosUser[3]); } public void setUsuarioLogado(UsuarioPublico usuarioLogado) { this.usuarioLogado = usuarioLogado; lblNome.setText(usuarioLogado.getNome()); } }
31.314199
182
0.664544
e8623139e1fe1c3cb602cffb838a7ffdfa389d16
4,947
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-257 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.04.07 at 07:27:56 AM EDT // package com.cisco.dvbu.ps.deploytool.modules; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Attribute Definition Entry Data Source Type: Display of attributes from getDataSourceAttributeDefs. * * * <p>Java class for AttributeDefEntryDataSourceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AttributeDefEntryDataSourceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="updateRule" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="required" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="displayName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="visible" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AttributeDefEntryDataSourceType", propOrder = { "name", "type", "updateRule", "required", "displayName", "visible" }) public class AttributeDefEntryDataSourceType { protected String name; protected String type; protected String updateRule; protected String required; protected String displayName; protected String visible; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the updateRule property. * * @return * possible object is * {@link String } * */ public String getUpdateRule() { return updateRule; } /** * Sets the value of the updateRule property. * * @param value * allowed object is * {@link String } * */ public void setUpdateRule(String value) { this.updateRule = value; } /** * Gets the value of the required property. * * @return * possible object is * {@link String } * */ public String getRequired() { return required; } /** * Sets the value of the required property. * * @param value * allowed object is * {@link String } * */ public void setRequired(String value) { this.required = value; } /** * Gets the value of the displayName property. * * @return * possible object is * {@link String } * */ public String getDisplayName() { return displayName; } /** * Sets the value of the displayName property. * * @param value * allowed object is * {@link String } * */ public void setDisplayName(String value) { this.displayName = value; } /** * Gets the value of the visible property. * * @return * possible object is * {@link String } * */ public String getVisible() { return visible; } /** * Sets the value of the visible property. * * @param value * allowed object is * {@link String } * */ public void setVisible(String value) { this.visible = value; } }
23.898551
126
0.565595
b3dc0f38e162c003c4fd9effd47758fb3f7fcd4c
5,677
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v7.widget; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; public class LinearLayoutCompat$LayoutParams extends android.view.ViewGroup.MarginLayoutParams { public int gravity; public float weight; public LinearLayoutCompat$LayoutParams(int i, int j) { super(i, j); // 0 0:aload_0 // 1 1:iload_1 // 2 2:iload_2 // 3 3:invokespecial #12 <Method void android.view.ViewGroup$MarginLayoutParams(int, int)> gravity = -1; // 4 6:aload_0 // 5 7:iconst_m1 // 6 8:putfield #14 <Field int gravity> weight = 0.0F; // 7 11:aload_0 // 8 12:fconst_0 // 9 13:putfield #16 <Field float weight> // 10 16:return } public LinearLayoutCompat$LayoutParams(int i, int j, float f) { super(i, j); // 0 0:aload_0 // 1 1:iload_1 // 2 2:iload_2 // 3 3:invokespecial #12 <Method void android.view.ViewGroup$MarginLayoutParams(int, int)> gravity = -1; // 4 6:aload_0 // 5 7:iconst_m1 // 6 8:putfield #14 <Field int gravity> weight = f; // 7 11:aload_0 // 8 12:fload_3 // 9 13:putfield #16 <Field float weight> // 10 16:return } public LinearLayoutCompat$LayoutParams(Context context, AttributeSet attributeset) { super(context, attributeset); // 0 0:aload_0 // 1 1:aload_1 // 2 2:aload_2 // 3 3:invokespecial #21 <Method void android.view.ViewGroup$MarginLayoutParams(Context, AttributeSet)> gravity = -1; // 4 6:aload_0 // 5 7:iconst_m1 // 6 8:putfield #14 <Field int gravity> context = ((Context) (context.obtainStyledAttributes(attributeset, android.support.v7.appcompat.R.styleable.LinearLayoutCompat_Layout))); // 7 11:aload_1 // 8 12:aload_2 // 9 13:getstatic #27 <Field int[] android.support.v7.appcompat.R$styleable.LinearLayoutCompat_Layout> // 10 16:invokevirtual #33 <Method TypedArray Context.obtainStyledAttributes(AttributeSet, int[])> // 11 19:astore_1 weight = ((TypedArray) (context)).getFloat(android.support.v7.appcompat.R.styleable.LinearLayoutCompat_Layout_android_layout_weight, 0.0F); // 12 20:aload_0 // 13 21:aload_1 // 14 22:getstatic #36 <Field int android.support.v7.appcompat.R$styleable.LinearLayoutCompat_Layout_android_layout_weight> // 15 25:fconst_0 // 16 26:invokevirtual #42 <Method float TypedArray.getFloat(int, float)> // 17 29:putfield #16 <Field float weight> gravity = ((TypedArray) (context)).getInt(android.support.v7.appcompat.R.styleable.LinearLayoutCompat_Layout_android_layout_gravity, -1); // 18 32:aload_0 // 19 33:aload_1 // 20 34:getstatic #45 <Field int android.support.v7.appcompat.R$styleable.LinearLayoutCompat_Layout_android_layout_gravity> // 21 37:iconst_m1 // 22 38:invokevirtual #49 <Method int TypedArray.getInt(int, int)> // 23 41:putfield #14 <Field int gravity> ((TypedArray) (context)).recycle(); // 24 44:aload_1 // 25 45:invokevirtual #53 <Method void TypedArray.recycle()> // 26 48:return } public LinearLayoutCompat$LayoutParams(LinearLayoutCompat$LayoutParams linearlayoutcompat$layoutparams) { super(((android.view.ViewGroup.MarginLayoutParams) (linearlayoutcompat$layoutparams))); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #57 <Method void android.view.ViewGroup$MarginLayoutParams(android.view.ViewGroup$MarginLayoutParams)> gravity = -1; // 3 5:aload_0 // 4 6:iconst_m1 // 5 7:putfield #14 <Field int gravity> weight = linearlayoutcompat$layoutparams.weight; // 6 10:aload_0 // 7 11:aload_1 // 8 12:getfield #16 <Field float weight> // 9 15:putfield #16 <Field float weight> gravity = linearlayoutcompat$layoutparams.gravity; // 10 18:aload_0 // 11 19:aload_1 // 12 20:getfield #14 <Field int gravity> // 13 23:putfield #14 <Field int gravity> // 14 26:return } public LinearLayoutCompat$LayoutParams(android.view.ViewGroup.LayoutParams layoutparams) { super(layoutparams); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #60 <Method void android.view.ViewGroup$MarginLayoutParams(android.view.ViewGroup$LayoutParams)> gravity = -1; // 3 5:aload_0 // 4 6:iconst_m1 // 5 7:putfield #14 <Field int gravity> // 6 10:return } public LinearLayoutCompat$LayoutParams(android.view.ViewGroup.MarginLayoutParams marginlayoutparams) { super(marginlayoutparams); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #57 <Method void android.view.ViewGroup$MarginLayoutParams(android.view.ViewGroup$MarginLayoutParams)> gravity = -1; // 3 5:aload_0 // 4 6:iconst_m1 // 5 7:putfield #14 <Field int gravity> // 6 10:return } }
40.841727
141
0.602607
4eab002cf8f281f37ac47d424951f219ceaa3b95
1,542
package org.intermine.web.uri; /* * Copyright (C) 2002-2018 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import org.intermine.api.InterMineAPI; import org.intermine.api.bag.BagManager; import org.intermine.api.profile.Profile; import org.intermine.api.query.PathQueryExecutor; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStore; public class MockInterMineLUIConverter extends InterMineLUIConverter { private ObjectStore os = null; private InterMineAPI im = null; public MockInterMineLUIConverter(Profile profile) { super(profile); } @Override public Model getModel() { return Model.getInstanceByName("testmodel"); } @Override public InterMineAPI getInterMineAPI() { return im; } @Override public PathQueryExecutor getPathQueryExecutor() { return new PathQueryExecutor(os, profile,null, new BagManager(profile, Model.getInstanceByName("testmodel"))); } /** * Set the os for testing * @param os the objectstore */ public void setObjectStore(ObjectStore os) { this.os = os; } /** * Set the InterMineAPI for testing * @param im the interMineAPI */ public void setInterMineAPI(InterMineAPI im) { this.im = im; } }
25.7
79
0.688067
a2bab93de125ac7c26b8321fede8a2f506032d0a
25,031
package vproxyx.websocks; import vfd.IP; import vfd.IPPort; import vjson.JSON; import vjson.util.ObjectBuilder; import vproxy.socks.Socks5ProxyProtocolHandler; import vproxy.util.CoreUtils; import vproxybase.connection.ConnectableConnection; import vproxybase.connection.ConnectionOpts; import vproxybase.connection.Connector; import vproxybase.dns.Resolver; import vproxybase.http.HttpContext; import vproxybase.http.HttpProtocolHandler; import vproxybase.processor.http1.entity.Header; import vproxybase.processor.http1.entity.Request; import vproxybase.processor.http1.entity.Response; import vproxybase.protocol.ProtocolHandler; import vproxybase.protocol.ProtocolHandlerContext; import vproxybase.protocol.SubProtocolHandlerContext; import vproxybase.selector.wrap.file.FileFD; import vproxybase.util.*; import vproxybase.util.nio.ByteArrayChannel; import vproxybase.util.ringbuffer.ByteBufferRingBuffer; import vproxybase.util.ringbuffer.SSLUtils; import javax.net.ssl.SSLEngine; import java.io.IOException; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.function.Supplier; public class WebSocksProtocolHandler implements ProtocolHandler<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>> { private interface Tool { String prefix(); void handle(WebSocksHttpProtocolHandler handler, ProtocolHandlerContext<HttpContext> ctx, String argument); } // some utils tools provided by the websocks-proxy-server through http private static final String TOOLS_PREFIX = "/tools"; private static final Tool[] tools = new Tool[]{ new ResolveTool(), }; static class ResolveTool implements Tool { @Override public String prefix() { return "/resolve?domain="; } @Override public void handle(WebSocksHttpProtocolHandler handler, ProtocolHandlerContext<HttpContext> ctx, String argument) { Resolver.getDefault().resolve(argument, new Callback<>() { @Override protected void onSucceeded(IP value) { JSON.Object object = new ObjectBuilder() .put("domain", argument) .putArray("addresses", arr -> arr.add(value.formatToIPString())).build(); ctx.write(handler.response(object)); } @Override protected void onFailed(UnknownHostException err) { handler.fail(ctx, 400, "Cannot resolve host: " + Utils.formatErr(err)); } }); } } class WebSocksHttpProtocolHandler extends HttpProtocolHandler { private final Supplier<ProtocolHandlerContext<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>>> rootCtxGetter; protected WebSocksHttpProtocolHandler(Supplier<ProtocolHandlerContext<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>>> rootCtxGetter) { super(false); this.rootCtxGetter = rootCtxGetter; } @Override protected void request(ProtocolHandlerContext<HttpContext> ctx) { Request req = ctx.data.result; assert Logger.lowLevelDebug("receive new request " + req); if (!req.method.equals("GET")) { fail(ctx, 400, "unsupported http method " + req.method); return; } if (req.headers.stream().map(h -> h.key).noneMatch(key -> key.equalsIgnoreCase("upgrade"))) { assert Logger.lowLevelDebug("not upgrade request, try to respond with a registered page"); if (pageProvider == null) { assert Logger.lowLevelDebug("pageProvider is not set, cannot respond a page"); // fall through } else { if (req.uri.contains("..")) { Logger.warn(LogType.INVALID_EXTERNAL_DATA, "the request " + req.uri + " wants to get upper level resources, which might be an attack"); // fall through } else { String uri = req.uri; // check for tools for (Tool tool : tools) { String prefix = TOOLS_PREFIX + tool.prefix(); if (!uri.startsWith(prefix)) { continue; } String arg = uri.substring(prefix.length()).trim(); if (arg.isEmpty()) { fail(ctx, 400, "Invalid argument"); return; } tool.handle(this, ctx, arg); return; } if (uri.contains("?")) { uri = uri.substring(0, uri.indexOf("?")); } Logger.alert("incoming request " + ctx.connection.remote + "->" + uri); fail(ctx, 200, uri); return; } } } if (!WebSocksUtils.checkUpgradeToWebSocketHeaders(req.headers, false)) { fail(ctx, 400, "upgrading related headers are invalid"); return; } if (ctx.inBuffer.used() != 0) { fail(ctx, 400, "upgrading request should not contain a body"); return; } if (!checkAuth(req.headers)) { fail(ctx, 401, "auth failed"); return; } { String useProtocol = selectProtocol(req.headers); if (useProtocol == null) { fail(ctx, 400, "no supported protocol"); return; } // we only support socks5 for now, so no need to save this protocol string } String key = null; for (Header header : req.headers) { if (header.key.trim().equalsIgnoreCase("sec-websocket-key")) { key = header.value.trim(); } } assert key != null; String accept = getWebSocketAccept(key); if (accept == null) { fail(ctx, 500, "generating sec-websocket-accept failed"); return; } // everything is fine, make an upgrade { // handling on the server side WebSocksHttpContext wrapCtx = (WebSocksHttpContext) ctx.data; wrapCtx.webSocksProxyContext.step = 2; // next step is WebSocket int expectingLen = WebSocksUtils.bytesToSendForWebSocketFrame.length; byte[] foo = Utils.allocateByteArray(expectingLen); wrapCtx.webSocksProxyContext.webSocketBytes = ByteArrayChannel.fromEmpty(foo); } response(101, accept, ctx); // respond to the client about the upgrading } // it's ordered with `-priority`, smaller the index is, higher priority it has private final List<String> supportedProtocols = Collections.singletonList("socks5"); private String selectProtocol(List<Header> headers) { List<String> protocols = new ArrayList<>(); for (Header h : headers) { if (h.key.trim().equalsIgnoreCase("sec-websocket-protocol")) { protocols.add(h.value.trim()); } } if (protocols.isEmpty()) return null; for (String p : supportedProtocols) { if (protocols.contains(p)) return p; } return null; } private void fail(ProtocolHandlerContext<HttpContext> ctx, int code, String msg) { assert Logger.lowLevelDebug("WebSocket handshake failed: " + msg); ctx.inBuffer.clear(); response(code, msg, ctx); // no need to tell the Proxy it fails // the client may make another http request } private boolean checkAuth(List<Header> headers) { for (Header h : headers) { if (h.key.trim().equalsIgnoreCase("authorization")) { String v = h.value.trim(); if (!v.startsWith("Basic ")) { assert Logger.lowLevelDebug("Authorization header not Basic: " + v); return false; } v = v.substring("Basic ".length()).trim(); try { v = new String(Base64.getDecoder().decode(v.getBytes())); } catch (IllegalArgumentException e) { assert Logger.lowLevelDebug("Authorization Basic not base64: " + v); return false; } String[] userpass = v.split(":"); if (userpass.length != 2) { assert Logger.lowLevelDebug("not user:pass, " + v); return false; } String user = userpass[0].trim(); String pass = userpass[1].trim(); String expectedPass = auth.get(user); if (expectedPass == null) { assert Logger.lowLevelDebug("user " + user + " not in registry"); return false; } assert Logger.lowLevelDebug("do check for " + user + ":" + pass); return checkPass(pass, expectedPass); } } assert Logger.lowLevelDebug("no Authorization header"); return false; } // we calculate the user's password with current minute number and sha256 // the input should match any of the following: // 1. base64str(base64str(sha256(password)) + str(current_minute_dec_digital))) // 2. base64str(base64str(sha256(password)) + str(current_minute_dec_digital - 1))) // 3. base64str(base64str(sha256(password)) + str(current_minute_dec_digital + 1))) private boolean checkPass(String pass, String expected) { long m = Utils.currentMinute(); long mInc = m + 60_000; long mDec = m - 60_000; return pass.equals(WebSocksUtils.calcPass(expected, m)) || pass.equals(WebSocksUtils.calcPass(expected, mInc)) || pass.equals(WebSocksUtils.calcPass(expected, mDec)); } private static final String rfc6455UUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private String getWebSocketAccept(String key) { String foo = key + rfc6455UUID; MessageDigest sha1; try { sha1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { Logger.shouldNotHappen("no SHA-1 alg", e); return null; } sha1.update(foo.getBytes()); return Base64.getEncoder().encodeToString(sha1.digest()); } private byte[] response(JSON.Instance body) { String statusMsg = HttpStatusCodeReasonMap.get(200); Response resp = new Response(); resp.version = "HTTP/1.1"; resp.statusCode = 200; resp.reason = statusMsg; resp.headers = new LinkedList<>(); resp.headers.add(new Header("Server", "vproxy/" + Version.VERSION)); resp.headers.add(new Header("Date", new Date().toString())); resp.headers.add(new Header("Content-Type", "application/json")); if (body != null) { ByteArray foo = ByteArray.from(body.pretty().getBytes()); resp.headers.add(new Header("Content-Length", "" + foo.length())); resp.body = foo; } return resp.toByteArray().toJavaArray(); } private final Set<String> ENCODED_MIMES = Set.of("text/html", "text/css", "text/javascript"); private void response(int statusCode, String msg, ProtocolHandlerContext<HttpContext> ctx) { // check whether the page exists when statusCode is 200 PageProvider.PageResult page = null; if (statusCode == 200) { page = pageProvider.getPage(msg); if (page == null) { statusCode = 404; msg = msg + " not found"; } else if (page.redirect != null) { statusCode = 302; msg = page.redirect; } } String statusMsg = HttpStatusCodeReasonMap.get(statusCode); Response resp = new Response(); resp.version = "HTTP/1.1"; resp.statusCode = statusCode; resp.reason = statusMsg; resp.headers = new LinkedList<>(); resp.headers.add(new Header("Server", "vproxy/" + Version.VERSION)); resp.headers.add(new Header("Date", new Date().toString())); FileFD fileToSend = null; if (statusCode == 101) { resp.headers.add(new Header("Upgrade", "websocket")); resp.headers.add(new Header("Connection", "Upgrade")); resp.headers.add(new Header("Sec-Websocket-Accept", msg)); resp.headers.add(new Header("Sec-WebSocket-Protocol", "socks5")); } else if (statusCode == 200) { resp.headers.add(new Header("Content-Type", page.mime)); assert page.content != null || page.file != null; assert page.content == null || page.file == null; if (page.file == null) { resp.headers.add(new Header("Content-Length", "" + page.content.length())); resp.body = page.content; } else { resp.headers.add(new Header("Content-Length", "" + page.file.length())); resp.headers.add(new Header("Connection", "Close")); fileToSend = page.file; } if (page.cacheAge != 0L) { resp.headers.add(new Header("Cache-Control", "max-age=" + page.cacheAge)); } boolean acceptGZip = false; if (fileToSend == null && ENCODED_MIMES.contains(page.mime)) { for (Header header : ctx.data.result.headers) { if (header.key.trim().equalsIgnoreCase("accept-encoding") && header.value.trim().toLowerCase().contains("gzip")) { acceptGZip = true; break; } } } if (acceptGZip) { resp.headers.add(new Header("Content-Encoding", "gzip")); resp.isPlain = true; } } else if (statusCode == 302) { ByteArray body = ByteArray.from(("" + "<html>\r\n" + "<head><title>302 Found</title></head>\r\n" + "<body bgcolor=\"white\">\r\n" + "<center><h1>302 Found</h1></center>\r\n" + "<hr><center>vproxy/" + Version.VERSION + "</center>\r\n" + "</body>\r\n" + "</html>\r\n").getBytes()); resp.headers.add(new Header("Location", msg)); resp.headers.add(new Header("Content-Length", "" + body.length())); resp.body = body; } else { if (statusCode == 401) { resp.headers.add(new Header("WWW-Authenticate", "Basic")); } resp.headers.add(new Header("Content-Type", "text/html")); { String rawIp = ctx.connection.remote.getAddress().formatToIPString(); String xff = null; if (ctx.data != null && ctx.data.result != null && ctx.data.result.headers != null) { var headers = ctx.data.result.headers; for (var header : headers) { if (header.key.trim().toLowerCase().equals("x-forwarded-for")) { xff = header.value.trim(); break; } } } if (xff == null) { xff = "(none)"; } msg = ErrorPages.build(statusCode, statusMsg, msg, rawIp, xff); } ByteArray body = ByteArray.from(msg.getBytes()); resp.headers.add(new Header("Content-Length", "" + body.length())); resp.body = body; } ctx.write(resp.toByteArray().toJavaArray()); if (fileToSend != null) { var rootCtx = rootCtxGetter.get(); var cb = rootCtx.data.right; if (cb == null) { Logger.shouldNotHappen("the callback Callback<Connector, IOException> is null while trying to send file " + fileToSend); return; } // make a connector ConnectableConnection conn; IPPort remote; try { remote = fileToSend.getRemoteAddress(); conn = ConnectableConnection.wrap(fileToSend, remote, ConnectionOpts.getDefault(), RingBuffer.allocate(0), RingBuffer.allocateDirect(0)); } catch (IOException e) { Logger.error(LogType.CONN_ERROR, "wrap " + fileToSend + " into ConnectableConnection failed", e); return; } var connector = new AlreadyConnectedConnector(remote, conn, ctx.loop); String id = ctx.connection.remote + " <- " + connector.remote; Logger.alert("sending large file: " + id); rootCtx.data.left.step = 4; // large file cb.succeeded(connector); } } } private final Socks5ProxyProtocolHandler socks5Handler = new Socks5ProxyProtocolHandler( (accepted, type, address, port, providedCallback) -> CoreUtils.directConnect(type, address, port, providedCallback)); private final Map<String, String> auth; private final Supplier<SSLEngine> engineSupplier; private final PageProvider pageProvider; public WebSocksProtocolHandler(Map<String, String> auth, Supplier<SSLEngine> engineSupplier, PageProvider pageProvider) { this.auth = auth; this.engineSupplier = engineSupplier; this.pageProvider = pageProvider; } private void initSSL(ProtocolHandlerContext<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>> ctx) { if (engineSupplier == null) { return; // not ssl, no need to init } assert Logger.lowLevelDebug("should upgrade the connection to ssl"); SSLEngine engine = engineSupplier.get(); SSLUtils.SSLBufferPair pair = SSLUtils.genbuf(engine, // we can allocate new buffer here, but it's ok to use the original allocated buffers (ByteBufferRingBuffer) ctx.connection.getInBuffer(), (ByteBufferRingBuffer) ctx.connection.getOutBuffer(), ctx.connection.channel); try { // when init, there should have not read any data yet // so we should safely replace the buffers ctx.connection.UNSAFE_replaceBuffer(pair.left, pair.right, true); } catch (IOException e) { Logger.shouldNotHappen("got error when switching buffers", e); // raise error to let others handle the error throw new RuntimeException("should not happen and the error is unrecoverable", e); } } @Override public void init(ProtocolHandlerContext<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>> ctx) { initSSL(ctx); // init if it's ssl (or may simply do nothing if not ssl) ctx.data = new Tuple<>(new WebSocksProxyContext( new SubProtocolHandlerContext<>(ctx, ctx.connectionId, ctx.connection, ctx.loop, new WebSocksHttpProtocolHandler(() -> ctx)), new SubProtocolHandlerContext<>(ctx, ctx.connectionId, ctx.connection, ctx.loop, socks5Handler) ), null); ctx.data.left.step = 1; // http ctx.data.left.httpContext.data = new WebSocksHttpContext(ctx.data.left); socks5Handler.init(ctx.data.left.socks5Context); ctx.data.left.socks5Context.data = new Tuple<>( ctx.data.left.socks5Context.data.left, // simply proxy the values of the Proxy lib new Callback<>() { @Override protected void onSucceeded(Connector connector) { String id = ctx.connection.remote + "->" + connector.remote; Logger.alert("proxy establishes: " + id); ctx.data.right.succeeded(connector); } @Override protected void onFailed(IOException err) { ctx.data.right.failed(err); } } ); } @Override public void readable(ProtocolHandlerContext<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>> ctx) { if (ctx.data.left.step == 1) { // http step ctx.data.left.httpContext.handler.readable(ctx.data.left.httpContext); } else if (ctx.data.left.step == 2) { // WebSocket handleWebSocket(ctx); } else { // socks5 step socks5Handler.readable(ctx.data.left.socks5Context); } } private void handleWebSocket(ProtocolHandlerContext<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>> ctx) { ByteArrayChannel chnl = ctx.data.left.webSocketBytes; ctx.inBuffer.writeTo(chnl); if (chnl.used() > 2) { // check first 2 bytes, whether it's indicating that it's a PONG message byte[] b = chnl.getBytes(); if ((b[0] & 0xf) == 0xA) { // opcode is PONG assert Logger.lowLevelDebug("received PONG message"); if (b[0] != (byte) 0b10001010 || b[1] != 0) { Logger.error(LogType.INVALID_EXTERNAL_DATA, "the message is PONG, but is not expected: [" + b[0] + "][" + b[1] + "]"); // here we went to an undefined state, we just leave it here } Utils.shiftLeft(b, 2); ctx.data.left.webSocketBytes = ByteArrayChannel.from(b, 0, chnl.used() - 2, b.length + 2 - chnl.used()); // then we read again handleWebSocket(ctx); return; } // otherwise it's not a PONG packet } else { return; // need more data } if (ctx.data.left.webSocketBytes.free() != 0) { return; // need more data } assert Logger.lowLevelDebug("web socket data receiving done"); ctx.data.left.step = 3; // socks5 WebSocksUtils.sendWebSocketFrame(ctx.connection.getOutBuffer()); if (ctx.inBuffer.used() != 0) { // still have data // let's call readable to handle the socks step readable(ctx); } } @Override public void exception(ProtocolHandlerContext<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>> ctx, Throwable err) { // connection should be closed by the protocol lib // we ignore the exception here assert Logger.lowLevelDebug("WebSocks exception " + ctx.connectionId + ", " + err); } @Override public void end(ProtocolHandlerContext<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>> ctx) { // connection is closed by the protocol lib // we ignore the event here assert Logger.lowLevelDebug("WebSocks end " + ctx.connectionId); } @Override public boolean closeOnRemoval(ProtocolHandlerContext<Tuple<WebSocksProxyContext, Callback<Connector, IOException>>> ctx) { if (ctx.data.left.step == 1 || ctx.data.left.step == 2) { // http step or WebSocket frame step return true; // proxy not established yet, so close the connection } else if (ctx.data.left.step == 3) { // socks5 step return socks5Handler.closeOnRemoval(ctx.data.left.socks5Context); } else { // large file return false; } } }
46.268022
159
0.544844
1017732632740aa3843a69abadd8fa6379ef6544
3,562
///* // * Copyright (c) 2020-2021 Heiko Bornholdt and Kevin Röbert // * // * Permission is hereby granted, free of charge, to any person obtaining a copy // * of this software and associated documentation files (the "Software"), to deal // * in the Software without restriction, including without limitation the rights // * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // * copies of the Software, and to permit persons to whom the Software is // * furnished to do so, subject to the following conditions: // * // * The above copyright notice and this permission notice shall be included in all // * copies or substantial portions of the Software. // * // * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // * OR OTHER DEALINGS IN THE SOFTWARE. // */ //package org.drasyl.crypto; // //import com.goterl.lazysodium.utils.Key; //import org.drasyl.AbstractBenchmark; //import org.drasyl.identity.IdentitySecretKey; //import org.drasyl.identity.IdentityPublicKey; //import org.drasyl.util.RandomUtil; //import org.openjdk.jmh.annotations.Benchmark; //import org.openjdk.jmh.annotations.BenchmarkMode; //import org.openjdk.jmh.annotations.Fork; //import org.openjdk.jmh.annotations.Measurement; //import org.openjdk.jmh.annotations.Mode; //import org.openjdk.jmh.annotations.Param; //import org.openjdk.jmh.annotations.Scope; //import org.openjdk.jmh.annotations.Setup; //import org.openjdk.jmh.annotations.State; //import org.openjdk.jmh.annotations.Threads; //import org.openjdk.jmh.annotations.Warmup; //import org.openjdk.jmh.infra.Blackhole; // //import java.security.IdentitySecretKey; //import java.security.IdentityPublicKey; // //@Fork(1) //@Warmup(iterations = 2) //@Measurement(iterations = 2) //@State(Scope.Benchmark) //public class CryptoBenchmark extends AbstractBenchmark { // @Param({ "1", "256", "5120" }) // private int size; // private byte[] message; // private Key publicKey; // private Key privateKey; // private byte[] signature; // // @Setup // public void setup() { // message = RandomUtil.randomBytes(size); // publicKey = IdentityPublicKey.of("030e54504c1b64d9e31d5cd095c6e470ea35858ad7ef012910a23c9d3b8bef3f22").toUncompressedKey(); // privateKey = IdentitySecretKey.of("6b4df6d8b8b509cb984508a681076efce774936c17cf450819e2262a9862f8").toUncompressedKey(); // try { // signature = Crypto.signMessage(privateKey, message); // } // catch (final CryptoException e) { // handleUnexpectedException(e); // } // } // // @Benchmark // @Threads(Threads.MAX) // @BenchmarkMode(Mode.Throughput) // public void signMessage(final Blackhole blackhole) { // try { // blackhole.consume(Crypto.signMessage(privateKey, message)); // } // catch (final CryptoException e) { // handleUnexpectedException(e); // } // } // // @Benchmark // @Threads(Threads.MAX) // @BenchmarkMode(Mode.Throughput) // public void verifySignature(final Blackhole blackhole) { // blackhole.consume(Crypto.verifySignature(publicKey, message, signature)); // } //}
40.022472
133
0.709152
4327c6e6a0aab578245b9919c4f69b971654b98e
643
package JAVA_20200331; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub showMyMoney1(); Main main = new Main(); main.showMyMoney1(); main.showMyMoney2(); main.showMyMoney3(); main.showMyMoney4(); main.showMyMoney5(); } public static void showMyMoney1() { System.out.println("1000won"); } public void showMyMoney2() { System.out.println("1000won"); } private void showMyMoney3() { System.out.println("1000won"); } protected void showMyMoney4() { System.out.println("1000won"); } void showMyMoney5() { System.out.println("1000won"); } }
15.682927
41
0.66563
cd0383b98ee891d6d963e4d8c6cec4f39ae2815d
5,790
/* * #%L * Wisdom-Framework * %% * Copyright (C) 2013 - 2015 Wisdom Framework * %% * 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. * #L% */ package org.modeshape.web.jcr.rest.handler; import org.wisdom.api.http.Request; import org.wisdom.api.http.Result; import javax.jcr.Property; import javax.jcr.RepositoryException; import java.io.InputStream; /** * User: Antoine Mischler <[email protected]> * Date: 19/03/15 * Time: 11:45 */ public interface RestBinaryHandler { /** * The default content disposition prefix, used when serving binary content. */ String DEFAULT_CONTENT_DISPOSITION_PREFIX = "attachment;filename="; /** * Returns a binary {@link javax.jcr.Property} for the given repository, workspace and path. * * @param request a non-null {@link Request} request * @param repositoryName a non-null {@link String} representing the name of a repository. * @param workspaceName a non-null {@link String} representing the name of a workspace. * @param binaryAbsPath a non-null {@link String} representing the absolute path to a binary property. * @return the {@link javax.jcr.Property} instance which is located at the given path. If such a property is not located, an exception * is thrown. * @throws javax.jcr.RepositoryException if any JCR related operation fails, including the case when the path to the property isn't valid. */ Property getBinaryProperty(Request request, String repositoryName, String workspaceName, String binaryAbsPath) throws RepositoryException; /** * Returns a default Content-Disposition {@link String} for a given binary property. * * @param binaryProperty a non-null {@link javax.jcr.Property} * @return a non-null String which represents a valid Content-Disposition. * @throws javax.jcr.RepositoryException if any JCR related operation involving the binary property fail. */ String getDefaultContentDisposition(Property binaryProperty) throws RepositoryException; /** * Returns the default mime-type of a given binary property. * * @param binaryProperty a non-null {@link javax.jcr.Property} * @return a non-null String which represents the mime-type of the binary property. * @throws javax.jcr.RepositoryException if any JCR related operation involving the binary property fail. */ String getDefaultMimeType(Property binaryProperty) throws RepositoryException; /** * Updates the {@link javax.jcr.Property property} at the given path with the content from the given {@link java.io.InputStream}. * * @param request a non-null {@link Request} request * @param repositoryName a non-null {@link String} representing the name of a repository. * @param workspaceName a non-null {@link String} representing the name of a workspace. * @param binaryPropertyAbsPath a non-null {@link String} representing the absolute path to a binary property. * @param binaryStream an {@link java.io.InputStream} which represents the new content of the binary property. * @param allowCreation a boolean flag which indicates what the behavior should be in case such a property does * not exist on its parent node: if the flag is {@code true}, the property will be created, otherwise a response code indicating * the absence is returned. * @return a {@link Result} object, which is either OK and contains the rest representation of the binary property, or is * NOT_FOUND. * @throws javax.jcr.RepositoryException if any JCR related operations fail * @throws IllegalArgumentException if the given input stream is {@code null} */ Result updateBinary(Request request, String repositoryName, String workspaceName, String binaryPropertyAbsPath, InputStream binaryStream, boolean allowCreation) throws RepositoryException; /** * Uploads a binary value at the given path, creating each missing path segment as an [nt:folder]. The binary is uploaded * as an [nt:resource] node of a [nt:file] node, both of which are created. * * @param request a {@link Request}, never {@code null} * @param repositoryName a {@link String}, the repository name; never {@code null} * @param workspaceName a {@link String}, the workspace name; never {@code null} * @param filePath a {@link String}, file absolute path to the [nt:file] node; never {@code null} * @param binaryStream an {@link java.io.InputStream} from which the binary content will be read. * @return a {@link Result} object, never {@code null} * @throws javax.jcr.RepositoryException if anything unexpected fails. */ Result uploadBinary(Request request, String repositoryName, String workspaceName, String filePath, InputStream binaryStream) throws RepositoryException; }
49.487179
161
0.671157
355a52a4323394442ea661d16cd7cb6437b17787
3,467
/* Copyright 2017 Ericsson AB. For a full list of individual contributors, please see the commit history. 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.ericsson.ei.queryservice; import java.util.ArrayList; import java.util.Iterator; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.ericsson.ei.mongodbhandler.MongoDBHandler; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * This class represents the mechanism to extract the aggregated data on the * basis of the SubscriptionName from the Missed Notification Object. * */ @Component public class ProcessMissedNotification { @Value("${missedNotificationCollectionName}") private String missedNotificationCollectionName; @Value("${missedNotificationDataBaseName}") private String missedNotificationDataBaseName; static Logger log = (Logger) LoggerFactory.getLogger(ProcessMissedNotification.class); @Autowired MongoDBHandler handler; /** * The method is responsible to extract the data on the basis of the * subscriptionName from the Missed Notification Object. * * @param subscriptionName * @return ArrayList */ public ArrayList processQueryMissedNotification(String subscriptionName) { ObjectMapper mapper = new ObjectMapper(); String condition = "{\"subscriptionName\" : \"" + subscriptionName + "\"}"; log.info("The condition is : " + condition); JsonNode jsonCondition = null; try { jsonCondition = mapper.readTree(condition); } catch (Exception e) { log.error(e.getMessage(), e); } log.info("The Json condition is : " + jsonCondition); ArrayList<String> output = handler.find(missedNotificationDataBaseName, missedNotificationCollectionName, jsonCondition.toString()); ArrayList<String> response = new ArrayList<String>(); Iterator itr = output.iterator(); while (itr.hasNext()) { String sElement = (String) itr.next(); try { JsonNode jElement = mapper.readTree(sElement); log.info("The individual element is : " + jElement.toString()); JsonNode element = jElement.path("AggregatedObject"); response.add(element.toString()); } catch (Exception e) { log.error(e.getMessage(), e); } } return response; } @PostConstruct public void init() { log.debug("The Aggregated Database is : " + missedNotificationDataBaseName); log.debug("The Aggregated Collection is : " + missedNotificationCollectionName); } }
37.27957
113
0.691376
38d8211020ada109a2a5a66c3e412d59ad584d86
2,331
package com.itextpdf.text.pdf; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.itextpdf.text.pdf.PRTokeniser.TokenType; import java.io.IOException; public class PRTokeniserTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } private void checkTokenTypes(String data, TokenType... expectedTypes) throws Exception { PRTokeniser tok = new PRTokeniser(new RandomAccessFileOrArray(data.getBytes())); for(int i = 0; i < expectedTypes.length; i++){ tok.nextValidToken(); //System.out.println(tok.getTokenType() + " -> " + tok.getStringValue()); Assert.assertEquals("Position " + i, expectedTypes[i], tok.getTokenType()); } } private void checkNumberValue(String data, String expectedValue) throws IOException { PRTokeniser tok = new PRTokeniser(new RandomAccessFileOrArray(data.getBytes())); tok.nextValidToken(); Assert.assertEquals("Wrong type", TokenType.NUMBER, tok.getTokenType()); Assert.assertEquals("Wrong multiple minus signs number handling", expectedValue, tok.getStringValue()); } @Test public void testOneNumber() throws Exception { checkTokenTypes( "/Name1 70", TokenType.NAME, TokenType.NUMBER, TokenType.ENDOFFILE ); } @Test public void testTwoNumbers() throws Exception { checkTokenTypes( "/Name1 70/Name 2", TokenType.NAME, TokenType.NUMBER, TokenType.NAME, TokenType.NUMBER, TokenType.ENDOFFILE ); } @Test public void testMultipleMinusSignsRealNumber() throws Exception { checkNumberValue("----40.25", "-40.25"); } @Test public void testMultipleMinusSignsIntegerNumber() throws Exception { checkNumberValue("--9", "0"); } @Test public void test() throws Exception { checkTokenTypes( "<</Size 70/Root 46 0 R/Info 44 0 R/ID[<8C2547D58D4BD2C6F3D32B830BE3259D><8F69587888569A458EB681A4285D5879>]/Prev 116 >>", TokenType.START_DIC, TokenType.NAME, TokenType.NUMBER, TokenType.NAME, TokenType.REF, TokenType.NAME, TokenType.REF, TokenType.NAME, TokenType.START_ARRAY, TokenType.STRING, TokenType.STRING, TokenType.END_ARRAY, TokenType.NAME, TokenType.NUMBER, TokenType.END_DIC, TokenType.ENDOFFILE ); } }
24.28125
126
0.714286
81d2db72034494cbd02ee5c99b9f885c713c792d
836
package org.kendar.utils; import com.google.common.hash.Hashing; import org.kendar.entities.GD2DriveItem; import org.kendar.entities.GD2DriveItemUtils; import javax.inject.Named; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; @Named("gD2Md5Calculator") public class GD2Md5CalculatorImpl implements GD2Md5Calculator { public void setupLocalMd5(GD2DriveItem local) throws GD2Exception { try{ if(local.getMd5()!=null && !local.getMd5().isEmpty())return; Path path = Paths.get(GD2DriveItemUtils.getPath(null,local).toString()); local.setMd5(com.google.common.io.Files. asByteSource(path.toFile()).hash(Hashing.md5()).toString()); }catch (IOException ex){ throw new GD2Exception("STATUS-22",ex); } } }
33.44
84
0.691388
224d8dc6ed5ab726a5ee60b871caf746df80966a
116
package com.semihunaldi.backendbootstrap.entitymodel.user; public enum RoleName { ROLE_USER, ROLE_ADMIN }
16.571429
58
0.767241
fe7c69d2b79a15345be63037f237dd49f400e13d
4,903
/* * 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 de.codekings.client.GUI.Katalog; import de.codekings.client.GUI.ContentView; import de.codekings.client.Controls.DataManager; import de.codekings.client.datacontent.Film_Client; import java.io.IOException; import java.util.ArrayList; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; /** * * @author Jan */ public class Katalogmanager implements ContentView { private ArrayList<Katalogeintrag> li_eintraege; private boolean contentready = false; private VBox content = new VBox(); private DataManager datamanager; public Katalogmanager(DataManager dmgr) { this.datamanager = dmgr; li_eintraege = new ArrayList<>(); } public boolean waitForContent() { return !contentready; } public void addEintrag(Katalogeintrag e) { if (!li_eintraege.contains(e)) { li_eintraege.add(e); } } public void removeEintrag(Katalogeintrag e) { if (li_eintraege.contains(e)) { li_eintraege.remove(e); } } public void removeEintrag(int index) { if (index >= 0 && index < li_eintraege.size()) { li_eintraege.remove(index); } } public Katalogeintrag getEintrag(int index) { if (index >= 0 && index < li_eintraege.size()) { return li_eintraege.get(index); } else { return null; } } @Override public Parent getContentView() { VBox vboxliste = new VBox(); for (Film_Client f : datamanager.getFilme()) { Pane pa = null; try { FXMLLoader fxmlLoader = new FXMLLoader(); pa = fxmlLoader.load(getClass().getClassLoader().getResource("de/codekings/client/GUI/Katalog/katalog_item.fxml").openStream()); Katalog_itemController kic = (Katalog_itemController) fxmlLoader.getController(); kic.setTitel(f.getS_titel()); kic.setDescription(f.getS_description()); //kic.setJahr("" + f.getRelease_date().getYear()); kic.setLaufzeit("" + f.getI_duration() + " min"); kic.setSubtitle(f.getS_subtitel()); kic.setCover(f.getCover().gibCoverImage()); Katalogeintrag k = new Katalogeintrag(pa, kic, f); addEintrag(k); kic.loadAfterInit(); vboxliste.getChildren().add(pa); } catch (IOException e) { System.out.println(e.getMessage()); } } content = vboxliste; contentready = true; return content; } public Parent getContentView(String search) { VBox vboxliste = new VBox(); for (Film_Client f : datamanager.getFilme()) { Pane pa = null; if (f.getS_titel().contains(search)) { try { FXMLLoader fxmlLoader = new FXMLLoader(); pa = fxmlLoader.load(getClass().getClassLoader().getResource("de/codekings/client/GUI/Katalog/katalog_item.fxml").openStream()); Katalog_itemController kic = (Katalog_itemController) fxmlLoader.getController(); kic.setTitel(f.getS_titel()); kic.setDescription(f.getS_description()); //kic.setJahr("" + f.getRelease_date().getYear()); kic.setLaufzeit("" + f.getI_duration() + " min"); kic.setSubtitle(f.getS_subtitel()); kic.setCover(f.getCover().gibCoverImage()); Katalogeintrag k = new Katalogeintrag(pa, kic, f); addEintrag(k); kic.loadAfterInit(); vboxliste.getChildren().add(pa); } catch (IOException e) { System.out.println(e.getMessage()); } } } if (vboxliste.getChildren().size() < 1) { Pane pa = null; try { FXMLLoader fxmlLoader = new FXMLLoader(); pa = fxmlLoader.load(getClass().getClassLoader().getResource("de/codekings/client/GUI/Katalog/nokatalog_item.fxml").openStream()); NoKatalog_itemController kic = (NoKatalog_itemController) fxmlLoader.getController(); kic.setSuchbefehl(search); vboxliste.getChildren().add(pa); } catch (IOException e) { System.out.println(e.getMessage()); } } content = vboxliste; contentready = true; return content; } }
31.837662
150
0.570671
097475be336fee046240ec39cc51316c463bcb80
557
package ru.swayfarer.swl2.z.dependencies.org.squiddev.luaj.luajc; import ru.swayfarer.swl2.z.dependencies.org.squiddev.luaj.luajc.analysis.ProtoInfo; /** * A handler for generation errors in classes. * * @see CompileOptions#handler */ public interface ErrorHandler { /** * Handle an error in generating a class * * @param info The prototype we are generating for * @param throwable The thrown exception. This will be an instance of {@link VerifyError} or {@link Exception}. */ void handleError(ProtoInfo info, Throwable throwable); }
29.315789
112
0.741472
aab0466fdac35cbec71276cf918f2989dceb10fe
1,540
package com.oop.memorystore.implementation.index; import java.util.List; import java.util.Objects; import java.util.Optional; public class SynchronizedIndex<T> implements Index<T> { private final Index<T> index; private final Object mutex; public SynchronizedIndex(final Index<T> index, final Object mutex) { this.index = index; this.mutex = mutex; } @Override public T getFirst(final Object key) { final T result; synchronized (mutex) { result = index.getFirst(key); } return result; } @Override public Optional<T> findFirst(final Object key) { final Optional<T> result; synchronized (mutex) { result = index.findFirst(key); } return result; } @Override public List<T> get(final Object key) { final List<T> results; synchronized (mutex) { results = index.get(key); } return results; } @Override public String getName() { return index.getName(); } public Index<T> getIndex() { return index; } @Override public boolean equals(final Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final SynchronizedIndex<?> that = (SynchronizedIndex<?>) other; return Objects.equals(index, that.index) && Objects.equals(mutex, that.mutex); } @Override public int hashCode() { return Objects.hash(index, mutex); } @Override public String toString() { return String.valueOf(index); } }
18.780488
82
0.644156
adbcb7453ed2f3c0192148df434d55ee24a9c8b8
287
package com.venafi.vcert.sdk.connectors.tpp.endpoint; import com.google.gson.annotations.SerializedName; import lombok.Data; @Data public class SetPolicyAttributeResponse { @SerializedName("Error") private String error; @SerializedName("Result") private int result; }
20.5
53
0.763066
c87c71af3a81cdcaca7f8f6634c487dea5934c41
2,729
/* * ICARUS2 Corpus Modeling Framework * Copyright (C) 2014-2022 Markus Gärtner <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.ims.icarus2.util; import java.util.Set; import de.ims.icarus2.util.collections.CollectionUtils; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; /** * @author Markus Gärtner * */ public class LongCounter<T extends Object> { private final Object2LongOpenHashMap<T> counts; public LongCounter() { counts = new Object2LongOpenHashMap<>(); counts.defaultReturnValue(0L); } public void copyFrom(LongCounter<? extends T> source) { counts.putAll(source.counts); } public void addAll(LongCounter<? extends T> source) { source.counts.object2LongEntrySet().forEach(e -> { add(e.getKey(), e.getLongValue()); }); } public long increment(T data) { return counts.addTo(data, 1) + 1; } public long add(T data, long delta) { long c = counts.getLong(data); c += delta; if(c<0) throw new IllegalStateException("Counter cannot get negative"); counts.put(data, c); // System.out.printf("%s: %d size=%d\n",data,c,counts.size()); return c; } public long decrement(T data) { long c = counts.getLong(data); if(c<1) throw new IllegalStateException("Cannot decrement count for data: "+data); //$NON-NLS-1$ c--; if(c==0) { counts.removeLong(data); } else { counts.put(data, c); } return c; } public void clear() { counts.clear(); } public long getCount(Object data) { return counts.getLong(data); } public void setCount(T data, long count) { if(count<0) throw new IllegalStateException("Counter cannot get negative: "+count); counts.put(data, count); } /** * Returns {@code true} iff the count for the given {@code data} is greater * that {@code 0}. * * @param data * @return */ public boolean hasCount(Object data) { long c = counts.getLong(data); return c>0; } public Set<T> getItems() { return CollectionUtils.getSetProxy(counts.keySet()); } public boolean isEmpty() { return counts.isEmpty(); } }
23.730435
92
0.662147
971271d7598b21666664378037662bb208109bf8
380
package com.study.java01; import java.util.Scanner; /*문제1. 요구사항] 횟수를 입력받아 인사를 하시오. 입력] 횟수 :3 출력] 안녕하세요~ 안녕하세요~ 안녕하세요~*/ public class For01 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("횟수 입력 : "); int n=sc.nextInt(); for (int i = 1; i <= n; i++) { System.out.println(i+"번째"+" . 안녕하세요"); } } }
17.272727
41
0.592105
7f6d128c6a188f56563f8c4827e090971ac100a2
283
package no.nav.foreldrepenger.mottak.innsending.pdf.modell; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) @Data @AllArgsConstructor public class FritekstBlokk extends Blokk { private String tekst; }
21.769231
59
0.819788
082f7311d28674b379f8cb65f88ceb385bc12d5e
6,029
/* * This file is part of bJdaUtilities, licensed under the MIT License. * * Copyright (c) 2019 bhop_ (Matt Worzala) * Copyright (c) 2019 contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.bhop.bjdautilities.command.provided; import me.bhop.bjdautilities.ReactionMenu; import me.bhop.bjdautilities.command.LoadedCommand; import me.bhop.bjdautilities.command.annotation.Command; import me.bhop.bjdautilities.command.annotation.Execute; import me.bhop.bjdautilities.command.result.CommandResult; import me.bhop.bjdautilities.pagination.Page; import me.bhop.bjdautilities.pagination.PageBuilder; import me.bhop.bjdautilities.pagination.PaginationEmbed; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import java.awt.*; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; /** * The provided command help implementation in a paginated list. */ @Command(label = {"help"}, usage = "help", description = "Receive information about all commands!") public class HelpCommand { private final int numEntries; private final Function<Guild, String> prefix; private final boolean usePermissions; public HelpCommand(int numEntries, Function<Guild, String> prefix, boolean usePermissions) { this.numEntries = numEntries; this.prefix = prefix; this.usePermissions = usePermissions; } @Execute public CommandResult onExecute(Member member, TextChannel channel, Message message, String label, List<String> args, Supplier<Set<LoadedCommand>> commandFetcher) { Set<LoadedCommand> commands = commandFetcher.get(); int page = 1; int count = 1; int size = (int) commandFetcher.get().stream().filter(cmd -> !usePermissions || member.hasPermission(cmd.getPermission())).count(); int maxPages = size % numEntries == 0 ? size / numEntries : size / numEntries + 1; List<Page> content = new ArrayList<>(); PaginationEmbed.Builder builder = new PaginationEmbed.Builder(member.getJDA()); while (count <= maxPages) { content.add(generatePage(page,numEntries, maxPages, commands.stream() .filter(cmd -> !usePermissions || member.hasPermission(cmd.getPermission())).skip((count - 1) * numEntries).limit(numEntries), member)); if (page < maxPages) page++; count++; } content.forEach(page1 -> builder.addPage(page1)); builder.buildAndDisplay(channel); return CommandResult.success(); } private Page generatePage(int page, int limit, int maxPages, Stream<LoadedCommand> commands, Member sender) { PageBuilder pageBuilder = new PageBuilder().setEntryLimit(limit).includeTimestamp(true).setColor(Color.CYAN).setTitle("__**Available Commands:**__"); pageBuilder.setFooter("Page " + page + " of " + maxPages, sender.getJDA().getSelfUser().getAvatarUrl()); commands.filter(cmd -> !cmd.isHiddenFromHelp()).forEach(cmd -> { StringBuilder aka = new StringBuilder("**"); String label = cmd.getLabels().get(0); aka.append(label.substring(0, 1).toUpperCase()).append(label.substring(1)).append("**"); if (cmd.getLabels().size() > 1) { aka.append(" (aka: "); cmd.getLabels().stream().skip(1).forEach(l -> aka.append(l).append(", ")); if (aka.charAt(aka.length() - 1) == ' ') aka.setLength(aka.length() - 2); aka.append(")"); } List<String> lines = new ArrayList<>(); if (cmd.getChildren().size() > 0) { StringBuilder children = new StringBuilder(); children.append("\u2022\u0020**Children:** "); for (LoadedCommand child : cmd.getChildren()) children.append(child.getLabels().get(0)).append(", "); if (aka.charAt(aka.length() - 1) == ' ') aka.setLength(aka.length() - 2); lines.add(children.toString()); } if (!cmd.getDescription().equals("")) lines.add("\u2022\u0020**Description:** " + cmd.getDescription()); if (!cmd.getUsageString().equals("")) lines.add("\u2022\u0020**Usage:** " + prefix.apply(sender.getGuild()) + cmd.getUsageString()); lines.add("\u2022\u0020**Permission:** " + (cmd.getPermission().get(0) == Permission.UNKNOWN ? "None" : cmd.getPermission().get(0).getName())); //todo temporarily first permission pageBuilder.addContent(false, aka.toString(), lines.toArray(new String[0])); }); return pageBuilder.build(); } }
48.620968
191
0.66827
f2f1b5741c96bdb819e28549a3945372342a6203
187
package biz.uro.CSVDataConverter.swing.json; @SuppressWarnings("serial") public class JSONException extends RuntimeException { JSONException( String message ) { super( message ); } }
23.375
53
0.775401
27d6682d9cfe269e2a77b6f4b3edf86f1bd215b9
907
package com.proposta.propostaservice.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; public class OfuscamentoUtilTest { @Test public void seDadoTiverTamanhoImparOfuscaTudoMenosPrimeiraLetra() { assertEquals("D************", OfuscamentoUtil.Ofuscar("Dado Sensivel")); assertEquals("4****", OfuscamentoUtil.Ofuscar("42422")); } @Test public void seDadoTiverTamanhoParOfuscaMetade(){ assertEquals("4*", OfuscamentoUtil.Ofuscar("42")); assertEquals("**do", OfuscamentoUtil.Ofuscar("dado")); } @Test public void seDadoTiverTamanhoIgualAUmOfuscaEle(){ assertEquals("*", OfuscamentoUtil.Ofuscar("4")); } @Test public void seDadoForVazioRetornaNulo() { assertNull(OfuscamentoUtil.Ofuscar("")); } }
27.484848
80
0.692393
cd31a20256af063f732de63714883f3cf8f535ca
10,902
/** * Ed-Fi Operational Data Store API * The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. The Ed-Fi ODS / API supports both transactional and bulk modes of operation. *** > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reasonable safeguards against cross-site scripting attacks and other malicious content, but the platform does not and cannot guarantee that the data it contains is free of all potentially harmful content.* *** * * OpenAPI spec version: 3 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.edfi.model.resource; import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import org.edfi.model.resource.TpdmSurveyQuestionReference; import org.edfi.model.resource.TpdmSurveyQuestionResponseSurveyQuestionMatrixElementResponse; import org.edfi.model.resource.TpdmSurveyResponseReference; /** * TpdmSurveyQuestionResponse */ @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2020-06-09T12:36:29.493-07:00") public class TpdmSurveyQuestionResponse { @SerializedName("id") private String id = null; @SerializedName("surveyQuestionReference") private TpdmSurveyQuestionReference surveyQuestionReference = null; @SerializedName("surveyResponseReference") private TpdmSurveyResponseReference surveyResponseReference = null; @SerializedName("comment") private String comment = null; @SerializedName("noResponse") private Boolean noResponse = null; @SerializedName("numericResponse") private Integer numericResponse = null; @SerializedName("surveyQuestionMatrixElementResponses") private List<TpdmSurveyQuestionResponseSurveyQuestionMatrixElementResponse> surveyQuestionMatrixElementResponses = new ArrayList<TpdmSurveyQuestionResponseSurveyQuestionMatrixElementResponse>(); @SerializedName("textResponse") private String textResponse = null; @SerializedName("_etag") private String etag = null; public TpdmSurveyQuestionResponse id(String id) { this.id = id; return this; } /** * * @return id **/ @ApiModelProperty(example = "null", required = true, value = "") public String getId() { return id; } public void setId(String id) { this.id = id; } public TpdmSurveyQuestionResponse surveyQuestionReference(TpdmSurveyQuestionReference surveyQuestionReference) { this.surveyQuestionReference = surveyQuestionReference; return this; } /** * Get surveyQuestionReference * @return surveyQuestionReference **/ @ApiModelProperty(example = "null", required = true, value = "") public TpdmSurveyQuestionReference getSurveyQuestionReference() { return surveyQuestionReference; } public void setSurveyQuestionReference(TpdmSurveyQuestionReference surveyQuestionReference) { this.surveyQuestionReference = surveyQuestionReference; } public TpdmSurveyQuestionResponse surveyResponseReference(TpdmSurveyResponseReference surveyResponseReference) { this.surveyResponseReference = surveyResponseReference; return this; } /** * Get surveyResponseReference * @return surveyResponseReference **/ @ApiModelProperty(example = "null", required = true, value = "") public TpdmSurveyResponseReference getSurveyResponseReference() { return surveyResponseReference; } public void setSurveyResponseReference(TpdmSurveyResponseReference surveyResponseReference) { this.surveyResponseReference = surveyResponseReference; } public TpdmSurveyQuestionResponse comment(String comment) { this.comment = comment; return this; } /** * Additional information provided by the responder about the question in the survey. * @return comment **/ @ApiModelProperty(example = "null", value = "Additional information provided by the responder about the question in the survey.") public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public TpdmSurveyQuestionResponse noResponse(Boolean noResponse) { this.noResponse = noResponse; return this; } /** * Indicates there was no response to the question. * @return noResponse **/ @ApiModelProperty(example = "null", value = "Indicates there was no response to the question.") public Boolean getNoResponse() { return noResponse; } public void setNoResponse(Boolean noResponse) { this.noResponse = noResponse; } public TpdmSurveyQuestionResponse numericResponse(Integer numericResponse) { this.numericResponse = numericResponse; return this; } /** * The numeric response to the question. * @return numericResponse **/ @ApiModelProperty(example = "null", value = "The numeric response to the question.") public Integer getNumericResponse() { return numericResponse; } public void setNumericResponse(Integer numericResponse) { this.numericResponse = numericResponse; } public TpdmSurveyQuestionResponse surveyQuestionMatrixElementResponses(List<TpdmSurveyQuestionResponseSurveyQuestionMatrixElementResponse> surveyQuestionMatrixElementResponses) { this.surveyQuestionMatrixElementResponses = surveyQuestionMatrixElementResponses; return this; } public TpdmSurveyQuestionResponse addSurveyQuestionMatrixElementResponsesItem(TpdmSurveyQuestionResponseSurveyQuestionMatrixElementResponse surveyQuestionMatrixElementResponsesItem) { this.surveyQuestionMatrixElementResponses.add(surveyQuestionMatrixElementResponsesItem); return this; } /** * An unordered collection of surveyQuestionResponseSurveyQuestionMatrixElementResponses. For matrix questions, the response for each row of the matrix. * @return surveyQuestionMatrixElementResponses **/ @ApiModelProperty(example = "null", value = "An unordered collection of surveyQuestionResponseSurveyQuestionMatrixElementResponses. For matrix questions, the response for each row of the matrix.") public List<TpdmSurveyQuestionResponseSurveyQuestionMatrixElementResponse> getSurveyQuestionMatrixElementResponses() { return surveyQuestionMatrixElementResponses; } public void setSurveyQuestionMatrixElementResponses(List<TpdmSurveyQuestionResponseSurveyQuestionMatrixElementResponse> surveyQuestionMatrixElementResponses) { this.surveyQuestionMatrixElementResponses = surveyQuestionMatrixElementResponses; } public TpdmSurveyQuestionResponse textResponse(String textResponse) { this.textResponse = textResponse; return this; } /** * The text response(s) for the question. * @return textResponse **/ @ApiModelProperty(example = "null", value = "The text response(s) for the question.") public String getTextResponse() { return textResponse; } public void setTextResponse(String textResponse) { this.textResponse = textResponse; } public TpdmSurveyQuestionResponse etag(String etag) { this.etag = etag; return this; } /** * A unique system-generated value that identifies the version of the resource. * @return etag **/ @ApiModelProperty(example = "null", value = "A unique system-generated value that identifies the version of the resource.") public String getEtag() { return etag; } public void setEtag(String etag) { this.etag = etag; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TpdmSurveyQuestionResponse tpdmSurveyQuestionResponse = (TpdmSurveyQuestionResponse) o; return Objects.equals(this.id, tpdmSurveyQuestionResponse.id) && Objects.equals(this.surveyQuestionReference, tpdmSurveyQuestionResponse.surveyQuestionReference) && Objects.equals(this.surveyResponseReference, tpdmSurveyQuestionResponse.surveyResponseReference) && Objects.equals(this.comment, tpdmSurveyQuestionResponse.comment) && Objects.equals(this.noResponse, tpdmSurveyQuestionResponse.noResponse) && Objects.equals(this.numericResponse, tpdmSurveyQuestionResponse.numericResponse) && Objects.equals(this.surveyQuestionMatrixElementResponses, tpdmSurveyQuestionResponse.surveyQuestionMatrixElementResponses) && Objects.equals(this.textResponse, tpdmSurveyQuestionResponse.textResponse) && Objects.equals(this.etag, tpdmSurveyQuestionResponse.etag); } @Override public int hashCode() { return Objects.hash(id, surveyQuestionReference, surveyResponseReference, comment, noResponse, numericResponse, surveyQuestionMatrixElementResponses, textResponse, etag); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TpdmSurveyQuestionResponse {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" surveyQuestionReference: ").append(toIndentedString(surveyQuestionReference)).append("\n"); sb.append(" surveyResponseReference: ").append(toIndentedString(surveyResponseReference)).append("\n"); sb.append(" comment: ").append(toIndentedString(comment)).append("\n"); sb.append(" noResponse: ").append(toIndentedString(noResponse)).append("\n"); sb.append(" numericResponse: ").append(toIndentedString(numericResponse)).append("\n"); sb.append(" surveyQuestionMatrixElementResponses: ").append(toIndentedString(surveyQuestionMatrixElementResponses)).append("\n"); sb.append(" textResponse: ").append(toIndentedString(textResponse)).append("\n"); sb.append(" etag: ").append(toIndentedString(etag)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
37.081633
544
0.755641
d0a2268464e2732a3d4ea7feb6010e2202480c77
3,491
package com.dreamwalker.knu2018.dteacher.Adapter; import android.content.Context; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.dreamwalker.knu2018.dteacher.Model.BloodSugar; import com.dreamwalker.knu2018.dteacher.Model.Global; import com.dreamwalker.knu2018.dteacher.R; import java.util.ArrayList; /** * Created by KNU2017 on 2018-02-11. */ class HomeViewHolder extends RecyclerView.ViewHolder{ TextView valueTypeTv; TextView valueTv; TextView timeTv; ImageView imageView; public HomeViewHolder(View itemView) { super(itemView); valueTypeTv = itemView.findViewById(R.id.valueTypeTextView); valueTv = itemView.findViewById(R.id.valueTextView); timeTv = itemView.findViewById(R.id.timeTextView); imageView = itemView.findViewById(R.id.homeImageView); } } public class HomeTimeLineAdapter extends RecyclerView.Adapter<HomeViewHolder>{ Context context; ArrayList<Global> bloodSugarArrayList; public HomeTimeLineAdapter(Context context, ArrayList<Global> bloodSugarArrayList) { this.context = context; this.bloodSugarArrayList = bloodSugarArrayList; } @Override public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View itemView = layoutInflater.inflate(R.layout.item_home_card,parent,false); HomeViewHolder homeViewHolder = new HomeViewHolder(itemView); return homeViewHolder; } @Override public void onBindViewHolder(HomeViewHolder holder, int position) { if (bloodSugarArrayList.get(position).getHead().equals("0")){ String value = "혈당 값 :" + bloodSugarArrayList.get(position).getValue(); holder.imageView.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.good_bloodsugar)); holder.valueTypeTv.setText(bloodSugarArrayList.get(position).getType()); holder.valueTv.setText(value); holder.timeTv.setText(bloodSugarArrayList.get(position).getTime()); }else if (bloodSugarArrayList.get(position).getHead().equals("1")){ String value = "칼로리 :" + bloodSugarArrayList.get(position).getValue(); holder.imageView.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.good_fitness)); holder.valueTypeTv.setText(bloodSugarArrayList.get(position).getType()); holder.valueTv.setText(value); holder.timeTv.setText(bloodSugarArrayList.get(position).getTime()); }else if (bloodSugarArrayList.get(position).getHead().equals("2")){ // TODO: 2018-02-11 식사 처리 추가해야해요 여기에 }else if (bloodSugarArrayList.get(position).getHead().equals("3")){ String value = "투약단위 :" + bloodSugarArrayList.get(position).getValue(); holder.imageView.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.fix_syringe)); holder.valueTypeTv.setText(bloodSugarArrayList.get(position).getType()); holder.valueTv.setText(value); holder.timeTv.setText(bloodSugarArrayList.get(position).getTime()); } } @Override public int getItemCount() { return bloodSugarArrayList.size(); } }
41.070588
109
0.717846
18400ed8f9f4a0709eef043b0c0572ca2b9daa46
1,403
package org.hammer.action; import org.hammer.dwarfs.Dwarf; import org.hammer.producao.Produto; import org.hammer.producao.game.GoldenHammer; import org.hammer.producao.game.utils.MovimentoUtils; public class Forjar implements Acao { private Produto produto; private Dwarf dwarf; private boolean terminou = false; private boolean indoParaAForja = true; private long contadorForjando = 4000; public Forjar(Produto produto, Dwarf dwarf) { super(); this.produto = produto; this.dwarf = dwarf; } public Produto getProduto() { return produto; } @Override public void executar(long delta) { GoldenHammer instance = GoldenHammer.instance(); if (indoParaAForja) { if (MovimentoUtils.moverAnaoParaEstacao(dwarf, instance.getOficinaFerreiro(), delta)) { instance.logMessage(dwarf.getNome() + " chegou na forja "); indoParaAForja = false; instance.getOficinaFerreiro().animate(); } } else if (contadorForjando >= 0) { contadorForjando -= delta; } else { instance.logMessage(dwarf.getNome() + " terminou de forjar um(a) " + produto); dwarf.addItemIventario(produto); terminou = true; } } @Override public boolean terminada() { return terminou; } }
28.06
99
0.625089
c0e101c68375ef04607bcbbf376a0c21d26364de
6,898
package kwasilewski.marketplace.dao; import kwasilewski.marketplace.dto.AdData; import kwasilewski.marketplace.dtoext.ad.AdSearchDataExt; import kwasilewski.marketplace.errors.MKTError; import kwasilewski.marketplace.errors.MKTException; import kwasilewski.marketplace.security.context.UserContext; import kwasilewski.marketplace.util.DateTimeUtil; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.persistence.*; import java.util.Date; import java.util.List; @Repository public class AdDAO { @PersistenceContext private EntityManager em; @Transactional public void create(AdData ad) throws DataAccessException, MKTException { if (ad.getId() != null) throw new MKTException(MKTError.AD_ALREADY_EXISTS); this.em.persist(ad); } @Transactional public void modify(UserContext ctx, AdData ad) throws DataAccessException, MKTException { AdData preModifyAd = ad.getId() != null ? find(ctx, ad.getId(), false) : null; if (preModifyAd == null) throw new MKTException(MKTError.NOT_AUTHORIZED); ad.setDate(preModifyAd.getDate()); ad.setViews(preModifyAd.getViews()); this.em.merge(ad); } @Transactional public void changeStatus(UserContext ctx, Long id) throws DataAccessException, MKTException { AdData ad = id != null ? find(ctx, id, false) : null; if (ad == null) throw new MKTException(MKTError.AD_NOT_EXISTS); if(!ad.isActive() && ad.isRefreshable()) { ad.setDate(new Date()); } ad.setActive(!ad.isActive()); this.em.merge(ad); } @Transactional public void refreshAd(UserContext ctx, Long id) throws DataAccessException, MKTException { AdData ad = id != null ? find(ctx, id, false) : null; if (ad == null) throw new MKTException(MKTError.AD_NOT_EXISTS); if (ad.isRefreshable()) { ad.setDate(new Date()); this.em.merge(ad); } } @Transactional public void remove(UserContext ctx, Long id) throws DataAccessException, MKTException { AdData ad = id != null ? get(ctx, id) : null; if (ad == null) throw new MKTException(MKTError.NOT_AUTHORIZED); this.em.remove(ad); } public List<AdData> getAll(UserContext ctx) throws DataAccessException { if (!ctx.isAdmin()) return null; TypedQuery<AdData> query = this.em.createQuery("SELECT ad FROM AdData ad", AdData.class); return query.getResultList(); } public AdData get(UserContext ctx, Long id) throws DataAccessException { if (!ctx.isAdmin()) return null; TypedQuery<AdData> query = this.em.createQuery("SELECT ad FROM AdData ad WHERE ad.id = :id", AdData.class); query.setParameter("id", id); try { return query.getSingleResult(); } catch (NoResultException e) { return null; } } public AdData find(Long id, boolean incrementViews) throws DataAccessException { String queryStr = "SELECT ad FROM AdData ad WHERE ad.id = :id"; queryStr += getActiveQuery(true); TypedQuery<AdData> query = this.em.createQuery(queryStr, AdData.class); query.setParameter("id", id); query.setParameter("date", DateTimeUtil.getMinAdActiveDate()); return getAdData(incrementViews, query); } public AdData find(UserContext ctx, Long id, boolean incrementViews) throws DataAccessException { String queryStr = "SELECT ad FROM AdData ad WHERE ad.id = :id"; queryStr += !ctx.isAdmin() ? " AND (ad.usrId = :usrId OR ad.active = TRUE)" : ""; TypedQuery<AdData> query = this.em.createQuery(queryStr, AdData.class); query.setParameter("id", id); if (!ctx.isAdmin()) query.setParameter("usrId", ctx.getUserId()); return getAdData(incrementViews, query); } private AdData getAdData(boolean incrementViews, TypedQuery<AdData> query) { AdData result; try { result = query.getSingleResult(); if(incrementViews) incrementViews(result.getId()); } catch (NoResultException e) { result = null; } return result; } public List<AdData> find(AdSearchDataExt criteria) throws DataAccessException { String queryStr = "SELECT ad FROM AdData ad WHERE ad.active = TRUE AND ad.date >= :date"; queryStr += criteria.getTitle() != null ? " AND upper(ad.title) LIKE :title" : ""; queryStr += criteria.getPrvId() != null ? " AND ad.prvId = :prvId" : ""; queryStr += criteria.getCatId() != null ? " AND (ad.catId = :catId OR ad.category.catId = :catId)" : ""; queryStr += criteria.getPriceMin() != null ? " AND ad.price >= :priceMin" : ""; queryStr += criteria.getPriceMax() != null ? " AND ad.price <= :priceMax" : ""; queryStr += " ORDER BY ad." + AdData.getSortingMethod(criteria.getSortingMethod()) +", ad.id"; TypedQuery<AdData> query = this.em.createQuery(queryStr, AdData.class); query.setParameter("date", DateTimeUtil.getMinAdActiveDate()); if (criteria.getTitle() != null) query.setParameter("title", "%" + criteria.getTitle().toUpperCase() + "%"); if (criteria.getPrvId() != null) query.setParameter("prvId", criteria.getPrvId()); if (criteria.getCatId() != null) query.setParameter("catId", criteria.getCatId()); if (criteria.getPriceMin() != null) query.setParameter("priceMin", criteria.getPriceMin()); if (criteria.getPriceMax() != null) query.setParameter("priceMax", criteria.getPriceMax()); query.setFirstResult(criteria.getOffset()); query.setMaxResults(criteria.getMaxResults()); return query.getResultList(); } public List<AdData> find(UserContext ctx, AdSearchDataExt criteria) throws DataAccessException { String queryStr = "SELECT ad FROM AdData ad WHERE ad.usrId = :usrId"; queryStr += getActiveQuery(criteria.isActive()) + " ORDER BY ad.date DESC"; TypedQuery<AdData> query = this.em.createQuery(queryStr, AdData.class); query.setParameter("usrId", ctx.getUserId()); query.setParameter("date", DateTimeUtil.getMinAdActiveDate()); query.setFirstResult(criteria.getOffset()); query.setMaxResults(criteria.getMaxResults()); return query.getResultList(); } private void incrementViews(Long id) { Query query = this.em.createQuery("UPDATE AdData ad SET ad.views = ad.views+1 WHERE ad.id = :id"); query.setParameter("id", id); query.executeUpdate(); } private String getActiveQuery(boolean active) { return active ? " AND ad.active = TRUE AND ad.date >= :date" : " AND (ad.active = FALSE OR ad.date < :date)"; } }
44.503226
117
0.659611
eb8b65697052038a3cf8b7bf01c2bbcc593bc9d3
220
package com.inetaddresstest; public class Student { public static void main(String[] args) { new Thread(new Demo01(6666,"127.0.0.1",9999)).start(); new Thread(new Demo02(7777,"老师")).start(); } }
24.444444
62
0.631818
649a6c3c6a0175866e4c8653643852597ed7e11e
21,279
/** * Autogenerated by Thrift Compiler (0.9.2) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.unionpay.serializer.thrift.dto; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) @Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2016-11-3") public class UserOrder implements org.apache.thrift.TBase<UserOrder, UserOrder._Fields>, java.io.Serializable, Cloneable, Comparable<UserOrder> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("UserOrder"); private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I64, (short)1); private static final org.apache.thrift.protocol.TField GMT_CREATE_FIELD_DESC = new org.apache.thrift.protocol.TField("gmtCreate", org.apache.thrift.protocol.TType.I64, (short)2); private static final org.apache.thrift.protocol.TField MONEY_FIELD_DESC = new org.apache.thrift.protocol.TField("money", org.apache.thrift.protocol.TType.I32, (short)3); private static final org.apache.thrift.protocol.TField LOCATION_FIELD_DESC = new org.apache.thrift.protocol.TField("location", org.apache.thrift.protocol.TType.STRING, (short)4); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new UserOrderStandardSchemeFactory()); schemes.put(TupleScheme.class, new UserOrderTupleSchemeFactory()); } public long id; // required public long gmtCreate; // required public int money; // required public String location; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ID((short)1, "id"), GMT_CREATE((short)2, "gmtCreate"), MONEY((short)3, "money"), LOCATION((short)4, "location"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ID return ID; case 2: // GMT_CREATE return GMT_CREATE; case 3: // MONEY return MONEY; case 4: // LOCATION return LOCATION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __ID_ISSET_ID = 0; private static final int __GMTCREATE_ISSET_ID = 1; private static final int __MONEY_ISSET_ID = 2; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.GMT_CREATE, new org.apache.thrift.meta_data.FieldMetaData("gmtCreate", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.MONEY, new org.apache.thrift.meta_data.FieldMetaData("money", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.LOCATION, new org.apache.thrift.meta_data.FieldMetaData("location", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(UserOrder.class, metaDataMap); } public UserOrder() { } public UserOrder( long id, long gmtCreate, int money, String location) { this(); this.id = id; setIdIsSet(true); this.gmtCreate = gmtCreate; setGmtCreateIsSet(true); this.money = money; setMoneyIsSet(true); this.location = location; } /** * Performs a deep copy on <i>other</i>. */ public UserOrder(UserOrder other) { __isset_bitfield = other.__isset_bitfield; this.id = other.id; this.gmtCreate = other.gmtCreate; this.money = other.money; if (other.isSetLocation()) { this.location = other.location; } } public UserOrder deepCopy() { return new UserOrder(this); } @Override public void clear() { setIdIsSet(false); this.id = 0; setGmtCreateIsSet(false); this.gmtCreate = 0; setMoneyIsSet(false); this.money = 0; this.location = null; } public long getId() { return this.id; } public UserOrder setId(long id) { this.id = id; setIdIsSet(true); return this; } public void unsetId() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID); } /** Returns true if field id is set (has been assigned a value) and false otherwise */ public boolean isSetId() { return EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID); } public void setIdIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value); } public long getGmtCreate() { return this.gmtCreate; } public UserOrder setGmtCreate(long gmtCreate) { this.gmtCreate = gmtCreate; setGmtCreateIsSet(true); return this; } public void unsetGmtCreate() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __GMTCREATE_ISSET_ID); } /** Returns true if field gmtCreate is set (has been assigned a value) and false otherwise */ public boolean isSetGmtCreate() { return EncodingUtils.testBit(__isset_bitfield, __GMTCREATE_ISSET_ID); } public void setGmtCreateIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __GMTCREATE_ISSET_ID, value); } public int getMoney() { return this.money; } public UserOrder setMoney(int money) { this.money = money; setMoneyIsSet(true); return this; } public void unsetMoney() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MONEY_ISSET_ID); } /** Returns true if field money is set (has been assigned a value) and false otherwise */ public boolean isSetMoney() { return EncodingUtils.testBit(__isset_bitfield, __MONEY_ISSET_ID); } public void setMoneyIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MONEY_ISSET_ID, value); } public String getLocation() { return this.location; } public UserOrder setLocation(String location) { this.location = location; return this; } public void unsetLocation() { this.location = null; } /** Returns true if field location is set (has been assigned a value) and false otherwise */ public boolean isSetLocation() { return this.location != null; } public void setLocationIsSet(boolean value) { if (!value) { this.location = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((Long)value); } break; case GMT_CREATE: if (value == null) { unsetGmtCreate(); } else { setGmtCreate((Long)value); } break; case MONEY: if (value == null) { unsetMoney(); } else { setMoney((Integer)value); } break; case LOCATION: if (value == null) { unsetLocation(); } else { setLocation((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case ID: return Long.valueOf(getId()); case GMT_CREATE: return Long.valueOf(getGmtCreate()); case MONEY: return Integer.valueOf(getMoney()); case LOCATION: return getLocation(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case ID: return isSetId(); case GMT_CREATE: return isSetGmtCreate(); case MONEY: return isSetMoney(); case LOCATION: return isSetLocation(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof UserOrder) return this.equals((UserOrder)that); return false; } public boolean equals(UserOrder that) { if (that == null) return false; boolean this_present_id = true; boolean that_present_id = true; if (this_present_id || that_present_id) { if (!(this_present_id && that_present_id)) return false; if (this.id != that.id) return false; } boolean this_present_gmtCreate = true; boolean that_present_gmtCreate = true; if (this_present_gmtCreate || that_present_gmtCreate) { if (!(this_present_gmtCreate && that_present_gmtCreate)) return false; if (this.gmtCreate != that.gmtCreate) return false; } boolean this_present_money = true; boolean that_present_money = true; if (this_present_money || that_present_money) { if (!(this_present_money && that_present_money)) return false; if (this.money != that.money) return false; } boolean this_present_location = true && this.isSetLocation(); boolean that_present_location = true && that.isSetLocation(); if (this_present_location || that_present_location) { if (!(this_present_location && that_present_location)) return false; if (!this.location.equals(that.location)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_id = true; list.add(present_id); if (present_id) list.add(id); boolean present_gmtCreate = true; list.add(present_gmtCreate); if (present_gmtCreate) list.add(gmtCreate); boolean present_money = true; list.add(present_money); if (present_money) list.add(money); boolean present_location = true && (isSetLocation()); list.add(present_location); if (present_location) list.add(location); return list.hashCode(); } @Override public int compareTo(UserOrder other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); if (lastComparison != 0) { return lastComparison; } if (isSetId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetGmtCreate()).compareTo(other.isSetGmtCreate()); if (lastComparison != 0) { return lastComparison; } if (isSetGmtCreate()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.gmtCreate, other.gmtCreate); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetMoney()).compareTo(other.isSetMoney()); if (lastComparison != 0) { return lastComparison; } if (isSetMoney()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.money, other.money); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetLocation()).compareTo(other.isSetLocation()); if (lastComparison != 0) { return lastComparison; } if (isSetLocation()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.location, other.location); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("UserOrder("); boolean first = true; sb.append("id:"); sb.append(this.id); first = false; if (!first) sb.append(", "); sb.append("gmtCreate:"); sb.append(this.gmtCreate); first = false; if (!first) sb.append(", "); sb.append("money:"); sb.append(this.money); first = false; if (!first) sb.append(", "); sb.append("location:"); if (this.location == null) { sb.append("null"); } else { sb.append(this.location); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (TException te) { throw new java.io.IOException(te); } } private static class UserOrderStandardSchemeFactory implements SchemeFactory { public UserOrderStandardScheme getScheme() { return new UserOrderStandardScheme(); } } private static class UserOrderStandardScheme extends StandardScheme<UserOrder> { public void read(org.apache.thrift.protocol.TProtocol iprot, UserOrder struct) throws TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ID if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.id = iprot.readI64(); struct.setIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // GMT_CREATE if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.gmtCreate = iprot.readI64(); struct.setGmtCreateIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // MONEY if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.money = iprot.readI32(); struct.setMoneyIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // LOCATION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.location = iprot.readString(); struct.setLocationIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, UserOrder struct) throws TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(ID_FIELD_DESC); oprot.writeI64(struct.id); oprot.writeFieldEnd(); oprot.writeFieldBegin(GMT_CREATE_FIELD_DESC); oprot.writeI64(struct.gmtCreate); oprot.writeFieldEnd(); oprot.writeFieldBegin(MONEY_FIELD_DESC); oprot.writeI32(struct.money); oprot.writeFieldEnd(); if (struct.location != null) { oprot.writeFieldBegin(LOCATION_FIELD_DESC); oprot.writeString(struct.location); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class UserOrderTupleSchemeFactory implements SchemeFactory { public UserOrderTupleScheme getScheme() { return new UserOrderTupleScheme(); } } private static class UserOrderTupleScheme extends TupleScheme<UserOrder> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, UserOrder struct) throws TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetId()) { optionals.set(0); } if (struct.isSetGmtCreate()) { optionals.set(1); } if (struct.isSetMoney()) { optionals.set(2); } if (struct.isSetLocation()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetId()) { oprot.writeI64(struct.id); } if (struct.isSetGmtCreate()) { oprot.writeI64(struct.gmtCreate); } if (struct.isSetMoney()) { oprot.writeI32(struct.money); } if (struct.isSetLocation()) { oprot.writeString(struct.location); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, UserOrder struct) throws TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.id = iprot.readI64(); struct.setIdIsSet(true); } if (incoming.get(1)) { struct.gmtCreate = iprot.readI64(); struct.setGmtCreateIsSet(true); } if (incoming.get(2)) { struct.money = iprot.readI32(); struct.setMoneyIsSet(true); } if (incoming.get(3)) { struct.location = iprot.readString(); struct.setLocationIsSet(true); } } } }
30.398571
180
0.66427
a92bf179253f62e5e79d1a1caf1edcfea00e35ca
953
package hr.zg.rus; import java.util.Hashtable; public class NetworksTest { public static void main(String[] args) { Networks networks = new Networks(); Hashtable<String, Hashtable> network = networks.getNetworks(); byte value; value = (byte)network.get("bitcoin").get("wif"); if(value != -128){ System.out.println("Invalid mainnet WIF prefix!"); } value = (byte)network.get("bitcoin").get("pubKeyHash"); if(value != 0){ System.out.println("Invalid mainnet pubKeyHash prefix!"); } value = (byte)network.get("testnet").get("wif"); if(value != -17){ System.out.println("Invalid testnet WIF prefix!"); } value = (byte)network.get("testnet").get("pubKeyHash"); if(value != 111){ System.out.println("Invalid testnet pubKeyHash prefix!"); } } }
28.878788
71
0.550892
be5add7959fa49edaa4bbb03259d0edda0aabfe5
15,427
/* * Copyright 2015-2021 Alexandr Evstigneev * * 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 unit.perl.parser; import com.perl5.lang.perl.idea.configuration.settings.PerlSharedSettings; import org.junit.Test; public class PerlParserTest extends PerlParserTestBase { @Override protected String getBaseDataPath() { return "testData/unit/perl/parser"; } @Test public void testIssue2319() {doTest();} @Test public void testAnnotationNoInject() {doTest();} @Test public void testIssue2308() {doTest();} @Test public void testIssue2298() {doTest();} @Test public void testIssue2306() {doTest();} @Test public void testIssue2306Sequence() {doTest();} @Test public void testIssue2304() {doTest();} @Test public void testScalarCall() {doTest();} @Test public void testArrayIndex() {doTest();} @Test public void testStringQQCorruptingOutside() {doTest(false);} @Test public void testStringQXCorruptingOutside() {doTest(false);} @Test public void testFileTestBareHandle() {doTest();} @Test public void testIsaOperatorAsSub() {doTest();} @Test public void testFpFallback() {doTest();} @Test public void testStatementModifiers() {doTest();} @Test public void testCharSubstitutionsWithUnderscore() {doTest();} @Test public void testStringsWithBlockUnclosed() {doTest(false);} @Test public void testReplaceRegexWithBlockUnclosed() {doTest(false);} @Test public void testPrintOperators() {doTest();} @Test public void testPrintArguments() {doTest();} @Test public void testAnonHashDetection() {doTest();} @Test public void testCommaAfterAnonHash() {doTest();} @Test public void testCommaAfterAnonHashMulti() {doTest();} @Test public void testStringListWithEscapes() {doTest();} @Test public void testReplaceRegexWithComments() { setSkipSpaces(false); doTest(); } @Test public void testLazyParsableNestedBlocks() {doTest();} @Test public void testBackReferencesOld() { doTest(); } @Test public void testTrBlocks() { doTest(); } @Test public void testTrBlocksLazy() { doTest(); } @Test public void testQuoteLikeSingleQuotes() { doTest(); } @Test public void testRegexpWithSingleQuotes() { setSkipSpaces(false); doTest(); } @Test public void testRegexExtended() { setSkipSpaces(false); doTest(); } @Test public void testSpecialCharsInReplacements() {doTest();} @Test public void testEscapeInSQStrings() {doTest();} @Test public void testEscapeInSqHeredoc() {doTest();} @Test public void testEscapeInSQStringsLazy() {doTest();} @Test public void testSmartLongStrings() {doTest();} @Test public void testBackReferences() {doTest();} @Test public void testOctSubstitutionCorrect() {doTest();} @Test public void testOctSubstitutionCorrectHeredocs() {doTest();} @Test public void testOctSubstitutionCorrectXQ() {doTest();} @Test public void testOctSubstitutionCorrectSQ() {doTest();} @Test public void testOctSubstitutionIncorrect() {doTest(false);} @Test public void testHexSubstitutionsCorrect() {doTest();} @Test public void testHexSubstitutionsCorrectHeredoc() {doTest();} @Test public void testHexSubstitutionsCorrectXQ() {doTest();} @Test public void testHexSubstitutionsCorrectSQ() {doTest();} @Test public void testHexSubstitutionsIncorrect() {doTest(false);} @Test public void testUnicodeSubstitutionsCorrect() {doTest();} @Test public void testUnicodeSubstitutionsCorrectHeredoc() {doTest();} @Test public void testUnicodeSubstitutionsCorrectXQ() {doTest();} @Test public void testUnicodeSubstitutionsCorrectSQ() {doTest();} @Test public void testUnicodeSubstitutionsIncorrect() {doTest(false);} @Test public void testControlSequenceCVariants() {doTest();} @Test public void testControlSequencesInStrings() {doTest();} @Test public void testControlSequencesInStringsMetaQuoted() {doTest();} @Test public void testMooseDefaultFallback() {doTest();} @Test public void testNotAnnotationComment() {doTest();} @Test public void testScalarCoderef() {doTest();} @Test public void testDefinedAndLength() {doTest();} @Test public void testShiftPopPushUnshift() {doTest();} @Test public void testAngledHandles() {doTest();} @Test public void testCpanfile() { String ext = myFileExt; try { myFileExt = ""; doTest(); } finally { myFileExt = ext; } } @Test public void testFunctionLikeExpr() {doTest();} @Test public void testStringBitwiseOperators() {doTest();} @Test public void testChainedComparison() {doTest();} @Test public void testIsaExpr() {doTest();} @Test public void testSignatureTrailingComma() { doTest(); } @Test public void testSignatureRecovery() { doTest(false); } @Test public void testIssue2158() {doTest();} @Test public void testSlices520() {doTest();} @Test public void testDefinedSigils() {doTest();} @Test public void testIssue2084() {doTest();} @Test public void testFileTestPrecedence() {doTest();} @Test public void testSpliceExpr() {doTest();} @Test public void testDefinedExpr() {doTest();} @Test public void testScalarExpr() {doTest(false);} @Test public void testUndefInDeclaration() {doTest();} @Test public void testMatchRegexWithBlock() {doTest();} @Test public void testMatchRegexWithBlockUnclosed() {doTest(false);} @Test public void testDefaultSub() {doTest();} @Test public void testFalsePositiveIndexInRegexp() {doTest();} @Test public void testPackageAsMethod() {doTest();} @Test public void testParentSub() {doTest();} @Test public void testPodInTheData() {doTest();} @Test public void testPodInTheEnd() {doTest();} @Test public void testPeriodInIndex() {doTest();} @Test public void testVariableIndexWithConcatenation() {doTest();} @Test public void testOldPerlVersionAsIndex() {doTest();} @Test public void testReadonly() {doTest();} @Test public void testRightwardFancyCall() {doTest();} @Test public void testPrintSubAndSomething() {doTest();} @Test public void testDiamondAfterScalar() {doTest();} @Test public void testLpLogicAfterComma() {doTest();} @Test public void testFlowControlWithDeref() {doTest();} @Test public void testPackageSubPackage() {doTest();} @Test public void testDeleteInList() {doTest();} @Test public void testExitKeyword() {doTest();} @Test public void testSayWithFatComma() {doTest();} @Test public void testScalarUnary() {doTest();} @Test public void testSmarterHash() {doTest();} @Test public void testAttributes528() {doTest();} @Test public void testSubExprComplex() {doTest();} @Test public void testEndSimple() {doTest();} @Test public void testEndMiddle() {doTest();} @Test public void testDataSimple() {doTest();} @Test public void testDataMiddle() {doTest();} @Test public void testIssue1723() {doTest();} @Test public void testMoose() {doTest();} @Test public void testDeclarations() {doTest();} @Test public void testNumericX() {doTest();} @Test public void testStringCmpWithPackage() {doTest();} @Test public void testIssue1655() {doTest();} @Test public void testForIndexedContinue() {doTest(false);} @Test public void testForEachIndexedContinue() {doTest(false);} @Test public void testComplexType() {doTest();} @Test public void testComplexReturns() {doTest();} @Test public void testWildCardReturns() {doTest();} @Test public void testContinueExpr() {doTest();} @Test public void testRangeAfterNumber() {doTest();} @Test public void testStandardTypes() {doTest();} @Test public void testNamespaceBinding() {doTest();} @Test public void testIssue1506() {doTest();} @Test public void testParenthesizedPrintArguments() {doTest();} @Test public void testBareAccessors() {doTest();} @Test public void testClassAccessorSubDeclaration() {doTest();} @Test public void testUseBareword() {doTest();} @Test public void testClassAccessor() {doTest();} @Test public void testExceptionClass() {doTest();} @Test public void testIssue1449() {doTest();} @Test public void testDeclareReference() {doTest();} @Test public void testBuiltInWithRefs() {doTest();} @Test public void testIssue1434() {doTest();} @Test public void testIssue1435() {doTest();} @Test public void testLexicalSubs() {doTest();} @Test public void testComplexModifiers() {doTest();} @Test public void testRegexSpacing() {doTest();} @Test public void testSuperExtendedRegexp() {doTest();} @Test public void testUseVars() { setSkipSpaces(false); doTest(); } @Test public void testIncorrectIndexes() { doTest(); } @Test public void testCharGroups() { doTest(); } @Test public void testCoreModules() { doTest(); } @Test public void testMultiTokenElements() { doTest(); } @Test public void testHandleAcceptors() { doTest(); } @Test public void testDynaLoaderCall() { doTest(); } @Test public void testFancyImport() { doTest(); } @Test public void testUniversalCan() { doTest(); } @Test public void testDefinedGlob() { doTest(); } @Test public void testCallPrecedance() { doTest(false); } @Test public void testSortArguments() { doTest(); } @Test public void testPerlPod() { doTest(); } @Test public void testPerlPodEmpty() { doTest(); } @Test public void testPerlPodIncomplete() { doTest(); } @Test public void testQuoteLikeWithHeredocs() { doTest(); } @Test public void testQwEmpty() { doTest(); } @Test public void testVarsAndCasts() { doTest(); } @Test public void testSubPrototypes() { doTest(); } @Test public void testLookAheadEofBug() { doTest(false); } @Test public void testVariableAttributes() { doTest(); } @Test public void testLazyParsableBlocks() { doTest(); } @Test public void testCommentInRegexp() { doTest(); } @Test public void testCommentInString() { doTest(); } @Test public void testHeredocs() { doTest(); } @Test public void testHeredocSequential() { doTest(); } @Test public void testHeredocUnclosed() { doTest(); } @Test public void testIndentableHeredocs() { doTest(); } @Test public void testIndentableHeredocSequential() { doTest(); } @Test public void testIndentableHeredocUnclosed() { doTest(); } @Test public void testHeredocUnclosedWithEmptyMarker() { doTest(); } @Test public void testSubAttributes() { doTest(); } @Test public void testSubSignatures() { doTest(); } @Test public void testSubSignaturesFromVimSupport() { doTest(); } @Test public void testFormat() { doTest(); } @Test public void testFormatEmpty() { doTest(); } @Test public void testFormatIncomplete() { doTest(false); } @Test public void testFormatEmptyIncomplete() { doTest(false); } @Test public void testNamedBlocks() { doTest(); } @Test public void testVariablesAndElements() { doTest(); } @Test public void testRegexpTailingBuck() { doTest(); } @Test public void testAmbiguousSigils() { doTest(); } @Test public void testTryCatchHybrid() { doTest(); } @Test public void testTryCatchVariants() { doTest(); } @Test public void testTryDancerException() {doTest();} @Test public void testTryError() {doTest();} @Test public void testTryExceptionClass() {doTest();} @Test public void testTryTry__Catch() {doTest();} @Test public void testTryTryCatch() {doTest();} @Test public void testTryTryCatchInSub() {doTest();} @Test public void testTryTryTiny() {doTest();} @Test public void testTryCatchErrors() {doTest();} @Test public void testHashAcceptors() { doTest(); } @Test public void testKeywordAsLabel() { doTest(); } @Test public void testKeywordsWithCore() { doTest(); } @Test public void testParserRefactoringBugs() { doTest(); } @Test public void testPostDeref() { doTest(); } @Test public void testInterpolation() { doTest(); } @Test public void testCompositeOps() { doTest(); } @Test public void testCompositeOpsSpaces() { doTest(false); } @Test public void testAnnotation() { doTest(false); } @Test public void testConstant() { doTest(); } @Test public void testBareUtfString() { doTest(); } @Test public void testLazyParsing() { doTest(); } @Test public void testParserTestSet() { doTest(); } @Test public void testTrickySyntax() { doTest(); } @Test public void testVariables() { doTest(); } @Test public void testMethodSignaturesSimple() { doTest(); } @Test public void testUtfIdentifiers() { doTest(); } @Test public void testVarRefactoringBugs() { doTest(); } @Test public void testSwitchAsSub() { doTest(); } @Test public void testPerlSwitch() { PerlSharedSettings.getInstance(getProject()).PERL_SWITCH_ENABLED = true; doTest(); } @Test public void testInterpolatedHashArrayElements() { doTest(); } @Test public void testImplicitRegex() { doTest(); } @Test public void testCamelcade94() { doTest(false); } @Test public void testIssue855() { doTest(); } @Test public void testIssue867() { doTest(); } @Test public void testRegexNModifier() { doTest(); } @Test public void testUtf8PackageName() { doTest(); } @Test public void testHexBinNumbersParsing() { doTest(); } @Test public void test28BackrefStyleHeredoc() { doTest(); } @Test public void testLabelsParsing() { doTest(); } @Test public void testInterpolatedElements() { doTest(); } @Test public void testOperatorsAfterLoopControl() {doTest();} @Test public void testAsyncSubExpr() {doTest();} @Test public void testAsyncDeclaration() {doTest(false);} @Test public void testAsyncJoined() {doTest(false);} @Test public void testAsyncDefinition() {doTest();} @Test public void testAsyncDefinitionFunc() {doTest();} @Test public void testAsyncDefinitionMethod() {doTest();} @Test public void testAsyncStatement() {doTest();} @Test public void testNumbers() {doTest();} @Test public void testFunctionParametersSyntax() { doTest(); } @Test public void testShiftLike() { doTest(); } }
16.91557
76
0.663123
a1f8fc044bcbf91ceee4a4a820f8429700f3065a
14,072
package com.toluene.commonbatis.plugin; import com.toluene.commonbatis.util.MapperResolver; import com.toluene.commonbatis.util.ReflectionUtil; import com.toluene.commonbatis.util.SimpleCache; import com.toluene.commonbatis.util.TableNameParser; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.*; import org.apache.ibatis.plugin.*; import org.apache.ibatis.scripting.defaults.RawSqlSource; import org.apache.ibatis.scripting.xmltags.DynamicSqlSource; import org.apache.ibatis.scripting.xmltags.MixedSqlNode; import org.apache.ibatis.scripting.xmltags.SqlNode; import org.apache.ibatis.scripting.xmltags.StaticTextSqlNode; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.xml.sax.SAXException; import java.lang.reflect.Field; import java.util.*; @Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class})}) public class Transfer implements Interceptor { private volatile boolean init = false; private final String KEY = "key"; private final String ENTITY = "entity"; private Set<String> commondSqlIdSet = new TreeSet<String>(); private void init() { if (init) return; try { commondSqlIdSet = MapperResolver.getElementsSet("id", "com/toluene/commonbatis/dao/mapper/CommonDaoMapper.xml"); } catch (SAXException e) { e.printStackTrace(); } } private void processDynamicResultMapIntercept(Invocation invocation, boolean handleKey) { final Object[] queryArgs = invocation.getArgs(); final MappedStatement ms = (MappedStatement) queryArgs[0]; final Object parameter = queryArgs[1]; String targetSimpleName = getTableName(parameter, true); String tableSimpleName = getTableName(parameter, false); reconstructSqlSource(ms, parameter, targetSimpleName, handleKey, APPENDTYPE.NONE); Class<?> targetClass = null; try { targetClass = Class.forName(tableSimpleName); } catch (ClassNotFoundException e) { e.printStackTrace(); } ResultMap.Builder builder = new ResultMap.Builder( ms.getConfiguration(), ms.getId(), targetClass, new ArrayList<ResultMapping>()); List<ResultMap> resultMaps = new ArrayList<ResultMap>(); resultMaps.add(0, builder.build()); ReflectionUtil.setTarget(ms, resultMaps, "resultMaps"); } private void processIntercept(Invocation invocation, boolean handleKey, APPENDTYPE appendType) { final Object[] queryArgs = invocation.getArgs(); final MappedStatement ms = (MappedStatement) queryArgs[0]; final Object parameter = queryArgs[1]; String tableSimpleName = getTableName(parameter, true); reconstructSqlSource(ms, parameter, tableSimpleName, handleKey, appendType); } @SuppressWarnings("unchecked") private void reconstructSqlSource(MappedStatement ms, Object parameter, String tableSimpleName, boolean handleKey, APPENDTYPE appendType) { SqlSource sqlSource = ms.getSqlSource(); if (sqlSource instanceof RawSqlSource) { BoundSql boundSql = sqlSource.getBoundSql(parameter); String sql = boundSql.getSql(); String cachePreSql; SimpleCache.MAPTYPE mapperType = MapperResolver.getSqlIdToCacheMap().get(ms.getId()); if (!sql.contains("@")) { cachePreSql = SimpleCache.get(tableSimpleName, mapperType); sql = (cachePreSql == null ? MapperResolver.getMapTypeToRawSqlMap().get(mapperType) : cachePreSql); } if (sql.contains("@")) { TableNameParser tableNameParser; tableNameParser = new TableNameParser("@", "@", tableSimpleName); sql = tableNameParser.parse(sql); SimpleCache.put(tableSimpleName, sql, mapperType); } if (appendType == APPENDTYPE.INSERT) { sql = appendInsertStatement(sql, ((HashMap) parameter).get(ENTITY)); } else { if (appendType == APPENDTYPE.UPDATE) { sql = appendUpdateStatement(sql, ((HashMap) parameter).get(ENTITY)); } if (handleKey) { sql = fixKeyStatement(sql, ((HashMap) parameter).get(KEY)); } } RawSqlSource rawSqlSource = new RawSqlSource(ms.getConfiguration(), sql, null); ReflectionUtil.setTarget(ms, rawSqlSource, "sqlSource"); } else if (sqlSource instanceof DynamicSqlSource) { SqlNode sqlNode = null; try { sqlNode = (SqlNode) ReflectionUtil.getFieldValue(sqlSource, "rootSqlNode"); } catch (Exception e) { e.printStackTrace(); } if (sqlNode instanceof MixedSqlNode) { List<SqlNode> contents = (List<SqlNode>) ReflectionUtil.getFieldValue(sqlNode, "contents"); SqlNode node = contents.get(0); if (node instanceof StaticTextSqlNode) { String sql = (String) ReflectionUtil.getFieldValue(node, "text"); String cachePreSql; SimpleCache.MAPTYPE mapperType = MapperResolver.getSqlIdToCacheMap().get(ms.getId()); if (!sql.contains("@")) { cachePreSql = SimpleCache.get(tableSimpleName, mapperType); sql = (cachePreSql == null ? MapperResolver.getMapTypeToRawSqlMap().get(mapperType) : cachePreSql); } if (sql.contains("@")) { TableNameParser tableNameParser; tableNameParser = new TableNameParser("@", "@", tableSimpleName); sql = tableNameParser.parse(sql); SimpleCache.put(tableSimpleName, sql, mapperType); } if (appendType == APPENDTYPE.INSERT) { sql = appendInsertStatement(sql, ((HashMap) parameter).get(ENTITY)); } else if (appendType == APPENDTYPE.UPDATE) { sql = appendUpdateStatement(sql, ((HashMap) parameter).get(ENTITY)); if (handleKey) { sql = fixKeyStatement(sql, ((HashMap) parameter).get(KEY)); } } StaticTextSqlNode staticTextSqlNode = new StaticTextSqlNode(sql); contents.set(0, staticTextSqlNode); ReflectionUtil.setTarget(sqlNode, contents, "contents"); DynamicSqlSource dynamicSqlSource = new DynamicSqlSource(ms.getConfiguration(), sqlNode); ReflectionUtil.setTarget(ms, dynamicSqlSource, "sqlSource"); } else { throw new RuntimeException("reconstruct sqlSource exception, sqlNode is not instanceof StaticTextSqlNode!"); } } else { throw new RuntimeException("reconstruct sqlSource exception, sqlNode is not instanceof MixedSqlNode!"); } } } private String appendUpdateStatement(String sql, Object obj) { StringBuilder builder = new StringBuilder(); builder.append(sql).append(" "); List<Field> fieldList = ReflectionUtil.getAllFields(obj.getClass()); if (fieldList != null) { boolean firstVal = true; for (int i = 0; i < fieldList.size(); i++) { boolean add = false; Field field = fieldList.get(i); try { add = field.get(obj) != null; } catch (IllegalAccessException e) { e.printStackTrace(); } if (add) { if (!firstVal) { builder.append(","); } else { builder.append(" set "); } String filedName = field.getName(); builder.append(filedName).append("="); builder.append("#{").append(ENTITY).append(".").append(filedName).append("}"); firstVal = false; } } } return builder.toString(); } private String appendInsertStatement(String sql, Object obj) { StringBuilder builderPre = new StringBuilder(); StringBuilder builderSuf = new StringBuilder(); builderPre.append(" ("); builderSuf.append(" values ("); List<Field> fieldList = ReflectionUtil.getAllFields(obj.getClass()); if (fieldList != null) { boolean firstVal = true; for (int i = 0; i < fieldList.size(); i++) { boolean add = false; Field field = fieldList.get(i); try { add = field.get(obj) != null; } catch (IllegalAccessException e) { e.printStackTrace(); } if (add) { if (!firstVal) { builderPre.append(","); builderSuf.append(","); } String filedName = field.getName(); builderPre.append(filedName); builderSuf.append("#{").append(ENTITY).append(".").append(filedName).append("}"); firstVal = false; } } } else { throw new RuntimeException("entity key has no field exception!"); } builderPre.append(")"); builderSuf.append(")"); return sql + builderPre + builderSuf; } private String fixKeyStatement(String sql, Object obj) { StringBuilder builder = new StringBuilder(); builder.append(sql); builder.append(" where "); List<Field> fieldList = ReflectionUtil.getAllFields(obj.getClass()); if (fieldList != null) { boolean added = false; for (int i = 0; i < fieldList.size(); i++) { boolean add = false; Field field = fieldList.get(i); try { add = field.get(obj) != null; } catch (IllegalAccessException e) { e.printStackTrace(); } if (add) { if (added) { builder.append(" and "); } String filedName = field.getName(); builder.append(filedName).append("=#{").append(KEY).append(".").append(filedName).append("}"); added = true; } } } else { throw new RuntimeException("entity key has no field exception!"); } return builder.toString(); } @SuppressWarnings("rawtypes") private String getTableName(Object obj, boolean simple) { String name; if (obj instanceof HashMap) { Object param1 = ((HashMap) obj).get("param1"); if (param1 instanceof Class) { name = ((Class) param1).getName(); } else { name = param1.getClass().getName(); } if (!simple) { return name; } int start = name.lastIndexOf("."); if (start > 0) name = name.substring(start + 1, name.length()); return name; } else if (obj instanceof Class) { if (!simple) { return ((Class) obj).getName(); } return ((Class) obj).getName(); } else { if (!simple) { return obj.getClass().getSimpleName(); } return obj.getClass().getSimpleName(); } } public Object intercept(Invocation invocation) throws Throwable { if (!init) { init(); } boolean intercept = false; Object[] obj = invocation.getArgs(); Object msObj = obj[0]; if (msObj instanceof MappedStatement) { intercept = commondSqlIdSet.contains(((MappedStatement) msObj) .getId()); } if (intercept) {//dynamic String sqlId = ((MappedStatement) msObj).getId(); if (MapperResolver.SELECT_BY_CRITERIA.equals(sqlId)) { processDynamicResultMapIntercept(invocation, false); } else if (MapperResolver.SELECT_BY_PRIMARYKEY.equals(sqlId)) { processDynamicResultMapIntercept(invocation, true); } else {//static if (MapperResolver.DELETE_BY_PRIMARYKEY.equals(sqlId)) { processIntercept(invocation, true, APPENDTYPE.NONE); } else if (MapperResolver.UPDATE_BY_PRIMARYKEY.equals(sqlId)) { processIntercept(invocation, true, APPENDTYPE.UPDATE); } else if (MapperResolver.UPDATE_BY_CRITERIA.equals(sqlId)) { processIntercept(invocation, false, APPENDTYPE.UPDATE); } else if (MapperResolver.INSERT.equals(sqlId)) { processIntercept(invocation, false, APPENDTYPE.INSERT); } else { processIntercept(invocation, false, APPENDTYPE.NONE); } } } return invocation.proceed(); } public Object plugin(Object o) { return Plugin.wrap(o, this); } public void setProperties(Properties properties) { } private enum APPENDTYPE { UPDATE, INSERT, NONE; } }
43.432099
128
0.554576
f0cefae1e78c63e3c0dc2f1ffa72c39ec77ec765
872
package org.ovirt.engine.core.common.validation; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.ovirt.engine.core.common.action.VmManagementParametersBase; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.validation.annotation.HostedEngineUpdate; public class HostedEngineUpdateValidator implements ConstraintValidator<HostedEngineUpdate, VmManagementParametersBase> { @Override public void initialize(HostedEngineUpdate constraintAnnotation) { } @Override public boolean isValid(VmManagementParametersBase value, ConstraintValidatorContext context) { return !value.getVm().isHostedEngine() || Config.<Boolean> getValue(ConfigValues.AllowEditingHostedEngine); } }
39.636364
121
0.807339
aa0405cc71664cd04a064f5a9a1bc7c0617f64cb
11,300
package io.github.lizhangqu.cronetsample; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.util.Log; import org.chromium.net.BuildConfig; import org.chromium.net.CronetEngine; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.math.BigInteger; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest; import java.util.concurrent.Executor; import java.util.concurrent.Executors; /** * native loader extension * * @author lizhangqu * @version V1.0 * @since 2019-04-29 09:40 */ public class ChromiumLibraryLoader extends CronetEngine.Builder.LibraryLoader { private static final String TAG = "ChromiumLibraryLoader"; private Context context; public ChromiumLibraryLoader(Context context) { this.context = context.getApplicationContext(); } @SuppressLint("UnsafeDynamicallyLoadedCode") @Override public void loadLibrary(String libName) { Log.w(TAG, "libName:" + libName); long start = System.currentTimeMillis(); try { //非cronet的so调用系统方法加载 if (!libName.contains("cronet")) { System.loadLibrary(libName); return; } //以下逻辑为cronet加载,优先加载本地,否则从远程加载 //首先调用系统行为进行加载 System.loadLibrary(libName); Log.w(TAG, "load from system"); } catch (Throwable e) { //如果找不到,则从远程下载 File dir = new File(context.getFilesDir(), "so_chromium"); String mappedLibraryName = System.mapLibraryName(libName); final File destSuccessFile = new File(dir, mappedLibraryName); File downloadFile = new File(new File(context.getCacheDir(), "so_chromium_download"), mappedLibraryName); //删除历史文件 deleteHistoryFile(dir, destSuccessFile); String md5 = null; String url = null; try { JSONObject jsonObject = new JSONObject(BuildConfig.REMOTE_JSON); String abi = getABI(context, getCurrentInstructionSetString()); Log.w(TAG, "abi:" + abi); JSONObject armeabiV7aJSON = jsonObject.getJSONObject(abi); md5 = armeabiV7aJSON.optString("md5"); url = armeabiV7aJSON.optString("url"); Log.w(TAG, "md5:" + md5); Log.w(TAG, "url:" + url); } catch (Exception e1) { e1.printStackTrace(); } if (md5 == null || md5.length() == 0 || url == null || url.length() == 0) { //如果md5或下载的url为空,则调用系统行为进行加载 System.loadLibrary(libName); return; } if (!destSuccessFile.exists() || !destSuccessFile.isFile()) { //noinspection ResultOfMethodCallIgnored destSuccessFile.delete(); download(url, md5, downloadFile, destSuccessFile); //如果文件不存在或不是文件,则调用系统行为进行加载 System.loadLibrary(libName); return; } if (destSuccessFile.exists()) { //如果文件存在,则校验md5值 String fileMD5 = getFileMD5(destSuccessFile); if (fileMD5 != null && fileMD5.equalsIgnoreCase(md5)) { //md5值一样,则加载 System.load(destSuccessFile.getAbsolutePath()); Log.w(TAG, "load from:" + destSuccessFile); return; } //md5不一样则删除 //noinspection ResultOfMethodCallIgnored destSuccessFile.delete(); } Log.w(TAG, "删除历史文件"); //删除历史文件 deleteHistoryFile(dir, destSuccessFile); //不存在则下载 download(url, md5, downloadFile, destSuccessFile); //使用系统加载方法 System.loadLibrary(libName); } finally { Log.w(TAG, "time:" + (System.currentTimeMillis() - start)); } } /** * 获得abi,可覆写 */ protected String getABI(Context context, String nowABI) { return nowABI; } private String getCurrentInstructionSetString() { if (Build.VERSION.SDK_INT < 21) { return "armeabi-v7a"; } try { Class<?> clazz = Class.forName("dalvik.system.VMRuntime"); Method currentGet = clazz.getDeclaredMethod("getCurrentInstructionSet"); String invoke = (String) currentGet.invoke(null); if ("arm".equals(invoke)) { return "armeabi-v7a"; } else if ("arm64".equals(invoke)) { return "arm64-v8a"; } else if ("x86".equals(invoke)) { return "x86"; } else if ("x86_64".equals(invoke)) { return "x86_64"; } else if ("mips".equals(invoke)) { return "mips"; } else if ("mips64".equals(invoke)) { return "mips64"; } else if ("none".equals(invoke)) { return "armeabi-v7a"; } } catch (Throwable e) { e.printStackTrace(); } return "armeabi-v7a"; } /** * 删除历史文件 */ private static void deleteHistoryFile(File dir, File currentFile) { File[] files = dir.listFiles(); if (files != null && files.length > 0) { for (File f : files) { if (f.exists() && (currentFile == null || !f.getAbsolutePath().equals(currentFile.getAbsolutePath()))) { boolean delete = f.delete(); Log.w(TAG, "delete file: " + f + " result: " + delete); if (!delete) { f.deleteOnExit(); } } } } } /** * 下载文件 */ private boolean downloadFileIfNotExist(String url, File destFile) { InputStream inputStream = null; OutputStream outputStream = null; try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); inputStream = connection.getInputStream(); if (destFile.exists()) { return true; } destFile.getParentFile().mkdirs(); destFile.createNewFile(); outputStream = new FileOutputStream(destFile); byte[] buffer = new byte[32768]; int read; while ((read = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, read); outputStream.flush(); } return true; } catch (Throwable e) { e.printStackTrace(); if (destFile.exists() && !destFile.delete()) { destFile.deleteOnExit(); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } static boolean download = false; Executor executor = Executors.newSingleThreadExecutor(); /** * 下载并拷贝文件 */ private synchronized void download(final String url, final String md5, final File downloadTempFile, final File destSuccessFile) { if (download) { return; } download = true; executor.execute(new Runnable() { @Override public void run() { boolean result = downloadFileIfNotExist(url, downloadTempFile); Log.w(TAG, "download result:" + result); //文件md5再次校验 String fileMD5 = getFileMD5(downloadTempFile); if (md5 != null && !md5.equalsIgnoreCase(fileMD5)) { boolean delete = downloadTempFile.delete(); if (!delete) { downloadTempFile.deleteOnExit(); } download = false; return; } Log.w(TAG, "download success, copy to " + destSuccessFile); //下载成功拷贝文件 copyFile(downloadTempFile, destSuccessFile); File parentFile = downloadTempFile.getParentFile(); deleteHistoryFile(parentFile, null); } }); } /** * 拷贝文件 */ private boolean copyFile(File source, File dest) { if (source == null || !source.exists() || !source.isFile() || dest == null) { return false; } if (source.getAbsolutePath().equals(dest.getAbsolutePath())) { return true; } FileInputStream is = null; FileOutputStream os = null; File parent = dest.getParentFile(); if (parent != null && (!parent.exists())) { boolean mkdirs = parent.mkdirs(); if (!mkdirs) { mkdirs = parent.mkdirs(); } } try { is = new FileInputStream(source); os = new FileOutputStream(dest, false); byte[] buffer = new byte[1024 * 512]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } return true; } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } return false; } /** * 获得文件md5 */ private static String getFileMD5(File file) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[1024 * 1024]; int numRead = 0; while ((numRead = fileInputStream.read(buffer)) > 0) { md5.update(buffer, 0, numRead); } return String.format("%032x", new BigInteger(1, md5.digest())).toLowerCase(); } catch (Exception e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } return null; } }
33.13783
133
0.509735
892988690e49b249ea8cf5fdb7aa836af0ca7e22
316
package com.exasol.csv.functional_test.selector; public enum ClassName implements Selector { UPLOAD_BUTTON("ui-fileupload-upload"); private final String className; private ClassName(String className) { this.className = className; } @Override public String asString() { return this.className; } }
16.631579
48
0.75
f166a8c38d07ac0d8101c851fc74ad66278d55ac
1,926
package com.polydes.common.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Timer; import java.util.TimerTask; public class CollectionObserver { private static ArrayList<CollectionObserver> observers = new ArrayList<CollectionObserver>(); private static Timer observerPollTimer; private static TimerTask observerPollTask; private int cachedSize; private Collection<?> observed; private ArrayList<CollectionUpdateListener> listeners; public CollectionObserver(Collection<?> observed) { this.observed = observed; cachedSize = observed.size(); if(observers.size() == 0) initTimer(); observers.add(this); listeners = new ArrayList<CollectionUpdateListener>(); } //TODO: This could fail if an equals number of additions and removals happened within one second. public void checkList() { if(observed.size() != cachedSize) { cachedSize = observed.size(); listUpdated(); } } public void addListener(CollectionUpdateListener l) { listeners.add(l); } public void removeListener(CollectionUpdateListener l) { listeners.remove(l); } public boolean hasNoListeners() { return listeners.isEmpty(); } public void cancel() { listeners.clear(); cachedSize = 0; observed = null; observers.remove(this); if(observers.size() == 0) cancelTimer(); } public void listUpdated() { for(CollectionUpdateListener listener : listeners) listener.listUpdated(); } private static void initTimer() { observerPollTask = new TimerTask() { @Override public void run() { for(CollectionObserver observer : observers) observer.checkList(); } }; observerPollTimer = new Timer(); observerPollTimer.schedule(observerPollTask, 1000, 1000); } private static void cancelTimer() { observerPollTimer.cancel(); observerPollTask.cancel(); observerPollTimer = null; observerPollTask = null; } }
20.934783
98
0.724818
dff9e3a297ee633d5a2daea9f06c74b4173cfe3a
1,342
package appointmentscheduler.service.business; import appointmentscheduler.entity.business.Business; import appointmentscheduler.repository.BusinessRepository; import appointmentscheduler.service.file.FileStorageService; import org.junit.*; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.mock.web.MockMultipartFile; import java.io.IOException; import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class BusinessServiceTest { @Mock private BusinessRepository businessRepository; @Mock private Business business; private BusinessService businessService; @Before public void setup() { businessService = new BusinessService( businessRepository); when(businessRepository.save(business)).thenReturn(business); when(business.getId()).thenReturn((long) 1); } @Test public void testAdd() throws IOException { long id = businessService.add(business); verify(businessRepository).save(business); verify(business).getId(); Assert.assertEquals(id,business.getId() ); } }
26.84
69
0.76006
85efb6374f5a5c7991b5262b071229da36d0f58e
1,531
/** * NOTE: This class is auto generated by the swagger code generator program (2.3.1). * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ package com.adidas.sub.event.api; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.adidas.sub.event.model.Event; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Authorization; @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-12-09T19:37:13.369Z") @Api(value = "EventController", description = "the EventController API") public interface EventControllerApi { @ApiOperation(value = "Recovery all event", nickname = "findAllEvents", notes = "", response = Event.class, authorizations = { @Authorization(value = "basicAuth") }, tags={ "event-controller", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = Event.class), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Not Found") }) @RequestMapping(value = "/events", produces = "*/*", consumes = "", method = RequestMethod.GET) ResponseEntity<Event> findAllEvents(); }
39.25641
130
0.714566
9d32d22b7b24227373fc9c75196333fcb30ad0ff
261
package com.yomahub.fastdownload.data.exporter; /** * Xls文件底部扩展接口 * @author Bryan Zhang */ import org.apache.poi.hssf.usermodel.HSSFSheet; public interface XlsBottomDeal { public Integer dealBottom(HSSFSheet sheet, Integer rowCnt) throws Exception; }
20.076923
80
0.770115
e22348f4924cb7bfdf8808f5150c0176aed4a592
8,743
/* * Copyright 2016 SRI International * * 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.sri.pal; import com.sri.ai.tasklearning.lapdog.LapdogConfiguration; import com.sri.pal.common.SimpleTypeName; import com.sri.pal.util.PALBridgeTestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Try to fully mimic the usage patterns for the BAD AC project. Procedures can be learned with either the specific or * general actions. The general action calls out to a Lumen procedure which is preloaded; that procedure dispatches to * a specific action at execution time, based on static properties on the specific actions and corresponding values in * a constraints object. The constraints object is passed to the procedure. * * @see LumenPreload_FuncTest */ public class GeneralizedActions_FuncTest extends PALBridgeTestCase { private static final Logger log = LoggerFactory.getLogger(GeneralizedActions_FuncTest.class); private static final String NAMESPACE = "BAD_AC"; private static final String VERS = "2.0"; private static final String BAD_AC_DIR = "../doc/applications/badac"; private static ActionDef detectRunwayDef; private static ActionDef importMsiDef; private static DetectorScorer detectorScorer; @BeforeClass public static void setup() throws Exception { // Check our data dir. File badAcDir = new File(BAD_AC_DIR); if (!badAcDir.isDirectory()) { badAcDir = new File("../" + BAD_AC_DIR); if (!badAcDir.isDirectory()) { throw new RuntimeException("Can't find data dir at " + BAD_AC_DIR); } } File amFile = new File(badAcDir, "BAD_AC_AF.xml"); File preloadFile = new File(badAcDir, "detectorSelection.lumen"); // Generate name objects that refer to action definitions we care about. SimpleTypeName importMsiName = new SimpleTypeName("importMSI", VERS, NAMESPACE); SimpleTypeName detectRunwayName = new SimpleTypeName("detectRunway", VERS, NAMESPACE); SimpleTypeName detectRunwayAltName = new SimpleTypeName("detectRunwayAlt", VERS, NAMESPACE); SimpleTypeName detectorScoreName = new SimpleTypeName("detectorScore", VERS, NAMESPACE); // These actions are prerequisites for the Lumen preload script. They're all actions that might be called by // DETECT_ENTITY/0, or the detectorScore function itself. List<String> prereqs = new ArrayList<>(); prereqs.add(importMsiName.getFullName()); prereqs.add(detectRunwayName.getFullName()); prereqs.add(detectRunwayAltName.getFullName()); prereqs.add(detectorScoreName.getFullName()); // Tell Lumen to load the preload file, and that it depends on the prerequisites above. System.setProperty("PAL.lumen-preload-file", preloadFile.getCanonicalPath()); System.setProperty("PAL.lumen-preload-prerequisites", String.join(",", prereqs)); // Use the test harness to initialize the task learning system. A production application would use other calls. setup(amFile.toURI().toURL(), NAMESPACE); // Use the mock executor to handle these three actions. A production application would define its own callback // handler. actionModel.registerExecutor(importMsiName, callbackHandler); actionModel.registerExecutor(detectRunwayName, callbackHandler); actionModel.registerExecutor(detectRunwayAltName, callbackHandler); // This special callback handler decides how well an action fits the constraints. detectorScorer = new DetectorScorer(); actionModel.registerExecutor(detectorScoreName, detectorScorer); importMsiDef = (ActionDef) actionModel.getType(importMsiName); detectRunwayDef = (ActionDef) actionModel.getType(detectRunwayName); } @AfterClass public static void teardown() throws Exception { palBridge.shutdown(); } @Test public void generalProcedure() throws Exception { // These actions will be used as the demonstration, to learn a new procedure. The demonstration includes both // input and output parameters. List<ActionStreamEvent> actions = new ArrayList<>(); // Action 1 imports the MSI file. String imageName = "test_image.msi"; ActionInvocation action1 = importMsiDef.invoke(null, imageName); String imageId = "23"; action1.setValue("image", imageId); actions.add(action1); // Action 2 looks for runways in the image. String classifier = "Alpha"; ActionInvocation action2 = detectRunwayDef.invoke(null, imageId, classifier); List<String> roads = new ArrayList<>(); roads.add("road1"); roads.add("road2"); action2.setValue("roads", roads); actions.add(action2); // Set learn properties to request the general procedure be learned, not the specific one. Properties learnProps = new Properties(); learnProps.put("lapdog.idiom.learning", LapdogConfiguration.IdiomLearning.ABSTRACT.name()); learnProps.put("lapdog.idiom.group-single-actions", "true"); // Learn the procedure now. ProcedureDef proc = learningBridge.learn("general", learnProps, null, actions.toArray(new ActionStreamEvent[0])); log.info("Learned procedure: {}", proc.getSource()); // Ensure it learned the general procedure. Assert.assertTrue(proc.getSource().contains("DETECT_ENTITY/0"), proc.getSource()); // Execute the procedure we just learned. It should call our DetectorScorer to decide which detector action to // use. ProcedureInvocation invocation = proc.invoke(null); invocation.start(); invocation.waitUntilFinished(); // Was the procedure execution successful? Assert.assertEquals(invocation.getStatus(), ActionStreamEvent.Status.ENDED); // Make sure the detector scorer was actually called. Assert.assertTrue(detectorScorer.wasCalled()); } private static class DetectorScorer implements ActionExecutor { private boolean wasCalled = false; @Override public void cancel(ActionStreamEvent event) { // Can be ignored, since the action runs synchronously. } @Override public void continueStepping(ActionInvocation invocation, ActionInvocation.StepCommand command, List<Object> actionArgs) throws PALException { // Can be ignored, since we don't support stepped execution. } @Override public void executeStepped(ActionInvocation invocation) throws PALException { execute(invocation); } @Override public void execute(ActionInvocation invocation) throws PALException { log.info("{} was called", invocation); wasCalled = true; // Retrieve the parameters for this invocation. String falseAlarmStr = (String) invocation.getValue("falseAlarmRate"); String requiresMsiStr = (String) invocation.getValue("requiresMSIData"); String viewpointStr = (String) invocation.getValue("viewpoint"); String minSamplesStr = (String) invocation.getValue("minSamples"); // For this test, we only care about the false alarm rate. Double falseAlarm = Double.parseDouble(falseAlarmStr); double score = 1 / falseAlarm; // Set the output parameter. invocation.setValue("score", score); // Tell the system that this execution is complete. invocation.setStatus(ActionStreamEvent.Status.ENDED); } boolean wasCalled() { return wasCalled; } } }
42.033654
121
0.68043
37b5650b866f54e3cc011c6db44553333f54a786
649
package org.iutools.webservice.spell; import org.iutools.webservice.AssertServiceInputs; import org.iutools.webservice.ServiceInputs; import org.iutools.webservice.ServiceInputsTest; import org.junit.jupiter.api.Test; public class SpellInputsTest extends ServiceInputsTest { @Override protected ServiceInputs makeInputs() throws Exception { return new SpellInputs(); } @Override protected boolean shouldGenerateNullSummary() { return true; } @Test public void test__summarizeForLogging() throws Exception { ServiceInputs inputs = new SpellInputs("inukkksuk"); new AssertServiceInputs(inputs) .logSummaryIs(null); ; } }
23.178571
59
0.787365
7047a6f7cbeefe4579e2f53109bf373e68d2d1cd
1,211
/* * Copyright (c) 2016-2021, Inversoft Inc., All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package com.inversoft.rest; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Brian Pontarelli */ public class SimpleFormDataBodyHandler extends FormDataBodyHandler { public SimpleFormDataBodyHandler(Map<String, String> request) { super(convertMap(request)); } private static Map<String, List<String>> convertMap(Map<String, String> request) { Map<String, List<String>> map = new HashMap<>(); request.forEach((key, value) -> map.put(key, Collections.singletonList(value))); return map; } }
32.72973
84
0.73493
75c7e7eb0659ee7df0ea770b342ae33875aad0a7
6,799
/* * Copyright 2017-2019 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.data.jdbc.mapper; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import io.micronaut.core.convert.ConversionService; import io.micronaut.core.convert.exceptions.ConversionErrorException; import io.micronaut.core.reflect.ReflectionUtils; import io.micronaut.data.exceptions.DataAccessException; import io.micronaut.data.model.DataType; import io.micronaut.data.runtime.mapper.ResultReader; import java.math.BigDecimal; import java.sql.*; import java.util.Date; /** * A {@link ResultReader} for JDBC that uses the column name. * * @author graemerocher * @since 1.0.0 */ public final class ColumnNameResultSetReader implements ResultReader<ResultSet, String> { private final ConversionService<?> conversionService = ConversionService.SHARED; @Nullable @Override public Object readDynamic(@NonNull ResultSet resultSet, @NonNull String index, @NonNull DataType dataType) { Object val = ResultReader.super.readDynamic(resultSet, index, dataType); try { return resultSet.wasNull() ? null : val; } catch (SQLException e) { throw exceptionForColumn(index, e); } } @Override public boolean next(ResultSet resultSet) { try { return resultSet.next(); } catch (SQLException e) { throw new DataAccessException("Error calling next on SQL result set: " + e.getMessage(), e); } } @Override public <T> T convertRequired(Object value, Class<T> type) { Class wrapperType = ReflectionUtils.getWrapperType(type); if (wrapperType.isInstance(value)) { return (T) value; } return conversionService.convert( value, type ).orElseThrow(() -> new DataAccessException("Cannot convert type [" + value.getClass() + "] with value [" + value + "] to target type: " + type + ". Consider defining a TypeConverter bean to handle this case.") ); } @Override public Date readTimestamp(ResultSet resultSet, String index) { try { return resultSet.getTimestamp(index); } catch (SQLException e) { throw exceptionForColumn(index, e); } } @Override public long readLong(ResultSet resultSet, String name) { try { return resultSet.getLong(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public char readChar(ResultSet resultSet, String name) { try { return (char) resultSet.getInt(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public Date readDate(ResultSet resultSet, String name) { try { return resultSet.getDate(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Nullable @Override public String readString(ResultSet resultSet, String name) { try { return resultSet.getString(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public int readInt(ResultSet resultSet, String name) { try { return resultSet.getInt(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public boolean readBoolean(ResultSet resultSet, String name) { try { return resultSet.getBoolean(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public float readFloat(ResultSet resultSet, String name) { try { return resultSet.getFloat(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public byte readByte(ResultSet resultSet, String name) { try { return resultSet.getByte(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public short readShort(ResultSet resultSet, String name) { try { return resultSet.getShort(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public double readDouble(ResultSet resultSet, String name) { try { return resultSet.getDouble(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public BigDecimal readBigDecimal(ResultSet resultSet, String name) { try { return resultSet.getBigDecimal(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public byte[] readBytes(ResultSet resultSet, String name) { try { return resultSet.getBytes(name); } catch (SQLException e) { throw exceptionForColumn(name, e); } } @Override public <T> T getRequiredValue(ResultSet resultSet, String name, Class<T> type) throws DataAccessException { try { Object o; if (Blob.class.isAssignableFrom(type)) { o = resultSet.getBlob(name); } else if (Clob.class.isAssignableFrom(type)) { o = resultSet.getClob(name); } else { o = resultSet.getObject(name); } if (o == null) { return null; } if (type.isInstance(o)) { //noinspection unchecked return (T) o; } else { return convertRequired(o, type); } } catch (SQLException | ConversionErrorException e) { throw exceptionForColumn(name, e); } } private DataAccessException exceptionForColumn(String name, Exception e) { return new DataAccessException("Error reading object for name [" + name + "] from result set: " + e.getMessage(), e); } }
30.488789
206
0.607001
0ec349fdb623badcda04d5563799472feeab25a6
96
package de.odysseus.el.test; public interface TestInterface { public int fourtyTwo(); }
16
33
0.71875
48d68b2948f561c3d4d24aca078a911553b6a56c
337
package com.garland.helpcenter.datastructure.tree; import java.io.Serializable; /** * Created by lemon on 11/3/2017. */ public class Color implements Serializable { private static final long serialVersionUID="Color".hashCode(); public static final boolean RED=false; public static final boolean BLACK=true; }
25.923077
67
0.727003
c50414dd8928986766f0df6e62aa4e639bd09145
6,017
package uk.ac.lincoln.games.nlfs.logic; import java.util.ArrayList; import java.util.Collections; import uk.ac.lincoln.games.nlfs.Assets; import uk.ac.lincoln.games.nlfs.logic.Footballer.Position; import uk.ac.lincoln.games.nlfs.logic.MatchEvent.MatchEventType; public class MatchResult { public transient Match match; public ArrayList<Goal> home_goals, away_goals; public transient ArrayList<MatchEvent> match_events; public int first_half_length; public int second_half_length; public int gate; public MatchResult(Match match,int h_goals,int a_goals){ this.match = match; this.home_goals = new ArrayList<Goal>(); this.away_goals = new ArrayList<Goal>(); this.match_events = new ArrayList<MatchEvent>(); first_half_length = 46+ GameState.rand2.nextInt(7); second_half_length = 46+ GameState.rand2.nextInt(7); //calculate scorers for(int i=0;i<h_goals;i++){ this.home_goals.add(new Goal(pickScorer(match.home),(GameState.rand2.nextInt(first_half_length+second_half_length)))); } for(int i=0;i<a_goals;i++){ this.away_goals.add(new Goal(pickScorer(match.away),(GameState.rand2.nextInt(first_half_length+second_half_length)))); } //calculate events for(int i=0;i<10+GameState.rand2.nextInt(10);i++) {//10-20 events per match match_events.add(new MatchEvent(match,GameState.rand2.nextInt(first_half_length+second_half_length))); } /* TODO: Make players able to get 2nd yellow card or red card At the moment the next lines prevent that from happening. Obviously this would be good, but sendings-off create headaches for us: * Currently events are given random times. we would need to sim them minute by minute, to make sure an event doesn't happen to a player who is off * Note this also makes substitutions tricky. * What happens in future matches? tracking bans between matches will require significant rewrite. What is the benefit? Flavour? */ //remove all but first yellow card for each player ArrayList<Footballer> yellows = new ArrayList<Footballer>(); ArrayList<MatchEvent> remove = new ArrayList<MatchEvent>(); for(MatchEvent me: match_events){ if(me.type==MatchEventType.YELLOWCARD) if(yellows.contains(me.player)) remove.add(me); else yellows.add(me.player); } for(MatchEvent me:remove) match_events.remove(me); Collections.sort(match_events); //set gate for this match. more fans come if the team is doing well gate = 70 + GameState.rand2.nextInt(190) + ((League.LEAGUE_SIZE - GameState.league.getTeamPosition(match.home))*8)+((League.LEAGUE_SIZE - GameState.league.getTeamPosition(match.away))*2); } public MatchResult(){} public Team getWinner() { if(this.home_goals.size()==this.away_goals.size()) return null; if(this.home_goals.size()>this.away_goals.size()) return match.home; else return match.away; } /** * Returns a random scoring player * @param team * @return */ private Footballer pickScorer(Team team){ //60% of goals are scored by strikers, 30% by midfielders and 9% by DF and 1% by GK! float s = GameState.rand2.nextFloat(); if(s<0.6) return team.getFootballerAtPosition(Position.ST); if(s<0.9) return team.getFootballerAtPosition(Position.MF); if(s<0.99) return team.getFootballerAtPosition(Position.DF); else return team.getFootballerAtPosition(Position.GK); } /** * Returns a nicely filled news story about this match, from the perspective of the supplied team * @param team * @return */ public String getDescription(Team team) { if(team!=match.home&&team!=match.away) return getDescription(match.home);//fail silently and return the description for the home team String scoreline; Team opposition; if(team==match.home) { scoreline = String.valueOf(home_goals.size())+"-"+String.valueOf(away_goals.size()); opposition = match.away; } else { scoreline = String.valueOf(away_goals.size())+"-"+String.valueOf(home_goals.size()); opposition = match.home; } ArrayList<String> news_items = Assets.news_summaries.get(scoreline); String news_item = news_items.get(GameState.rand2.nextInt(news_items.size()));//random description // Tokens: yourteam, opposition, goalkeeper, defender, midfielder, attacker, stadium news_item = news_item.replace("{yourteam}",team.name); news_item = news_item.replace("{opposition}",opposition.name); news_item = news_item.replace("{goalkeeper}",team.getFootballerAtPosition(Position.GK).getName()); news_item = news_item.replace("{defender}",team.getFootballerAtPosition(Position.DF).getName()); news_item = news_item.replace("{attacker}",team.getFootballerAtPosition(Position.ST).getName()); news_item = news_item.replace("{midfielder}",team.getFootballerAtPosition(Position.MF).getName()); news_item = news_item.replace("{stadium}",match.home.stadium); return news_item; } public String toString() { return match.home.name +" "+String.valueOf(home_goals.size())+":"+String.valueOf(away_goals.size())+" "+match.away.name; } /** * Returns the letter result for this team in this match W/L/D * @param t * @return */ public String resultForTeam(Team t){ if(!(t.equals(match.home)||t.equals(match. away))) return null;//team not in this match if(getWinner()==null) return("D"); if(getWinner()==t) return ("W"); return ("L"); } /** * Used for simplifying GF/GA calculations * @param t * @return */ public int goalsFor(Team t) { if(t==match.home) return home_goals.size(); return away_goals.size(); } public int goalsAgainst(Team t) { if(t==match.home) return away_goals.size(); return home_goals.size(); } //Reload circular pointers after deserialisation public void reinit(Match m) { match = m; for(Goal g: home_goals) { g.reinit(match.home); } for(Goal g: away_goals) { g.reinit(match.away); } } }
39.071429
189
0.706166
0a41c9731689e7e2613df58eb434995a0bbfcb96
13,752
package com.raffler.app.utils; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.media.ThumbnailUtils; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.ImageView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import com.raffler.app.R; import com.raffler.app.alertView.AlertView; import com.raffler.app.classes.AppConsts; import com.raffler.app.classes.AppManager; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; public class Util { public static DisplayImageOptions displayImageOptions_original = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.img_logo) .showImageForEmptyUri(R.drawable.img_logo) .showImageOnFail(R.drawable.img_logo) .cacheInMemory(true) .cacheOnDisk(true) .considerExifParams(true) .build(); public static DisplayImageOptions displayImageOptions_circluar = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_profile_person) .showImageForEmptyUri(R.drawable.ic_profile_person) .showImageOnFail(R.drawable.ic_profile_person) .cacheInMemory(true) .cacheOnDisk(true) .considerExifParams(true) .displayer(new CircleBitmapDisplayer(0xccff8000, 1)) .build(); public static class AnimateFirstDisplayListener extends SimpleImageLoadingListener { static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>()); @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); displayedImages.add(imageUri); } } } } public static void setProfileImage(String url, ImageView imgView){ if (url != null) { ImageLoader.getInstance().displayImage(url, imgView, Util.displayImageOptions_circluar, new Util.AnimateFirstDisplayListener()); } } public static void setProfileImage(String url, ImageView imgView, ImageLoadingListener listener) { if (url != null) { if (ImageLoader.getInstance() != null) { ImageLoader.getInstance().displayImage(url, imgView, Util.displayImageOptions_circluar, listener); } } } public static void setURLImage(String url, ImageView imgView){ if (url != null) { ImageLoader.getInstance().displayImage(url, imgView, Util.displayImageOptions_original, new Util.AnimateFirstDisplayListener()); } } public static void setURLImage(String url, ImageView imgView, ImageLoadingListener listener) { if (url != null) { if (ImageLoader.getInstance() != null) { ImageLoader.getInstance().displayImage(url, imgView, Util.displayImageOptions_original, listener); } } } public static void requestPermission(Activity activity, String permission) { if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, new String[]{permission}, 0); } } public static String formatSeconds(int seconds) { return getTwoDecimalsValue(seconds / 3600) + ":" + getTwoDecimalsValue(seconds / 60) + ":" + getTwoDecimalsValue(seconds % 60); } public static String getMessageTime(Date time) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault()); return simpleDateFormat.format(time); } public static String getUserTime(long datetime) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(datetime); return getUserTime(calendar); } public static String getUserTime(Calendar calendar) { return getUserTime(calendar.getTime()); } public static String getUserTime(Date time) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault()); return simpleDateFormat.format(time); } public static String getUserFriendlyDate(Context context, long millis) { millis = getMillisForDateOnly(millis); long currentMillis = getMillisForDateOnly(System.currentTimeMillis()); long diff = currentMillis - millis; int days = (int) Math.floor(diff / (1000 * 60 * 60 * 24)); if (days == 1) return context.getResources().getString(R.string.yesterday); else { return Util.getSimpleDateString(millis); } } public static String getUserFriendlyDateForChat(Context context, long millis) { millis = getMillisForDateOnly(millis); long currentMillis = getMillisForDateOnly(System.currentTimeMillis()); long diff = currentMillis - millis; int days = (int) Math.floor(diff / (1000 * 60 * 60 * 24)); if (days == 0) return context.getResources().getString(R.string.today); else if (days == 1) return context.getResources().getString(R.string.yesterday); else { return Util.getChatDateString(millis); } } public static String getSimpleDateString(long millis) { Calendar date = Calendar.getInstance(); date.setTimeInMillis(millis); return getSimpleDateString(date.getTime()); } public static String getSimpleDateString(Date date) { SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault()); return format.format(date); } public static String getChatDateString(long millis) { Calendar date = Calendar.getInstance(); date.setTimeInMillis(millis); return getChatDateString(date.getTime()); } public static String getChatDateString(Date date) { SimpleDateFormat format = new SimpleDateFormat("MMMM dd, yyyy", Locale.getDefault()); return format.format(date); } private static long getMillisForDateOnly(long millis) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(millis); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTimeInMillis(); } public static String getDateString(long millis) { Calendar date = Calendar.getInstance(); date.setTimeInMillis(millis); return getDateString(date.getTime()); } public static String getDateString(Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.getDefault()); return format.format(date); } public static String generateChatKeyFrom(String publisher, String subscriber) { return (publisher.compareTo(subscriber) < 0 ? publisher + "_" + subscriber : subscriber + "_" + publisher); } private static String getTwoDecimalsValue(int value) { if (value >= 0 && value <= 9) { return "0" + value; } else { return value + ""; } } public static String getUnicodeString(String myString) { String text = ""; try { byte[] utf8Bytes = myString.getBytes("UTF8"); text = new String(utf8Bytes, "UTF8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return text; } public static String escapeUnicodeText(String input) { StringBuilder b = new StringBuilder(input.length()); java.util.Formatter f = new java.util.Formatter(b); for (char c : input.toCharArray()) { if (c < 128) { b.append(c); } else { f.format("\\u%04x", (int) c); } } return b.toString(); } /** * get values from Hash map data */ public static Date getDateFromData(String key, Map<String, Object> data){ Date date = new Date(); String strDate = null; long timeSince1970 = System.currentTimeMillis(); try{ timeSince1970 = (long) data.get(key); date = new Date(timeSince1970); }catch (Exception e){ e.printStackTrace(); } if (date == null) date = new Date(); return date; } public static int getIntFromData(String key, Map<String, Object> data){ Integer value = 0; try{ String strValue = data.get(key).toString(); value = Integer.parseInt(strValue); }catch (Exception e){ e.printStackTrace(); } if(value == null) value = 0; return value; } public static long getLongFromData(String key, Map<String, Object> data){ long value = 0; try{ value = (long)data.get(key); }catch (Exception e){ e.printStackTrace(); } return value; } public static String getStringFromData(String key, Map<String, Object> data){ String value = "?"; try{ value = (String) data.get(key); }catch (Exception e){ e.printStackTrace(); } return value; } public static boolean getBooleanFromData(String key, Map<String, Object> data){ boolean value = false; try{ value = (boolean) data.get(key); }catch (Exception e){ e.printStackTrace(); } return value; } public static Map<String, Object> getMapDataFromData(String key, Map<String, Object> data){ Map<String, Object> value = new HashMap<>(); try{ value = (Map<String, Object>) data.get(key); }catch (Exception e){ e.printStackTrace(); } if (value == null) value = new HashMap<>(); return value; } public static String[] getUserIdsFrom(String chatId) { String[] userIds = chatId.split("_"); return userIds; } /** * Handler */ private static final Handler HANDLER = new Handler(); public static void wait(int millis, Runnable callback){ HANDLER.postDelayed(callback, millis); } private static String PREF_HIGH_QUALITY = "pref_high_quality"; public static void setPrefHighQuality(Context context, boolean isEnabled) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(PREF_HIGH_QUALITY, isEnabled); editor.apply(); } public static boolean getPrefHighQuality(Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); return preferences.getBoolean(PREF_HIGH_QUALITY, false); } public static void showAlert (String title, String message, Context context) { AlertView alertView = new AlertView(title, message, context.getString(R.string.alert_button_okay), null, null, context, AlertView.Style.Alert, null); alertView.show(); } public static Bitmap getCircleBitmap(Bitmap bm) { if (bm == null) return null; int sice = Math.min((bm.getWidth()), (bm.getHeight())); Bitmap bitmap = ThumbnailUtils.extractThumbnail(bm, sice, sice); Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xffff0000; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); paint.setDither(true); paint.setFilterBitmap(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawOval(rectF, paint); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth((float) 4); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } }
33.705882
157
0.648706
0a78624cfc6cdbc8248be16d90137c64ea853e20
2,511
package com.ncoding.backend.user.service; import com.ncoding.backend.user.controller.request.UserRequest; import com.ncoding.backend.user.domain.User; import com.ncoding.backend.user.persistence.UserRepository; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import java.util.Date; @Log4j2 @Service @Primary public class UserServiceImpl implements UserService<User, UserRequest> { private final UserRepository userRepository; private final BCryptPasswordEncoder encoder; @Autowired public UserServiceImpl(UserRepository userRepository) { super(); this.userRepository = userRepository; this.encoder = new BCryptPasswordEncoder(); } @Override public Page<User> findAll(Pageable pageable) { return userRepository.findAll(pageable); } @Override public User registerNewUser(UserRequest userRequest) { if (userRepository.existsByEmail(userRequest.getEmail())) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST); } return userRepository.save(createUserFromUserRequest(userRequest)); } private User createUserFromUserRequest(UserRequest userRequest) { return User.builder() .email(userRequest.getEmail()) .password(encoder.encode(userRequest.getPassword())) .build(); } @Override public User doLogin(UserRequest userRequest) { User user = userRepository.findByEmail(userRequest.getEmail()) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); if (!isUserPasswordMatch(user, userRequest.getPassword())) { log.error("The given password does not match."); throw new ResponseStatusException(HttpStatus.BAD_REQUEST); } user.setLastLogin(new Date()); log.info(String.format("User [%s] is now logged", user)); return userRepository.save(user); } private boolean isUserPasswordMatch(User user, String password) { return encoder.matches(password, user.getPassword()); } }
35.366197
86
0.725209
7da44d188ee7077f8f252cc09b07c5c10a0dbf22
15,597
package vektra.GUI; import java.util.Collections; import java.util.Comparator; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.BorderPane; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Callback; import vektra.BugItem; import vektra.Priority; import vektra.Status; import vektra.Vektra; import vektra.extrawindows.FilterWindow; import vektra.resources.FilterConfiguration; public class BugListGUI { final static Background SetFixedStatusBackground = new Background(new BackgroundFill(Color.GREEN, new CornerRadii(0), new Insets(5))); final static Background UpdatedColor = new Background(new BackgroundFill(Color.valueOf("rgb(57, 71, 61)"), new CornerRadii(0), new Insets(5))); private static boolean autoFilterBugs = true; private static Label bugsFilteredLabel; private static Label bugCountLabel; /** * Creates a new TableView to contain our list of bugs * @param primaryStage * @param vektra * @return */ public static Pane create(Stage primaryStage, Vektra vektra) { BorderPane pane = new BorderPane(); TableView<BugItem> bugs = new TableView<BugItem>(); bugs.setRowFactory(new Callback<TableView<BugItem>, TableRow<BugItem>>() { @Override public TableRow<BugItem> call(TableView<BugItem> tableView) { final TableRow<BugItem> row = new TableRow<BugItem>() { @Override protected void updateItem(BugItem person, boolean empty){ super.updateItem(person, empty); if( !empty ){ if (person.hasBeenUpdated) { if (! getStyleClass().contains("updatedRow")) { getStyleClass().add("updatedRow"); } } else { getStyleClass().removeAll(Collections.singleton("updatedRow")); } } } }; return row; } }); // Listen for the selected item to change bugs.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> { if (newSelection != null) { BugItem item = bugs.getSelectionModel().getSelectedItem(); if(item.hasBeenUpdated ){ item.hasBeenUpdated = false; } // Change the GUI vektra.selectBug(item); } }); bugs.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); bugs.setMaxWidth(300); bugs.getStylesheets().add("css/buglist.css"); vektra.setBugs(bugs); pane.setCenter(bugs); // // FILTER OPTIONS // GridPane filterOptionsPane = new GridPane(); filterOptionsPane.setBackground(UpdatedColor); filterOptionsPane.setPadding(new Insets(5)); filterOptionsPane.setAlignment(Pos.TOP_LEFT); Label filterLabel = new Label("Filter"); filterLabel.getStylesheets().add("css/buglist.css"); filterLabel.getStyleClass().add("filter"); filterOptionsPane.addRow(0, filterLabel); HBox filterCountPane = new HBox(); // Bug Filter Count bugsFilteredLabel = new Label("?"); bugsFilteredLabel.setPadding(new Insets(0,0,0,10)); bugsFilteredLabel.getStylesheets().add("css/buglist.css"); bugsFilteredLabel.getStyleClass().add("filter"); Label label = new Label("/"); label.getStylesheets().add("css/buglist.css"); label.getStyleClass().add("filter"); // Bug Count bugCountLabel = new Label("?"); bugCountLabel.getStylesheets().add("css/buglist.css"); bugCountLabel.getStyleClass().add("filter"); filterCountPane.getChildren().addAll(bugsFilteredLabel,label,bugCountLabel); filterOptionsPane.addColumn(1, filterCountPane); HBox filterOptions = new HBox(); filterOptions.setAlignment(Pos.CENTER); filterOptions.setSpacing(5); filterOptions.setPadding(new Insets(5)); GridPane.setColumnSpan(filterOptions, 2); ImageView autoFilterIcon = new ImageView(); autoFilterIcon.setImage(new Image("auto.png",30,30,false,false)); CheckBox autoFilter = new CheckBox(); autoFilter.setTooltip(new Tooltip("Auto filter Bug list")); autoFilter.setSelected(autoFilterBugs); autoFilter.selectedProperty().addListener((a,o,n)->{autoFilterBugs = n;}); autoFilter.setGraphic(autoFilterIcon); Button filterButton = new Button("FILTER"); filterButton.setOnAction((a)->filterBugs(bugs.getItems(), bugs, vektra)); filterButton.setTooltip(new Tooltip("Filter the currently listed Bugs")); Button editFilterButton = new Button(); editFilterButton.setGraphic(new ImageView(new Image("edit.png",15,15,false,false))); editFilterButton.setOnAction((a)->FilterWindow.show(vektra)); editFilterButton.setTooltip(new Tooltip("Edit the Filter Settings")); filterOptions.getChildren().addAll(autoFilterIcon, autoFilter,filterButton,editFilterButton); filterOptionsPane.addRow(1, filterOptions); setupColumns(null, bugs, vektra); pane.setBottom(filterOptionsPane); GridPane.setValignment(filterOptions, VPos.BOTTOM); return pane; } public static void filterBugs(ObservableList<BugItem> items, TableView<BugItem> bugs, Vektra vektra) { autoFilterBugs = true; setupColumns(items, bugs, vektra); autoFilterBugs = false; } /** * Resets up the columns when the information is updated * @param importedData * @param bugs * @param vektra */ public static void setupColumns(ObservableList<BugItem> importedData, TableView<BugItem> bugs, Vektra vektra) { bugCountLabel.setText(importedData == null ? "?" : String.valueOf(importedData.size())); // Create a new list if we don't have one ObservableList<BugItem> filtered = importedData == null ? FXCollections.observableArrayList() : importedData; if( autoFilterBugs ){ filtered = FilterConfiguration.filter(filtered); bugsFilteredLabel.setText(String.valueOf(filtered.size())); } else{ bugsFilteredLabel.setText(importedData == null ? "?" : String.valueOf(importedData.size())); } bugs.setItems(filtered); // Bottom Left ( BUG LIST ) // if( bugs.getColumns().isEmpty() ){ createColumns(bugs, vektra); // } bugs.sort(); } private static void createColumns(TableView<BugItem> bugs, Vektra vektra){ TableColumn<BugItem, Priority> priorityColumn = new TableColumn<BugItem, Priority>("P"); priorityColumn.setMinWidth(20); priorityColumn.setMaxWidth(20); priorityColumn.setComparator(new PriorityComparator()); priorityColumn.setCellValueFactory(new PropertyValueFactory<BugItem, Priority>("priority")); priorityColumn.setCellFactory(new Callback<TableColumn<BugItem, Priority>, TableCell<BugItem, Priority>>() { public TableCell<BugItem, Priority> call(TableColumn<BugItem, Priority> param) { return new TableCell<BugItem, Priority>() { @Override public void updateItem(Priority priority, boolean empty) { super.updateItem(priority, empty); if (!isEmpty()) { int index = getIndex(); BugItem bug = bugs.getItems().get(index); this.getStylesheets().add("css/buglist.css"); // this.addEventFilter(MouseEvent.MOUSE_CLICKED, (a)->{ refreshRow(bugs, index, bug); vektra.selectBug(bug); }); if( bug.getStatus() == Status.FIXED ){ setBackground(SetFixedStatusBackground); } else{ setBackground(new Background(new BackgroundFill(priority.getColor(), new CornerRadii(0), new Insets(5)))); } } } }; } }); if( !bugs.getColumns().isEmpty() ){ priorityColumn.setSortType(bugs.getColumns().get(0).getSortType()); } // Bottom Left ( BUG LIST ) TableColumn<BugItem, Integer> idColumn = new TableColumn<BugItem, Integer>("ID"); idColumn.setMinWidth(40); idColumn.setMaxWidth(40); idColumn.setCellValueFactory(new PropertyValueFactory<BugItem, Integer>("ID")); idColumn.setCellFactory(new Callback<TableColumn<BugItem, Integer>, TableCell<BugItem, Integer>>() { public TableCell<BugItem, Integer> call(TableColumn<BugItem, Integer> param) { return new TableCell<BugItem, Integer>() { @Override public void updateItem(Integer item, boolean empty) { super.updateItem(item, empty); if (!isEmpty()) { int index = getIndex(); BugItem bug = bugs.getItems().get(index); this.getStylesheets().add("css/buglist.css"); // this.addEventFilter(MouseEvent.MOUSE_CLICKED, (a)->{ refreshRow(bugs, index, bug); vektra.selectBug(bug); }); setText(String.valueOf(item)); } } }; } }); if( !bugs.getColumns().isEmpty() ){ idColumn.setSortType(bugs.getColumns().get(1).getSortType()); } TableColumn<BugItem, Status> statusColumn = new TableColumn<BugItem, Status>("STATUS"); statusColumn.setMinWidth(50); statusColumn.setMaxWidth(50); statusColumn.setComparator(new StatusComparator()); statusColumn.setCellValueFactory(new PropertyValueFactory<BugItem, Status>("status")); statusColumn.setCellFactory(new Callback<TableColumn<BugItem, Status>, TableCell<BugItem, Status>>() { public TableCell<BugItem, Status> call(TableColumn<BugItem, Status> param) { return new TableCell<BugItem, Status>() { @Override public void updateItem(Status item, boolean empty) { super.updateItem(item, empty); if (!isEmpty()) { int index = getIndex(); BugItem bug = bugs.getItems().get(index); this.getStylesheets().add("css/buglist.css"); // this.addEventFilter(MouseEvent.MOUSE_CLICKED, (a)->{ refreshRow(bugs, index, bug); vektra.selectBug(bug); }); setText(item.toString()); } } }; } }); if( !bugs.getColumns().isEmpty() ){ statusColumn.setSortType(bugs.getColumns().get(2).getSortType()); } TableColumn<BugItem, String> updateColumn = new TableColumn<BugItem, String>("UPDATED"); updateColumn.setCellValueFactory(new PropertyValueFactory<BugItem, String>("lastUpdate")); updateColumn.setCellFactory(new Callback<TableColumn<BugItem, String>, TableCell<BugItem, String>>() { public TableCell<BugItem, String> call(TableColumn<BugItem, String> param) { return new TableCell<BugItem, String>() { @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (!isEmpty()) { int index = getIndex(); BugItem bug = bugs.getItems().get(index); this.getStylesheets().add("css/buglist.css"); // this.addEventFilter(MouseEvent.MOUSE_CLICKED, (a)->{ refreshRow(bugs, index, bug); vektra.selectBug(bug); }); int[] date = splitDate(item); String displayDate = date[1] + "-" + date[2] + " " + date[3] + ":" + date[4] + ":" + date[5]; setText(displayDate); } } }; } }); if( !bugs.getColumns().isEmpty() ){ updateColumn.setSortType(bugs.getColumns().get(3).getSortType()); } @SuppressWarnings("rawtypes") TableColumn sorting = bugs.getSortOrder().isEmpty() ? null : bugs.getSortOrder().get(0); if( sorting == null ){ // Ignore } else if( sorting == bugs.getColumns().get(0) ){ bugs.getSortOrder().set(0, priorityColumn); } else if( sorting == bugs.getColumns().get(1) ){ bugs.getSortOrder().set(0, idColumn); } else if( sorting == bugs.getColumns().get(2) ){ bugs.getSortOrder().set(0, statusColumn); } else if( sorting == bugs.getColumns().get(2) ){ bugs.getSortOrder().set(0, updateColumn); } bugs.getColumns().clear(); bugs.getColumns().addAll(priorityColumn, idColumn, statusColumn,updateColumn); } /** * Divides a timestamp into an array of integers * Year * Month * Day * Hour * Minute * Second * @param item Timestamp from the database to split * @return Array containing the entire timestamp */ private static int[] splitDate(String item) { String[] date = item.split("\\s|[-/:]"); int[] numbered = new int[date.length]; numbered[0] = Integer.parseInt(date[0]); // year numbered[1] = Integer.parseInt(date[1]); // Month numbered[2] = Integer.parseInt(date[2]); // Day numbered[3] = Integer.parseInt(date[3]); // Hour numbered[4] = Integer.parseInt(date[4]); // Minute // Seconds sometimes have decimals. We want to remove them if( date[5].contains(".") ){ date[5] = date[5].substring(0, date[5].indexOf(".")); } numbered[5] = Integer.parseInt(date[5]); // Second return numbered; } private static class PriorityComparator implements Comparator<Priority>{ @Override public int compare(Priority one, Priority two) { return getValue(one)-getValue(two); } private int getValue(Priority p){ if( p == Priority.LOW ) return 0; if( p == Priority.MEDIUM ) return 1; if( p == Priority.HIGH ) return 2; return -1; } } private static class StatusComparator implements Comparator<Status>{ @Override public int compare(Status one, Status two) { return getValue(one)-getValue(two); } private int getValue(Status s){ if( s == Status.FIXED ) return 0; if( s == Status.PENDING ) return 1; if( s == Status.WIP ) return 2; return -1; } } }
36.612676
145
0.611336
79e6363f2e727945701a8f8b6df7181a0768e139
1,749
package com.tsy.sdk.social.sina; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import com.sina.weibo.sdk.api.share.BaseResponse; import com.sina.weibo.sdk.api.share.IWeiboHandler; import com.tsy.sdk.social.PlatformConfig; import com.tsy.sdk.social.PlatformType; import com.tsy.sdk.social.SocialApi; /** * Created by tsy on 16/8/4. */ public class WBShareCallbackActivity extends Activity implements IWeiboHandler.Response { protected SinaWBHandler mSinaWBHandler = null; public WBShareCallbackActivity() { } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SocialApi api = SocialApi.get(this.getApplicationContext()); this.mSinaWBHandler = (SinaWBHandler) api.getSSOHandler(PlatformType.SINA_WB); this.mSinaWBHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.SINA_WB)); if(this.getIntent() != null) { this.handleIntent(this.getIntent()); } } protected final void onNewIntent(Intent paramIntent) { super.onNewIntent(paramIntent); SocialApi api = SocialApi.get(this.getApplicationContext()); this.mSinaWBHandler = (SinaWBHandler) api.getSSOHandler(PlatformType.SINA_WB); this.mSinaWBHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.SINA_WB)); this.handleIntent(this.getIntent()); } protected void handleIntent(Intent intent) { this.mSinaWBHandler.onNewIntent(intent, this); } @Override public void onResponse(BaseResponse baseResponse) { this.mSinaWBHandler.onResponse(baseResponse); finish(); } }
32.388889
123
0.730132
c6ef5e9b829288e7de7778af3a8e36d6ef442842
4,605
/****************************************************************************** * ~ Copyright (c) 2018 [[email protected] | https://github.com/Jasonandy] * * ~ * * ~ 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 cn.ucaner.netty.demo.server; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; /** * @Package:cn.ucaner.netty.demo.server * @ClassName:DiscardServerHandler * @Description: <p> * 服务端处理通道.这里只是打印一下请求的内容,并不对请求进行任何的响应 DiscardServerHandler 继承自 * ChannelHandlerAdapter, 这个类实现了ChannelHandler接口, ChannelHandler提供了许多事件处理的接口方法, * 然后你可以覆盖这些方法。 现在仅仅只需要继承ChannelHandlerAdapter类而不是你自己去实现接口方法。 * </p> * @Author: - Jason * @CreatTime:2019年1月10日 下午9:43:16 * @Modify By: * @ModifyTime: 2019年1月10日 * @Modify marker: * @version V1.0 */ public class DiscardServerHandler extends ChannelHandlerAdapter{ /** * 这里我们覆盖了chanelRead()事件处理方法。 每当从客户端收到新的数据时, 这个方法会在收到消息时被调用, * 这个例子中,收到的消息的类型是ByteBuf * @param ctx * 通道处理的上下文信息 * @param msg * 接收的消息 */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{ try { //做类型转换,将msg转换成Netty的ByteBuf对象。 //ByteBuf类似于JDK中的java.nio.ByteBuffer 对象,不过它提供了更加强大和灵活的功能。 ByteBuf buf = (ByteBuf) msg; // 打印客户端输入,传输过来的的字符 System.out.print(buf.toString(CharsetUtil.UTF_8)); //通过ByteBuf的readableBytes方法可以获取缓冲区可读的字节数, //根据可读的字节数创建byte数组 byte[] data = new byte[buf.readableBytes()]; //通过ByteBuf的readBytes方法将缓冲区中的字节数组复制到新建的byte数组中 buf.readBytes(data); //通过new String构造函数获取请求消息。 String request = new String(data, "utf-8"); System.out.println("1.Server: " + request); System.out.println("2.This server receive Message by Jason : " + request); String command = "I WANT KNOW WHO IS JASON".equalsIgnoreCase(request)? "Jason is the CEO of JasonInternational" :"Sorry ! This is a bad Command!"; ctx.writeAndFlush(Unpooled.copiedBuffer(command.getBytes())); String response = "yesp I accept you message . Connection is established!"; //通过ChannelHandlerContext的write方法异步发送应答消息给客户端。 ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes())); //((ChannelFuture) ctx).addListener(ChannelFutureListener.CLOSE); } finally { /** * ByteBuf是一个引用计数对象,这个对象必须显示地调用release()方法来释放。 * 请记住处理器的职责是释放所有传递到处理器的引用计数对象。 */ // 抛弃收到的数据 ReferenceCountUtil.release(msg); } } /*** * 这个方法会在发生异常时触发 * * @param ctx * @param cause */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { /** * exceptionCaught() 事件处理方法是当出现 Throwable 对象才会被调用,即当 Netty 由于 IO * 错误或者处理器在处理事件时抛出的异常时。在大部分情况下,捕获的异常应该被记录下来 并且把关联的 channel * 给关闭掉。然而这个方法的处理方式会在遇到不同异常的情况下有不 同的实现,比如你可能想在关闭连接之前发送一个错误码的响应消息。 */ // 出现异常就关闭 cause.printStackTrace(); ctx.close(); } }
39.025424
95
0.54354
0b65f993d3a8d612f37ccc0f64e7de9558a088bf
2,398
package sensor_msgs.msg.dds; /** * * Definition of the class "CompressedImage" defined in CompressedImage_.idl. * * This file was automatically generated from CompressedImage_.idl by us.ihmc.idl.generator.IDLGenerator. * Do not update this file directly, edit CompressedImage_.idl instead. * */ public class CompressedImage { private std_msgs.msg.dds.Header header_; private java.lang.StringBuilder format_; private us.ihmc.idl.IDLSequence.Byte data_; public CompressedImage() { header_ = new std_msgs.msg.dds.Header(); format_ = new java.lang.StringBuilder(255); data_ = new us.ihmc.idl.IDLSequence.Byte(100, "type_9"); } public void set(CompressedImage other) { std_msgs.msg.dds.HeaderPubSubType.staticCopy(other.header_, header_); format_.setLength(0); format_.append(other.format_); data_.set(other.data_); } public std_msgs.msg.dds.Header getHeader() { return header_; } public java.lang.String getFormatAsString() { return getFormat().toString(); } public java.lang.StringBuilder getFormat() { return format_; } public void setFormat(String format) { format_.setLength(0); format_.append(format); } public us.ihmc.idl.IDLSequence.Byte getData() { return data_; } @Override public boolean equals(java.lang.Object other) { if (other == null) return false; if (other == this) return true; if (!(other instanceof CompressedImage)) return false; CompressedImage otherMyClass = (CompressedImage) other; boolean returnedValue = true; returnedValue &= this.header_.equals(otherMyClass.header_); returnedValue &= us.ihmc.idl.IDLTools.equals(this.format_, otherMyClass.format_); returnedValue &= this.data_.equals(otherMyClass.data_); return returnedValue; } @Override public java.lang.String toString() { StringBuilder builder = new StringBuilder(); builder.append("CompressedImage {"); builder.append("header="); builder.append(this.header_); builder.append(", "); builder.append("format="); builder.append(this.format_); builder.append(", "); builder.append("data="); builder.append(this.data_); builder.append("}"); return builder.toString(); } }
24.222222
105
0.658882
1a462b6a62c8c0da5ed75fb65bdb26cb28915597
600
package test.api.activity.async; import javastrava.api.API; import javastrava.model.StravaActivity; import test.api.activity.DeleteActivityTest; import test.api.callback.APIDeleteCallback; /** * <p> * Tests for {@link API#deleteActivityAsync(Long)} * </p> * * @author Dan Shannon * */ public class DeleteActivityAsyncTest extends DeleteActivityTest { @Override protected String classUnderTest() { return this.getClass().getName(); } @Override protected APIDeleteCallback<StravaActivity> deleter() { return ((api, activity) -> api.deleteActivityAsync(activity.getId()).get()); } }
22.222222
78
0.746667
6756520459e40e1385e90b39547475ce197d7990
773
package com.iovation.launchkey.sdk.integration.managers; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class ServiceTotpManager { private final DirectoryServiceManager directoryServiceManager; private boolean currentVerifyUserTotpResponse; @Inject public ServiceTotpManager(DirectoryServiceManager directoryServiceManager) { this.directoryServiceManager = directoryServiceManager; } public void verifyUserTotpCode(String userId, String totpCode) throws Throwable { currentVerifyUserTotpResponse = directoryServiceManager.getServiceClient().verifyTotp(userId, totpCode); } public Boolean getCurrentVerifyUserTotpResponse() { return currentVerifyUserTotpResponse; } }
30.92
112
0.791721
22ea680326e54a2dee283cc8dce75c4470d8e13f
1,644
/* OpenRemote, the Home of the Digital Home. * Copyright 2008-2011, OpenRemote Inc. * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openremote.controller.rest.support.json; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletOutputStream; /** * This is a adapter for adapting ByteArrayOutputStream and ServletOutputStream. * * @author handy.wang 2010-06-28 */ public class FilterServletOutputStream extends ServletOutputStream { private DataOutputStream stream; public FilterServletOutputStream(OutputStream output) { stream = new DataOutputStream(output); } public void write(int b) throws IOException { stream.write(b); } public void write(byte[] b) throws IOException { stream.write(b); } public void write(byte[] b, int off, int len) throws IOException { stream.write(b, off, len); } }
31.615385
80
0.748783
9c5dec92d67698f8445ac7fc2686c0bf7ab10071
1,957
/* * Copyright (c) 2020 Broadcom. * The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Broadcom, Inc. - initial API and implementation * */ package org.eclipse.lsp.cobol.usecases; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.eclipse.lsp.cobol.positive.CobolText; import org.eclipse.lsp.cobol.usecases.engine.UseCaseEngine; import org.junit.jupiter.api.Test; /** * Test that the functional identifiers are allowed in copy replace statement. COBOL LSP supports * just the syntax, actual manipulation of function doesn't take place. */ class TestFunctionalIdentifiersAllowedInCopyReplace { private static final String BASE = "0 IDENTIFICATION DIVISION.\n" + "1 PROGRAM-ID. TESTREPL.\n" + "2 DATA DIVISION.\n" + "3 WORKING-STORAGE SECTION.\n"; private static final String TEXT = BASE + "5 COPY {~DEMO1} REPLACING TAG_ID BY FUNCTION CONCAT(\"ACC\",\"_ID\").\n" + "8 PROCEDURE DIVISION."; private static final String TEXT2 = BASE + "5 COPY {~DEMO1} REPLACING FUNCTION CONCAT(\"ACC\",\"_ID\") BY TAG_ID.\n" + "8 PROCEDURE DIVISION."; private static final String DEMO1 = " \n"; private static final String DEMO1_NAME = "DEMO1"; @Test void testReplacementWithFunctionIdentifier() { UseCaseEngine.runTest( TEXT, ImmutableList.of(new CobolText(DEMO1_NAME, DEMO1)), ImmutableMap.of()); } @Test void testReplaceableWithFunctionIdentifier() { UseCaseEngine.runTest( TEXT2, ImmutableList.of(new CobolText(DEMO1_NAME, DEMO1)), ImmutableMap.of()); } }
33.169492
97
0.683189
38d3d5936438eddf9bc70c0d82c6303783d48456
524
package project.model.util; import project.model.gfx.Players; import project.model.gfx.Soldier.Faction; import project.model.util.Match.Mode; public class GameOptions { public Mode mode; public Faction[][] teams; public Players players; public String mapName; public int killsToWin; public GameOptions(Mode mode, Faction[][] teams, Players players, String mapName, int killsToWin){ this.mode = mode; this.teams = teams; this.players = players; this.mapName = mapName; this.killsToWin = killsToWin; } }
22.782609
99
0.748092
2f7ddf2b80fcf1d9f1374b73b54c33b2ddc12dc0
1,069
// This is a generated file. Not intended for manual editing. package fr.ensimag.deca.intellijplugin.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static fr.ensimag.deca.intellijplugin.psi.DecaTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import fr.ensimag.deca.intellijplugin.psi.*; public class DecaListDeclFieldImpl extends ASTWrapperPsiElement implements DecaListDeclField { public DecaListDeclFieldImpl(ASTNode node) { super(node); } public void accept(@NotNull DecaVisitor visitor) { visitor.visitListDeclField(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof DecaVisitor) accept((DecaVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List<DecaDeclField> getDeclFieldList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, DecaDeclField.class); } }
29.694444
94
0.785781
475863dfe0d485600280a05e288c44e2d518eabd
734
package br.com.agorainvestimentos.exchange.model; import java.math.BigDecimal; public class Trade { private Order buyOrder; private Order sellOrder; private Long quantity; private BigDecimal volume; public Order getBuyOrder() { return buyOrder; } public void setBuyOrder(Order buyOrder) { this.buyOrder = buyOrder; } public Order getSellOrder() { return sellOrder; } public void setSellOrder(Order sellOrder) { this.sellOrder = sellOrder; } public Long getQuantity() { return quantity; } public void setQuantity(Long quantity) { this.quantity = quantity; } public BigDecimal getVolume() { return volume; } public void setVolume(BigDecimal volume) { this.volume = volume; } }
14.68
49
0.719346
e93cf463f906b4f90021ca177c27008e7af5db6c
3,113
package at.tugraz.ist.swe; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PointF; import android.view.Gravity; import android.view.MotionEvent; import android.widget.Toast; public class ImageImportTool extends PaintingTool { private Bitmap image; private PointF position; private boolean overwrite_full_canvas; private Context context; public ImageImportTool(Bitmap file, Context context) { this.context = context; this.image = file; this.position = null; this.overwrite_full_canvas = false; if (context != null) showUsageHint(); } @Override public void drawTool(Canvas canvas) { float pos_x = 0.0f; float pos_y = 0.0f; int c_width = canvas.getWidth(); int c_height = canvas.getHeight(); if (image != null && position != null) { if (image.getHeight() > c_height || image.getWidth() > c_width) { if (context != null) { Toast toast; toast = Toast.makeText(context, "Your image is larger than the canvas dimensions. It has been resized to fit in.", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } image = scaleDownBitmap(image, c_height, c_width); overwrite_full_canvas = true; } if (!overwrite_full_canvas) { pos_x = position.x - image.getWidth() / 2.f; pos_y = position.y - image.getHeight() / 2.f; } canvas.drawBitmap(image, pos_x, pos_y, null); } } @Override public void handleEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { float x = event.getX(); float y = event.getY(); position = new PointF(x, y); } } @Override public void cleanUp() { } @Override public int getId() { return R.drawable.ic_outline_add_photo_alternate_24px; } private Bitmap scaleDownBitmap(Bitmap bm, int max_height, int max_width) { int new_height = bm.getHeight(); int new_width = bm.getWidth(); float aspect_ratio = new_width/ (float) new_height; if (new_width > max_width) { new_width = max_width; new_height = Math.round(new_width / aspect_ratio); } if (new_height > max_height) { new_height = max_height; new_width = Math.round(new_height * aspect_ratio); } return Bitmap.createScaledBitmap( bm, new_width, new_height, false); } private void showUsageHint() { Toast toast; toast = Toast.makeText(context,"Tap on the screen to place the image.", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }
28.3
155
0.564729
26a286979966024bcd76b991e934a951440adb2c
62
/* this comment spans a /* whats that? ifnore it! few lines */
10.333333
25
0.677419
5c956da432b698c900f6498e80c8718981ec6a71
863
package com.bignerdranch.android.coolweather.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; /** * Created by ericchen on 2016/11/21. */ public class CoolWeatherDB { //数据库名 public static final String DB_NAME = "cool_weather"; //数据库版本 public static final int VERSION = 1; private static CoolWeatherDB coolWeatherDB; private SQLiteDatabase db; //将构造方法私有化 private CoolWeatherDB(Context context){ CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context,DB_NAME,null,VERSION); db = dbHelper.getWritableDatabase(); } //获取CoolWeatherDB实例 public synchronized static CoolWeatherDB getInstance(Context context){ if(coolWeatherDB==null){ coolWeatherDB = new CoolWeatherDB(context); } return coolWeatherDB; } //将 }
23.972222
97
0.701043
924e5b3a57aa740b9858b3e9925e9647cdf7febe
2,627
import javafx.scene.transform.Rotate; import system.SystemA; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.util.stream.Stream; public class File8 { public static void main(String[] args) throws IOException { System.out.println(System.getProperty("os.name")); Path path = Paths.get("E:\\WORK\\需求\\sf"); String s = path.toString(); System.out.println(s); Path fileName = path.getFileName(); System.out.println(fileName); boolean absolute = path.isAbsolute(); System.out.println(absolute); Path path1 = path.toAbsolutePath(); System.out.println(path1.toString()); //File file = new File(path); FileSystem aDefault = FileSystems.getDefault(); PathMatcher pathMatcher = aDefault.getPathMatcher("glob:**/*.docx"); Files.walk(path, FileVisitOption.FOLLOW_LINKS) //.map(p->p.getFileName()) .filter(m -> pathMatcher.matches(m)) .forEach(System.out::println); System.out.println("*************************"); PathMatcher pathMatcher1 = aDefault.getPathMatcher("glob:*.docx"); Files.walk(path, FileVisitOption.FOLLOW_LINKS) .map(Path::getFileName) .filter(pathMatcher1::matches) .forEach(System.out::println); System.out.println("**************************"); Path textPath = Paths.get("src/main/17_iterator_pattern/source/test.txt"); System.out.println(textPath.toAbsolutePath()); //一次性读取所有文件 Files.readAllLines(textPath).stream() .forEach(System.out::println); System.out.println("***********************************"); Files.lines(textPath)//流式读取文件 .filter(a -> a.contains("a")) .forEach(System.out::println); System.out.println("**************************读的同时写入"); Stream <String> lines = Files.lines(textPath); PrintWriter printWriter = new PrintWriter("F:/learn/rust/design_model/src/main/17_iterator_pattern/source/testout.txt"); lines.map(l -> { System.out.println(l + "**"); return l + "*"; }) .filter(l -> l.contains("a")) .forEach(printWriter::println); printWriter.flush(); //Stream.generate(); } }
38.632353
128
0.590027
da8dd422e4298cbc0263379f85f44b4546d08071
5,465
package de.marvin.merkletree; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; /** * Stores all relevant information for a merkle proof and provides the functionality to verify a proof and to convert it to a byte array. */ public class Proof { private byte[] rootHash; /** * The proofSet contains all relevant hash values for the proof */ private ArrayList<byte[]> proofSet; private int leafIndex; private int leafSize; private String hashAlg; public Proof(byte[] rootHash, ArrayList<byte[]> proofSet, int leafIndex, int leafSize, String hashAlg){ this.rootHash = rootHash; this.proofSet = proofSet; this.leafIndex = leafIndex; this.leafSize = leafSize; this.hashAlg = hashAlg; } /** * Creates a byte array which contains all information of the proof. * The byte array is constructed in the following way: * hash length (int) | proofSet Size (int) | leafIndex (int) | leafSize (int) | rootHash (byte[]) | proofSet (byte[]) | hashAlgorithm (String) * @return byte array */ public byte[] asBytes(){ ByteBuffer bb = ByteBuffer.allocate((proofSet.size() + 1) * rootHash.length + 4 * Integer.BYTES + hashAlg.length()); bb.putInt(rootHash.length); bb.putInt(proofSet.size()); bb.putInt(leafIndex); bb.putInt(leafSize); bb.put(rootHash); for(byte[] hash: proofSet){ bb.put(hash); } bb.put(hashAlg.getBytes(StandardCharsets.UTF_8)); return bb.array(); } public byte[] getRootHash() { return rootHash; } public String getHashAlg() { return hashAlg; } @Override public String toString() { return "Proof{" + "rootHash=" + Arrays.toString(rootHash) + ", proofSet=" + proofSet + ", leafIndex=" + leafIndex + ", leafSize=" + leafSize + ", hashAlg='" + hashAlg + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()){ return false; } Proof proof = (Proof) o; if(this.proofSet.size() != proof.proofSet.size()){ return false; } for(int i = 0; i<this.proofSet.size(); i++){ if(!Arrays.equals(this.proofSet.get(i), proof.proofSet.get(i))){ return false; } } return leafIndex == proof.leafIndex && leafSize == proof.leafSize && Arrays.equals(rootHash, proof.rootHash) && hashAlg.equals(proof.hashAlg); } /** * Restores a proof from a byte array which was created with {@link #asBytes()} * @param proof byte array which contains the proof * @return proof */ public static Proof getFromBytes(byte[] proof){ ByteBuffer bb = ByteBuffer.wrap(proof); int hashLength = bb.getInt(); int proofSetSize = bb.getInt(); int leafIndex = bb.getInt(); int leafSize = bb.getInt(); int position = bb.position(); byte[] rootHash = Arrays.copyOfRange(proof, position, position+hashLength); ArrayList<byte[]> proofSet = new ArrayList<>(); for(int i = 0; i < proofSetSize; i++){ position += hashLength; proofSet.add(Arrays.copyOfRange(proof, position, position+hashLength)); } position += hashLength; String hashAlg = new String(Arrays.copyOfRange(proof, position, proof.length), StandardCharsets.UTF_8); return new Proof(rootHash, proofSet, leafIndex, leafSize, hashAlg); } /** * Evaluates a merkle proof with the given data and verifies if the data belongs to the corresponding merkle tree * @param data * @param proof * @return true iff data fulfills the merkle proof * @throws NoSuchAlgorithmException */ public static boolean verify(byte[] data, Proof proof) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(proof.hashAlg); byte[] currentHash = md.digest(data); byte[] combinedChildHashes = new byte[2*md.getDigestLength()]; int index = proof.leafIndex; int leafSize = proof.leafSize; for(byte[] hash: proof.proofSet){ if(index == leafSize - 1 || index % 2 == 1){ // currentHash is the right child and the hash from the proofSet is the left child System.arraycopy(hash, 0, combinedChildHashes, 0, hash.length); System.arraycopy(currentHash, 0, combinedChildHashes, md.getDigestLength(), currentHash.length); } else { // currentHash is the left child and the hash from the proofSet is the right child System.arraycopy(currentHash, 0, combinedChildHashes, 0, currentHash.length); System.arraycopy(hash, 0, combinedChildHashes, md.getDigestLength(), hash.length); } currentHash = md.digest(combinedChildHashes); leafSize = leafSize / 2 + leafSize % 2; index = index / 2; } return MessageDigest.isEqual(proof.rootHash, currentHash); } }
36.925676
146
0.603843
2e0915e288a04fc43f51eca2d2b7c1700ef48b3a
3,941
/* * Copyright 2018 Institut Laue–Langevin * * 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 eu.ill.preql.domain; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @Entity @Table(name = "course") public class Course extends AbstractTestEntity { @Column private Boolean active; @Column private String code; @Column private Integer credits; @Column private Date startDate; @Column private Date endDate; @Column private Long duration; @Column private String description; @Column private Double price; @Embedded private CourseDetails details; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "course_tag", joinColumns = @JoinColumn(name = "course_id"), inverseJoinColumns = @JoinColumn(name = "tag_id") ) private List<Tag> tags = new ArrayList<>(); @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "teacher_id", nullable = false) private Teacher teacher; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "tenant_id", nullable = false) private Tenant tenant; @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "course_id") private List<Attachment> attachments = new ArrayList<>(); public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getCredits() { return credits; } public void setCredits(Integer credits) { this.credits = credits; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<Tag> getTags() { return tags; } public void setTags(List<Tag> tags) { this.tags = tags; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public List<Attachment> getAttachments() { return attachments; } public void setAttachments(List<Attachment> attachments) { this.attachments = attachments; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public Tenant getTenant() { return tenant; } public void setTenant(Tenant tenant) { this.tenant = tenant; } public Long getDuration() { return duration; } public void setDuration(Long duration) { this.duration = duration; } public CourseDetails getDetails() { return details; } public void setDetails(CourseDetails details) { this.details = details; } }
21.074866
75
0.634611
ac4ed68453efeecf5938481e7027eca02dbd7b61
294
package com.agileengine.imageparser.service; import com.agileengine.imageparser.domain.Picture; import java.util.List; public interface PictureService { List<Picture> searchPicturesByMetadata(String searchTerm); List<Picture> getAll(); Picture getPictureDetails(String id); }
19.6
62
0.782313
bae6f745618b4134d2946cae88cb2d7d7f2ca45b
2,780
package org.bougainvillea.java.basejava.codequality.chapter07; import java.util.ArrayList; import java.util.List; /** * 97.警惕泛型是不能协变和逆变的 * * 注意:Java的泛型是不支持协变和逆变的,只是能够实现协变和逆变 * * 协变(covariance)和逆变(contravariance)?Wiki上是这样定义的: * Within the type system of a programming language, * covariance and contravariance refers to the ordering of types from narrower to widerand their interchangeability or equivalence in certain situations (such asparameters, generics, and return types). * 在编程语言的类型框架中, * 协变和逆变是指宽类型和窄类型在某种情况下(如参数、泛型、返回值)替换或交换的特性, * 简单地说,协变是用一个窄类型替换宽类型, * 而逆变则是用宽类型覆盖窄类型。 * 其实,在Java中协变和逆变我们已经用了很久了,只是我们没发觉而已 * * 1)泛型不支持协变 * ArrayList是List的子类型,( 不支持协变) * Integer是Number的子类型,(支持协变) * 里氏替换原则(Liskov Substitution Principle)在此处行不通了, * 原因就是Java为了保证运行期的安全性, * 必须保证泛型参数类型是固定的, * 所以不允许一个泛型参数可以同时包含两种类型, * 即使是父子类关系也不行 * 泛型不支持协变,但可以使用通配符(Wildcard)模拟协变 * 2)泛型不支持逆变 * Java虽然可以允许逆变存在,但在对类型赋值上是不允许逆变的, * 不能把一个父类实例对象赋值给一个子类类型变量, * 泛型自然也不允许此种情况发生了, * 但是它可以使用super关键字来模拟实现 * * 泛型既不支持协变也不支持逆变,带有泛型参数的子类型定义与我们经常使用的类类型也不相同 * Integer是Number的子类型 * ArrayList<Integer>是List<Integer>的子类型 * Integer[]是Number[]的子类型 * List<Integer>不是List<Number>的子类型 * List<Integer>不是List<? extends Integer>的子类型 * List<Integer>不是List<? super Integer>的子类型 */ public class Ds { public static void main(String[] args) { /** * baseDs变量发生协变, * base变量是Base类型,它是父类,而其赋值却是子类实例,也就是用窄类型覆盖了宽类型 * 这也叫多态(Polymorphism),两者同含义 */ BaseDs baseDs=new SubDs(); //数组支持协变 Number[] n=new Integer[10]; //泛型不支持协变 // List<Number> ln=new ArrayList<Integer>();//编译不通过 //泛型不支持协变,但可以使用通配符(Wildcard)模拟协变 //“? extends Number”表示的意思是,允许Number所有的子类(包括自身)作为泛型参数类型, // 但在运行期只能是一个具体类型,或者是Integer类型,或者是Double类型,或者是Number类型, // 也就是说通配符只是在编码期有效,运行期则必须是一个确定类型 List<? extends Number> ln1=new ArrayList<Integer>(); //泛型不支持逆变 //但是可以使用super关键字来模拟实现 //? super Integer”的意思是可以把所有Integer父类型(自身、父类或接口)作为泛型参数, // 这里看着就像是把一个Number类型的ArrayList赋值给了Integer类型的List, // 其外观类似于使用一个宽类型覆盖一个窄类型,它模拟了逆变的实现 List<? super Integer> li=new ArrayList<Number>(); } } class BaseDs{ public Number doStuff(){ return 0; } public void doStuff1(Integer i){ } } class SubDs extends BaseDs{ /** * 子类的doStuff方法返回值的类型比父类方法要窄 * 此时doStuff方法就是一个协变方法, * 同时根据Java的覆写定义来看,这又属于覆写 */ @Override public Integer doStuff() { return 0; } /** * 子类的doStuff方法的参数类型比父类要宽,此时就是一个逆变方法, * 子类扩大了父类方法的输入参数, * 但根据覆写定义来看,doStuff不属于覆写,只是重载而已。 * 由于此时的doStuff方法已经与父类没有任何关系了, * 只是子类独立扩展出的一个行为, * 所以是否声明为doStuff方法名意义不大, * 逆变已经不具有特别的意义 */ public void doStuff1(Number i) { } }
26.990291
201
0.68777
388205772dfabf476feb97ad239d01a3f7649938
512
package ru.codeunited.sbapi.escrow; import java.util.UUID; public class RqUID { private final UUID uuid; public RqUID() { this(UUID.randomUUID()); } public RqUID(UUID uuid) { this.uuid = uuid; } public UUID get() { return uuid; } /** * Return without - * @return */ public String trimmed() { return uuid.toString().replaceAll("-", ""); } @Override public String toString() { return trimmed(); } }
15.058824
51
0.535156
c9aa2738d327f0ab4def79c48735e44cec88ef8f
142
import org.testng.annotations.Test; public class AppClass2Test { @Test public void testMain() { AppClass2.main(null); } }
17.75
35
0.65493
573dcb03822948def48ff2edd7a93f3112a3b7f9
1,303
package com.freedy.backend.config.security; import com.alibaba.fastjson.JSON; import com.freedy.backend.utils.Result; import com.freedy.backend.enumerate.ResultCode; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 当用户没有携带有效凭证时,就会转到这里来 * 认证失败处理类 * @author Freedy * @date 2021/4/28 15:41 */ @Slf4j @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { log.debug("访问无凭证"); Result r; r = Result.error(ResultCode.USER_NO_CERTIFICATE_OR_ACCOUNT_EXPIRED.getCode() ,ResultCode.USER_NO_CERTIFICATE_OR_ACCOUNT_EXPIRED.getMessage()); // 使用fastjson String json = JSON.toJSONString(r); // 指定响应格式是json response.setContentType("text/json;charset=utf-8"); response.getWriter().write(json); } }
34.289474
148
0.76746
0f323429e757acc745fa541a05cbadfc885bb5e9
1,897
package com.techreturners.exercise004; import org.junit.Ignore; import org.junit.Test; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; import static org.junit.Assert.assertEquals; public class Exercise004Test { @Test public void checkGetDateTimeWhenDateIsSpecified() { Exercise004 ex004 = new Exercise004(LocalDate.of(2021, Month.JULY, 19)); LocalDateTime expected = LocalDateTime.of(2053, Month.MARCH, 27, 1, 46, 40); assertEquals(expected, ex004.getDateTime()); } @Test public void checkGetDateTimeWhenBothDateAndTimeIsSpecified() { Exercise004 ex004 = new Exercise004(LocalDateTime.of(2021, Month.MARCH, 4, 23, 22, 0, 0)); LocalDateTime expected = LocalDateTime.of(2052, Month.NOVEMBER, 11, 1, 8, 40); assertEquals(expected, ex004.getDateTime()); } @Test public void checkGetDateTimeWhenBothDateAndTimeIsSpecifiedWithDayRollOver() { Exercise004 ex004 = new Exercise004(LocalDateTime.of(2021, Month.JANUARY, 24, 23, 59, 59, 0)); LocalDateTime expected = LocalDateTime.of(2052, Month.OCTOBER, 03, 1, 46, 39); assertEquals(expected, ex004.getDateTime()); } // ================ // Additional tests // ================ @Test public void checkGetDateTimeOf1890() { Exercise004 ex004 = new Exercise004(LocalDateTime.of(1890, Month.MARCH, 1, 0, 0, 0, 0)); LocalDateTime expected = LocalDateTime.of(1921, Month.NOVEMBER, 8, 1, 46, 40); assertEquals(expected, ex004.getDateTime()); } @Test public void checkGetDateTimeOf10330() { Exercise004 ex004 = new Exercise004(LocalDateTime.of(10330, Month.JANUARY, 1, 23, 59, 59, 0)); LocalDateTime expected = LocalDateTime.of(10361, Month.SEPTEMBER, 10, 1, 46, 39); assertEquals(expected, ex004.getDateTime()); } }
30.111111
102
0.674222
d0f958050a57710d3c6242c5d19a73d0e364bc45
2,050
package net.es.oscars.topo.ent; import com.fasterxml.jackson.annotation.*; import lombok.*; import net.es.oscars.topo.beans.IntRange; import net.es.oscars.topo.enums.Layer; import org.hibernate.annotations.NaturalId; import javax.persistence.*; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; @Data @Entity @Builder @AllArgsConstructor @NoArgsConstructor @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "urn") public class Port { @Id @GeneratedValue private Long id; @NonNull @NaturalId @Column(unique = true) private String urn; @Basic @Column(length = 65535) @JsonInclude(JsonInclude.Include.NON_EMPTY) private ArrayList<String> tags; @NonNull @ManyToOne @JsonBackReference(value="device") private Device device; @Column @NonNull private Integer reservableIngressBw; @Column @NonNull private Integer reservableEgressBw; @ElementCollection(fetch = FetchType.EAGER) @CollectionTable @JsonInclude(JsonInclude.Include.NON_EMPTY) private Set<Layer3Ifce> ifces = new HashSet<>(); @ElementCollection(fetch = FetchType.EAGER) @CollectionTable @JsonInclude(JsonInclude.Include.NON_EMPTY) private Set<IntRange> reservableVlans = new HashSet<>(); @ElementCollection(fetch = FetchType.EAGER) @CollectionTable @JsonInclude(JsonInclude.Include.NON_EMPTY) private Set<Layer> capabilities = new HashSet<>(); @Override public int hashCode() { return 31; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null ) { return false; } if (getClass() != obj.getClass()) { return false; } Port other = (Port) obj; return id != null && id.equals(other.getId()); } public String toString() { return this.getClass().getSimpleName() + "-" + getUrn(); } }
22.777778
73
0.655122
b5fc7bf42295bf6c2716eb9c644fddd28429324f
4,279
package com.trkj.framework.mybatisplus.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.trkj.framework.entity.mybatisplus.ClockRecord; import com.trkj.framework.entity.mybatisplus.Staff; import com.trkj.framework.mybatisplus.mapper.CardRecordMapper; import com.trkj.framework.mybatisplus.mapper.StaffMapper; import com.trkj.framework.mybatisplus.service.CardRecordService; import lombok.var; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; @Service public class CardRecordlmpl implements CardRecordService { @Autowired private CardRecordMapper cardRecordMapper; @Autowired private StaffMapper staffMapper; /** * 根据员工名称查询打卡记录 * * @param cardRecord * @return */ @Override public IPage<ClockRecord> selectCardRecordAll(ClockRecord cardRecord) { Page<ClockRecord> page = new Page<>(cardRecord.getCurrentPage(), cardRecord.getPagesize()); final var staffName = cardRecord.getStaffName(); QueryWrapper<ClockRecord> queryWrapper = new QueryWrapper<>(); if (cardRecord.getStartTime() != null || cardRecord.getEndTime() != null) { //根据开始日期结束日期范围查询 queryWrapper.between("CREATED_TIME", cardRecord.getStartTime(), cardRecord.getEndTime()); } queryWrapper.eq("STAFF_NAME", staffName); return cardRecordMapper.selectPage(page, queryWrapper); } /** * 删除打卡记录 * * @param clockRecord * @return */ @Override @Transactional(rollbackFor = Exception.class) public Integer deleteClock(ClockRecord clockRecord) throws ArithmeticException { final var clockRecordId = clockRecord.getClockRecordId(); ClockRecord cardRecord = new ClockRecord(); cardRecord.setIsDeleted(1L); cardRecord.setClockRecordId(clockRecordId); cardRecord.setUpdatedTime(new Date()); final var i = cardRecordMapper.deleteById(cardRecord); if (i == 1) { return 1; } else { throw new ArithmeticException("删除失败"); } } /** * 导入打卡记录数据 * * @param list * @return */ @Override @Transactional(rollbackFor = Exception.class) public Integer importCardRecord(List<ClockRecord> list) { var insert = ""; for (int i = 0; i < list.size(); i++) { insert = String.valueOf(cardRecordMapper.insert(list.get(i))); } if ("1".equals(insert)) { return 99; } else { return 66; } } /** * 获取Excel表中的数据去数据库中查有无相同数据 * * @param objects * @return */ @Override public Integer selcetCardRecord(List<Object> objects) { QueryWrapper<ClockRecord> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("STAFF_NAME", objects.get(0).toString()); queryWrapper.eq("DEPT_NAME", objects.get(1).toString()); System.out.println("11111111111111111111111111111111111111111111111111111"); System.out.println(objects.get(2).toString().substring(0, 10)); if (objects.get(2).toString().substring(0, 10) != null) { queryWrapper.apply("TO_CHAR(MORN_CLOCK,'yyyy-mm-dd') = {0}", objects.get(2).toString().substring(0, 10)); } if (objects.get(3).toString().substring(0, 10) != null) { queryWrapper.apply("TO_CHAR(AFTERNOON_CLOCK,'yyyy-mm-dd') = {0}", objects.get(3).toString().substring(0, 10)); } return cardRecordMapper.selectCount(queryWrapper); } /** * 根据员工名称查询打卡记录2 * * @param * @return */ @Override public List<ClockRecord> selectCardRecordAllByName(ClockRecord clockRecord) { QueryWrapper<ClockRecord> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("STAFF_NAME", clockRecord.getStaffName()); return cardRecordMapper.selectList(queryWrapper); } }
34.788618
122
0.667446
399c792d0cb1ea18e7bfa80726a8f4dc301d3d8e
905
package com.intellij.eslint_idea.internal; import java.util.List; public class ESLintSocketResponse { private List<ESLintResult> results; public ESLintSocketResponse() { } public List<ESLintResult> getResults() { return results; } public static class ESLintResult { private String filePath; private List<ESLintMessage> messages; public ESLintResult() { } public List<ESLintMessage> getMessages() { return messages; } } public static class ESLintMessage { private String ruleId; private int severity; private String message; private int line; private int column; public ESLintMessage() { } public String getRuleId() { return ruleId; } public int getSeverity() { return severity; } public String getMessage() { return message; } public int getLine() { return line; } public int getColumn() { return column; } } }
14.365079
44
0.695028
1bccec5c6e9eadac02b8c6c9c5d426a695c8a247
23,310
/* * Copyright © 2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.internal.app.runtime.distributed; import co.cask.cdap.api.flow.FlowSpecification; import co.cask.cdap.api.flow.FlowletDefinition; import co.cask.cdap.app.program.Program; import co.cask.cdap.app.queue.QueueSpecification; import co.cask.cdap.app.queue.QueueSpecificationGenerator; import co.cask.cdap.app.runtime.AbstractProgramRuntimeService; import co.cask.cdap.app.runtime.ProgramController; import co.cask.cdap.app.runtime.ProgramResourceReporter; import co.cask.cdap.app.store.Store; import co.cask.cdap.app.store.StoreFactory; import co.cask.cdap.common.conf.CConfiguration; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.metrics.MetricsCollectionService; import co.cask.cdap.common.metrics.MetricsCollector; import co.cask.cdap.common.queue.QueueName; import co.cask.cdap.data2.transaction.queue.QueueAdmin; import co.cask.cdap.data2.transaction.stream.StreamAdmin; import co.cask.cdap.internal.app.program.TypeId; import co.cask.cdap.internal.app.queue.SimpleQueueSpecificationGenerator; import co.cask.cdap.internal.app.runtime.AbstractResourceReporter; import co.cask.cdap.internal.app.runtime.ProgramRunnerFactory; import co.cask.cdap.internal.app.runtime.flow.FlowUtils; import co.cask.cdap.internal.app.runtime.service.SimpleRuntimeInfo; import co.cask.cdap.proto.Containers; import co.cask.cdap.proto.DistributedProgramLiveInfo; import co.cask.cdap.proto.Id; import co.cask.cdap.proto.NotRunningProgramLiveInfo; import co.cask.cdap.proto.ProgramLiveInfo; import co.cask.cdap.proto.ProgramType; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Table; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.inject.Inject; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FsStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.twill.api.ResourceReport; import org.apache.twill.api.RunId; import org.apache.twill.api.TwillController; import org.apache.twill.api.TwillRunResources; import org.apache.twill.api.TwillRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.cask.cdap.proto.Containers.ContainerInfo; import static co.cask.cdap.proto.Containers.ContainerType.FLOWLET; /** * */ public final class DistributedProgramRuntimeService extends AbstractProgramRuntimeService { private static final Logger LOG = LoggerFactory.getLogger(DistributedProgramRuntimeService.class); // Pattern to split a Twill App name into [type].[accountId].[appName].[programName] private static final Pattern APP_NAME_PATTERN = Pattern.compile("^(\\S+)\\.(\\S+)\\.(\\S+)\\.(\\S+)$"); private final TwillRunner twillRunner; // TODO (terence): Injection of Store and QueueAdmin is a hack for queue reconfiguration. // Need to remove it when FlowProgramRunner can runs inside Twill AM. private final Store store; private final QueueAdmin queueAdmin; private final StreamAdmin streamAdmin; private final ProgramResourceReporter resourceReporter; @Inject DistributedProgramRuntimeService(ProgramRunnerFactory programRunnerFactory, TwillRunner twillRunner, StoreFactory storeFactory, QueueAdmin queueAdmin, StreamAdmin streamAdmin, MetricsCollectionService metricsCollectionService, Configuration hConf, CConfiguration cConf) { super(programRunnerFactory); this.twillRunner = twillRunner; this.store = storeFactory.create(); this.queueAdmin = queueAdmin; this.streamAdmin = streamAdmin; this.resourceReporter = new ClusterResourceReporter(metricsCollectionService, hConf, cConf); } @Override public synchronized RuntimeInfo lookup(final RunId runId) { RuntimeInfo runtimeInfo = super.lookup(runId); if (runtimeInfo != null) { return runtimeInfo; } // Lookup all live applications and look for the one that matches runId String appName = null; TwillController controller = null; for (TwillRunner.LiveInfo liveInfo : twillRunner.lookupLive()) { for (TwillController c : liveInfo.getControllers()) { if (c.getRunId().equals(runId)) { appName = liveInfo.getApplicationName(); controller = c; break; } } if (controller != null) { break; } } if (controller == null) { LOG.info("No running instance found for RunId {}", runId); // TODO (ENG-2623): How about mapreduce job? return null; } Matcher matcher = APP_NAME_PATTERN.matcher(appName); if (!matcher.matches()) { LOG.warn("Unrecognized application name pattern {}", appName); return null; } ProgramType type = getType(matcher.group(1)); if (type == null) { LOG.warn("Unrecognized program type {}", appName); return null; } Id.Program programId = Id.Program.from(matcher.group(2), matcher.group(3), matcher.group(4)); if (runtimeInfo != null) { runtimeInfo = createRuntimeInfo(type, programId, controller); updateRuntimeInfo(type, runId, runtimeInfo); return runtimeInfo; } else { LOG.warn("Unable to find program {} {}", type, programId); return null; } } @Override public synchronized Map<RunId, RuntimeInfo> list(ProgramType type) { Map<RunId, RuntimeInfo> result = Maps.newHashMap(); result.putAll(super.list(type)); // Goes through all live application, filter out the one that match the given type. for (TwillRunner.LiveInfo liveInfo : twillRunner.lookupLive()) { String appName = liveInfo.getApplicationName(); Matcher matcher = APP_NAME_PATTERN.matcher(appName); if (!matcher.matches()) { continue; } ProgramType appType = getType(matcher.group(1)); if (appType != type) { continue; } for (TwillController controller : liveInfo.getControllers()) { RunId runId = controller.getRunId(); if (result.containsKey(runId)) { continue; } Id.Program programId = Id.Program.from(matcher.group(2), matcher.group(3), matcher.group(4)); RuntimeInfo runtimeInfo = createRuntimeInfo(type, programId, controller); if (runtimeInfo != null) { result.put(runId, runtimeInfo); updateRuntimeInfo(type, runId, runtimeInfo); } else { LOG.warn("Unable to find program {} {}", type, programId); } } } return ImmutableMap.copyOf(result); } private RuntimeInfo createRuntimeInfo(ProgramType type, Id.Program programId, TwillController controller) { try { Program program = store.loadProgram(programId, type); Preconditions.checkNotNull(program, "Program not found"); ProgramController programController = createController(program, controller); return programController == null ? null : new SimpleRuntimeInfo(programController, type, programId); } catch (Exception e) { LOG.error("Got exception: ", e); return null; } } private ProgramController createController(Program program, TwillController controller) { AbstractTwillProgramController programController = null; String programId = program.getId().getId(); switch (program.getType()) { case FLOW: { FlowSpecification flowSpec = program.getSpecification().getFlows().get(programId); DistributedFlowletInstanceUpdater instanceUpdater = new DistributedFlowletInstanceUpdater( program, controller, queueAdmin, streamAdmin, getFlowletQueues(program, flowSpec) ); programController = new FlowTwillProgramController(programId, controller, instanceUpdater); break; } case PROCEDURE: programController = new ProcedureTwillProgramController(programId, controller); break; case MAPREDUCE: programController = new MapReduceTwillProgramController(programId, controller); break; case WORKFLOW: programController = new WorkflowTwillProgramController(programId, controller); break; case WEBAPP: programController = new WebappTwillProgramController(programId, controller); break; case SERVICE: DistributedServiceRunnableInstanceUpdater instanceUpdater = new DistributedServiceRunnableInstanceUpdater( program, controller); programController = new ServiceTwillProgramController(programId, controller, instanceUpdater); break; } return programController == null ? null : programController.startListen(); } private ProgramType getType(String typeName) { try { return ProgramType.valueOf(typeName.toUpperCase()); } catch (IllegalArgumentException e) { return null; } } // TODO (terence) : This method is part of the hack mentioned above. It should be removed when // FlowProgramRunner moved to run in AM. private Multimap<String, QueueName> getFlowletQueues(Program program, FlowSpecification flowSpec) { // Generate all queues specifications Id.Application appId = Id.Application.from(program.getAccountId(), program.getApplicationId()); Table<QueueSpecificationGenerator.Node, String, Set<QueueSpecification>> queueSpecs = new SimpleQueueSpecificationGenerator(appId).create(flowSpec); // For storing result from flowletId to queue. ImmutableSetMultimap.Builder<String, QueueName> resultBuilder = ImmutableSetMultimap.builder(); // Loop through each flowlet for (Map.Entry<String, FlowletDefinition> entry : flowSpec.getFlowlets().entrySet()) { String flowletId = entry.getKey(); long groupId = FlowUtils.generateConsumerGroupId(program, flowletId); int instances = entry.getValue().getInstances(); // For each queue that the flowlet is a consumer, store the number of instances for this flowlet for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.column(flowletId).values())) { resultBuilder.put(flowletId, queueSpec.getQueueName()); } } return resultBuilder.build(); } @Override public ProgramLiveInfo getLiveInfo(Id.Program program, ProgramType type) { String twillAppName = String.format("%s.%s.%s.%s", type.name().toLowerCase(), program.getAccountId(), program.getApplicationId(), program.getId()); Iterator<TwillController> controllers = twillRunner.lookup(twillAppName).iterator(); JsonObject json = new JsonObject(); // this will return an empty Json if there is no live instance if (controllers.hasNext()) { TwillController controller = controllers.next(); if (controllers.hasNext()) { LOG.warn("Expected at most one live instance of Twill app {} but found at least two.", twillAppName); } ResourceReport report = controller.getResourceReport(); if (report != null) { DistributedProgramLiveInfo liveInfo = new DistributedProgramLiveInfo(program, type, report.getApplicationId()); // if program type is flow then the container type is flowlet. Containers.ContainerType containerType = ProgramType.FLOW.equals(type) ? FLOWLET : Containers.ContainerType.valueOf(type.name()); for (Map.Entry<String, Collection<TwillRunResources>> entry : report.getResources().entrySet()) { for (TwillRunResources resources : entry.getValue()) { liveInfo.addContainer(new ContainerInfo(containerType, entry.getKey(), resources.getInstanceId(), resources.getContainerId(), resources.getHost(), resources.getMemoryMB(), resources.getVirtualCores(), resources.getDebugPort())); } } // Add a list of announced services and their discoverables to the liveInfo. liveInfo.addServices(report.getServices()); return liveInfo; } } return new NotRunningProgramLiveInfo(program, type); } /** * Reports resource usage of the cluster and all the app masters of running twill programs. */ private class ClusterResourceReporter extends AbstractResourceReporter { private static final String RM_CLUSTER_METRICS_PATH = "/ws/v1/cluster/metrics"; private static final String CLUSTER_METRICS_CONTEXT = "-.cluster"; private final Path hbasePath; private final Path namedspacedPath; private final PathFilter namespacedFilter; private final List<URL> rmUrls; private final String namespace; private FileSystem hdfs; public ClusterResourceReporter(MetricsCollectionService metricsCollectionService, Configuration hConf, CConfiguration cConf) { super(metricsCollectionService); try { this.hdfs = FileSystem.get(hConf); } catch (IOException e) { LOG.error("unable to get hdfs, cluster storage metrics will be unavailable"); this.hdfs = null; } this.namespace = cConf.get(Constants.CFG_HDFS_NAMESPACE); this.namedspacedPath = new Path(namespace); this.hbasePath = new Path(hConf.get(HConstants.HBASE_DIR)); this.namespacedFilter = new NamespacedPathFilter(); List<URL> rmUrls = Collections.emptyList(); try { rmUrls = getResourceManagerURLs(hConf); } catch (MalformedURLException e) { LOG.error("webapp address for the resourcemanager is malformed." + " Cluster memory metrics will not be collected.", e); } LOG.trace("RM urls determined... {}", rmUrls); this.rmUrls = rmUrls; } // if ha resourcemanager is being used, need to read the config differently // HA rm has a setting for the rm ids, which is a comma separated list of ids. // it then has a separate webapp.address.<id> setting for each rm. private List<URL> getResourceManagerURLs(Configuration hConf) throws MalformedURLException { List<URL> urls = Lists.newArrayList(); // if HA resource manager is enabled if (hConf.getBoolean(YarnConfiguration.RM_HA_ENABLED, false)) { LOG.trace("HA RM is enabled, determining webapp urls..."); // for each resource manager for (String rmID : hConf.getStrings(YarnConfiguration.RM_HA_IDS)) { urls.add(getResourceURL(hConf, rmID)); } } else { LOG.trace("HA RM is not enabled, determining webapp url..."); urls.add(getResourceURL(hConf, null)); } return urls; } // get the url for resource manager cluster metrics, given the id of the resource manager. private URL getResourceURL(Configuration hConf, String rmID) throws MalformedURLException { String setting = YarnConfiguration.RM_WEBAPP_ADDRESS; if (rmID != null) { setting += "." + rmID; } String addrStr = hConf.get(setting); // in HA mode, you can either set yarn.resourcemanager.hostname.<rm-id>, // or you can set yarn.resourcemanager.webapp.address.<rm-id>. In non-HA mode, the webapp address // is populated based on the resourcemanager hostname, but this is not the case in HA mode. // Therefore, if the webapp address is null, check for the resourcemanager hostname to derive the webapp address. if (addrStr == null) { // this setting is not a constant for some reason... setting = YarnConfiguration.RM_PREFIX + "hostname"; if (rmID != null) { setting += "." + rmID; } addrStr = hConf.get(setting) + ":" + YarnConfiguration.DEFAULT_RM_WEBAPP_PORT; } addrStr = "http://" + addrStr + RM_CLUSTER_METRICS_PATH; LOG.trace("Adding {} as a rm address.", addrStr); return new URL(addrStr); } @Override public void reportResources() { for (TwillRunner.LiveInfo info : twillRunner.lookupLive()) { String metricContext = getMetricContext(info); if (metricContext == null) { continue; } // will have multiple controllers if there are multiple runs of the same application for (TwillController controller : info.getControllers()) { ResourceReport report = controller.getResourceReport(); if (report == null) { continue; } int memory = report.getAppMasterResources().getMemoryMB(); int vcores = report.getAppMasterResources().getVirtualCores(); sendMetrics(metricContext, 1, memory, vcores, controller.getRunId().getId()); } } reportClusterStorage(); boolean reported = false; // if we have HA resourcemanager, need to cycle through possible webapps in case one is down. for (URL url : rmUrls) { // if we were able to hit the resource manager webapp, we don't have to try the others. if (reportClusterMemory(url)) { reported = true; break; } } if (!reported) { LOG.warn("unable to get resource manager metrics, cluster memory metrics will be unavailable"); } } // YARN api is unstable, hit the webservice instead // returns whether or not it was able to hit the webservice. private boolean reportClusterMemory(URL url) { Reader reader = null; HttpURLConnection conn = null; LOG.trace("getting cluster memory from url {}", url); try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); reader = new InputStreamReader(conn.getInputStream(), Charsets.UTF_8); JsonObject response; try { response = new Gson().fromJson(reader, JsonObject.class); } catch (JsonParseException e) { // this is normal if this is not the active RM return false; } if (response != null) { JsonObject clusterMetrics = response.getAsJsonObject("clusterMetrics"); long totalMemory = clusterMetrics.get("totalMB").getAsLong(); long availableMemory = clusterMetrics.get("availableMB").getAsLong(); MetricsCollector collector = getCollector(CLUSTER_METRICS_CONTEXT); LOG.trace("resource manager, total memory = " + totalMemory + " available = " + availableMemory); collector.gauge("resources.total.memory", totalMemory); collector.gauge("resources.available.memory", availableMemory); return true; } return false; } catch (Exception e) { LOG.error("Exception getting cluster memory from ", e); return false; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LOG.error("Exception closing reader", e); } } if (conn != null) { conn.disconnect(); } } } private void reportClusterStorage() { try { ContentSummary summary = hdfs.getContentSummary(namedspacedPath); long totalUsed = summary.getSpaceConsumed(); long totalFiles = summary.getFileCount(); long totalDirectories = summary.getDirectoryCount(); // cdap hbase tables for (FileStatus fileStatus : hdfs.listStatus(hbasePath, namespacedFilter)) { summary = hdfs.getContentSummary(fileStatus.getPath()); totalUsed += summary.getSpaceConsumed(); totalFiles += summary.getFileCount(); totalDirectories += summary.getDirectoryCount(); } FsStatus hdfsStatus = hdfs.getStatus(); long storageCapacity = hdfsStatus.getCapacity(); long storageAvailable = hdfsStatus.getRemaining(); MetricsCollector collector = getCollector(CLUSTER_METRICS_CONTEXT); LOG.trace("total cluster storage = " + storageCapacity + " total used = " + totalUsed); collector.gauge("resources.total.storage", (storageCapacity / 1024 / 1024)); collector.gauge("resources.available.storage", (storageAvailable / 1024 / 1024)); collector.gauge("resources.used.storage", (totalUsed / 1024 / 1024)); collector.gauge("resources.used.files", totalFiles); collector.gauge("resources.used.directories", totalDirectories); } catch (IOException e) { LOG.warn("Exception getting hdfs metrics", e); } } private class NamespacedPathFilter implements PathFilter { @Override public boolean accept(Path path) { return path.getName().startsWith(namespace); } } private String getMetricContext(TwillRunner.LiveInfo info) { Matcher matcher = APP_NAME_PATTERN.matcher(info.getApplicationName()); if (!matcher.matches()) { return null; } ProgramType type = getType(matcher.group(1)); if (type == null) { return null; } Id.Program programId = Id.Program.from(matcher.group(2), matcher.group(3), matcher.group(4)); return Joiner.on(".").join(programId.getApplicationId(), TypeId.getMetricContextId(type), programId.getId()); } } @Override protected void startUp() throws Exception { resourceReporter.start(); LOG.debug("started distributed program runtime service"); } @Override protected void shutDown() throws Exception { resourceReporter.stop(); } }
41.111111
119
0.679365
83c12b9062fb732141e5ea0e4e47f1c33e78bc98
4,633
/** * @package FirePass - katropine * @author Kristian Beres <[email protected]> * @copyright Katropine (c) 2014, www.katropine.com * @since March 24, 2014 * @licence MIT * * Copyright (c) 2014 Katropine - Kristian Beres, http://www.katropine.com/ * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.katropine.model; import com.katropine.helper.Permission; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * * @author kriss */ @Entity @Table(name="access_control_list") @NamedQueries({ @NamedQuery(name="AccessControlList.getAll", query="SELECT e FROM AccessControlList e"), @NamedQuery(name="AccessControlList.getAllByUserGroupId", query="SELECT e FROM AccessControlList e WHERE e.userGroup.id=:userGroupId ") }) public class AccessControlList implements Serializable{ private int id; private Permission permission; private UserGroup userGroup; private boolean canView; private boolean canInsert; private boolean canUpdate; private boolean canDelete; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") public int getId() { return id; } public void setId(int id) { this.id = id; } @Enumerated(value = EnumType.STRING) @Column(name="permission") public Permission getPermission() { return permission; } public void setPermission(Permission permission) { this.permission = permission; } @ManyToOne(targetEntity = UserGroup.class, cascade = CascadeType.ALL) @JoinColumn(name="usergroup_id") public UserGroup getUserGroup() { return userGroup; } public void setUserGroup(UserGroup userGroup) { this.userGroup = userGroup; } @Basic @Column(name="can_view") public boolean isCanView() { return canView; } public void setCanView(boolean canView) { this.canView = canView; } @Basic @Column(name="can_insert") public boolean isCanInsert() { return canInsert; } public void setCanInsert(boolean canInsert) { this.canInsert = canInsert; } @Basic @Column(name="can_update") public boolean isCanUpdate() { return canUpdate; } public void setCanUpdate(boolean canUpdate) { this.canUpdate = canUpdate; } @Basic @Column(name="can_delete") public boolean isCanDelete() { return canDelete; } public void setCanDelete(boolean canDelete) { this.canDelete = canDelete; } public AccessControlList(){} @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[ID=" + this.getId()); sb.append(", PERMISSION=" + this.getPermission()); sb.append(", USERTYPE=" + this.getUserGroup().getName()); sb.append(", CAN_VIEW=" + this.isCanView()); sb.append(", CAN_INSERT=" + this.isCanInsert()); sb.append(", CAN_UPDATE=" + this.isCanUpdate()); sb.append(", CAN_DELETE=" + this.isCanDelete()); sb.append("]"); return sb.toString(); } }
29.698718
139
0.696309
94c4a1f3f04db81631b232770f259df12084438f
240
package com.study.u.service; import com.study.u.dataobject.Asset; import com.study.u.vo.WithdrawVo; public interface AssetService { Asset findByUsername(String username); void withdraw(String username, WithdrawVo withdrawVo); }
20
58
0.775
86cdae45ba817323bea107d983f376c11c5a350b
169
package hal.phpmetrics.idea.runner; public interface ResultListener { void onSuccess(String output); void onError(String error, String output, int exitCode); }
24.142857
60
0.763314
15bcf825c6a092543c592c831b5ac3d29d1fbb61
9,333
package com.toprako.application_db; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.net.Uri; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.Base64; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import static android.content.Context.LAYOUT_INFLATER_SERVICE; public class ActivityShopAdepter extends ArrayAdapter<String> { Activity activity; private ArrayList<String> numbers,qytpppercent,adress; ArrayList<String> supplier_id,product_id,price,qyt; DataBase db; ArrayList<byte[]> image,slip_img; public ActivityShopAdepter(Context context,Activity activity, ArrayList<String> supplier_id,ArrayList<String> product_id, ArrayList<byte[]> image,ArrayList<String> price,ArrayList<String> qytpppercent, ArrayList<String> adress,ArrayList<byte[]> slip_img,ArrayList<String> qyt,DataBase db) { super(activity,R.layout.activity_shopadepter,supplier_id); this.activity=activity; this.supplier_id=supplier_id; this.product_id=product_id; this.image=image; this.price=price; this.qytpppercent=qytpppercent; this.adress=adress; this.slip_img=slip_img; this.qyt=qyt; this.db=db; numbers=new ArrayList<>(); for (int i = 1; i <= 1000; i++) { numbers.add(String.valueOf(i)); } } @Override public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater inflater = activity.getLayoutInflater(); final View view = inflater.inflate(R.layout.activity_shopadepter, null, true); ImageView ımageView = (ImageView) view.findViewById(R.id.shopadepter_img); TextView shop_adepter_supplier_id = (TextView) view.findViewById(R.id.shopadepter_supplier_id); TextView shop_adepter_prise = (TextView) view.findViewById(R.id.shopadepter_price); TextView shop_adepter_product_id =(TextView) view.findViewById(R.id.shopadepter_productid); final EditText shop_adepter_shippingadres = (EditText) view.findViewById(R.id.shopadepter_adrestext); final Spinner shopadpter_spinner= (Spinner) view.findViewById(R.id.shopadpter_spinner); final TextView shopadepter_payable = (TextView) view.findViewById(R.id.shopadepter_payable); final TextView shopadepter_slip = (TextView) view.findViewById(R.id.shopadepter_slip); Bitmap decodedByte = BitmapFactory.decodeByteArray(image.get(position), 0, image.get(position).length); ımageView.setImageBitmap(decodedByte); final LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(LAYOUT_INFLATER_SERVICE); ArrayAdapter<String> adapterState = new ArrayAdapter<String>(layoutInflater.getContext(), android.R.layout.simple_spinner_item, numbers); adapterState.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); shopadpter_spinner.setAdapter(adapterState); if(!qyt.get(position).equals("")){ int a = Math.round(Float.parseFloat(qyt.get(position))); shopadpter_spinner.setSelection(a-1); } shop_adepter_shippingadres.setText(adress.get(position)); shop_adepter_shippingadres.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { adress.set(position,shop_adepter_shippingadres.getText().toString()); } @Override public void afterTextChanged(Editable s) { } }); shopadpter_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position2, long id) { qytpppercent.set(position, String.valueOf(((Float.parseFloat(price.get(position))) * (Float.parseFloat(String.valueOf(Integer.parseInt(parent.getSelectedItem().toString()))))))); shopadepter_payable.setText("$"+qytpppercent.get(position)); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); shop_adepter_prise.setText("$"+price.get(position)); shop_adepter_product_id.setText(product_id.get(position)); shop_adepter_supplier_id.setText(supplier_id.get(position)); shopadepter_slip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE); final Display display = wm.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); PopupWindow pwindo; final Point size = new Point(); display.getSize(size); final LayoutInflater layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View inflatedView = layoutInflater.inflate(R.layout.upload_view_slip, null,false); final ImageView img = (ImageView) inflatedView.findViewById(R.id.upload_view_slip_img);//upload_view_slip_img Button bt_add = (Button) inflatedView.findViewById(R.id.bt_upload_view_slip_add); final Button bt_delete = (Button) inflatedView.findViewById(R.id.bt_upload_view_slip_delete); Button bt_cancel = (Button) inflatedView.findViewById(R.id.upload_view_slip_save_close); Button bt_view = (Button) inflatedView.findViewById(R.id.upload_view_slip_viewed); pwindo = new PopupWindow(inflatedView, size.x-5,size.y-300, true ); pwindo.setBackgroundDrawable(activity.getResources().getDrawable(android.R.color.white)); bt_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); activity.startActivityForResult(intent, position); Toast.makeText(activity.getApplicationContext(),"Add Succeed",Toast.LENGTH_LONG).show(); } }); bt_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { slip_img.set(position,new byte[1]); Toast.makeText(activity.getApplicationContext(),"Delete Succeed",Toast.LENGTH_LONG).show(); }catch (Exception e){ } } }); final PopupWindow finalPwindo = pwindo; bt_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finalPwindo.dismiss(); } }); bt_view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bitmap decodedByte; if (slip_img.get(position).length > 1) { decodedByte = BitmapFactory.decodeByteArray(slip_img.get(position), 0, slip_img.get(position).length); img.setImageBitmap(decodedByte); } } }); pwindo.setFocusable(true); pwindo.setOutsideTouchable(true); inflatedView.setAnimation(AnimationUtils.loadAnimation(activity, R.anim.up)); pwindo.showAtLocation(inflatedView, Gravity.CENTER, 0,0); } }); return view; } }
46.665
194
0.663024
53e5d28b79f0db301253bfcd3a197e8f1ed657e3
1,917
package com.les4elefantastiq.les4elefantcowork.models; import android.support.annotation.NonNull; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class LiveFeedMessage implements Comparable<LiveFeedMessage> { // -------------- Objects, Variables -------------- // public static final int TYPE_ARRIVAL = 0; public static final int TYPE_TWITTER = 1; public static final int TYPE_COWORKSPACE_ADMIN = 2; public static final int TYPE_COWORKSPACE_OPENING = 3; public String title; public String text; public int type; public String dateTime; public String tweetLink; public String sender; public String coworkerLinkedInId; public Boolean isBirthday; public String pictureUrl; // ----------------- Constructor ------------------ // public LiveFeedMessage(String title, String text, int type, String dateTime, String tweetLink, String sender, String coworkerLinkedInId, Boolean isBirthday, String pictureUrl) { this.title = title; this.text = text; this.type = type; this.tweetLink = tweetLink; this.sender = sender; this.coworkerLinkedInId = coworkerLinkedInId; this.isBirthday = isBirthday; this.pictureUrl = pictureUrl; this.dateTime = dateTime; } // ---------------- Public Methods ---------------- // public Date getDate() { try { return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateTime); } catch (ParseException e) { e.printStackTrace(); return null; } } // ---------------- Private Methods --------------- // // ----------------- Miscellaneous ---------------- // @Override public int compareTo(@NonNull LiveFeedMessage liveFeedMessage) { return - getDate().compareTo(liveFeedMessage.getDate()); } }
29.492308
181
0.616067
eb01905bd49947e751c43cf50c0a1134f4c41d77
2,463
package com.sparrow.weixin.common; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; import java.lang.reflect.InvocationTargetException; /** * Created by yuanzc on 2015/10/23. */ public class MsgFormat { public static final String format(String msg, Object var) { return substitute(var, msg); } static String substitute(Object vars, String expr) { if (StringUtils.isEmpty(expr)) return expr; return replace(expr, vars); } static int skip(char ar[], int start, char sc) { int len = ar.length; for (int i = start; i < len; i++) { if (ar[i] == sc) return i; } return len - 1; } static String replace(String str, Object variables) { char ar[] = str.toCharArray(); int len = ar.length; char c; int i = 0, ns = 0, rl, st; String key, value; StringBuilder sb = new StringBuilder(); while (i < len) { c = ar[i]; switch (c) { case '$': rl = st = i; if (rl > ns) sb.append(str.substring(ns, rl)); if (ar[i + 1] == '{') rl = i + 2; else rl++; i = skip(ar, rl, '}'); if (i > rl) { key = str.substring(rl, i); value = getValue(key, variables); if (!StringUtils.isEmpty(value)) sb.append(value); else sb.append(str.substring(st, i + 1)); } ns = i + 1; break; } i++; } if (len > ns) sb.append(str.substring(ns)); return sb.toString(); } static String getValue(String key, Object object) { try { if ("time".equals(key)) return String.valueOf(System.nanoTime()); return BeanUtils.getSimpleProperty(object, key); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } }
28.976471
64
0.455136
c9b96242ae2a84154ea3112ce13f457c6ca49a2f
9,909
package com.wallpaper.anime.activity; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import com.wallpaper.anime.R; import com.wallpaper.anime.db.SimpleTitleTip; import com.wallpaper.anime.fragment.AcgFragment; import com.wallpaper.anime.fragment.CollectFragment; import com.wallpaper.anime.fragment.FlowerFragment; import com.wallpaper.anime.fragment.Fragment_for3d; import com.wallpaper.anime.fragment.HistoryFragment; import com.wallpaper.anime.menu.DrawerAdapter; import com.wallpaper.anime.menu.DrawerItem; import com.wallpaper.anime.menu.SimpleItem; import com.wallpaper.anime.menu.SpaceItem; import com.wallpaper.anime.util.CircularAnim; import com.wallpaper.slidingrootnav.SlidingRootNav; import com.wallpaper.slidingrootnav.SlidingRootNavBuilder; import org.litepal.LitePal; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity implements DrawerAdapter.OnItemSelectedListener { private static final int POS_DASHBOARD = 0; private static final int POS_ACCOUNT = 1; private static final int POS_MESSAGES = 2; private static final int POS_CART = 3; private static final int POS_3D = 4; private static final int POS_LOGOUT = 6; private static final int PSOS_MOVIE = 5; private String[] screenTitles; private Drawable[] screenIcons; private SlidingRootNav slidingRootNav; private Map<String, Fragment> map = new HashMap<>(); private FragmentManager fragmentManager; private Fragment currentFragment = new Fragment(); private List<Fragment> fragments = new ArrayList<>(); private static final String CURRENT_FRAGMENT = "STATE_FRAGMENT_SHOW"; private int currentIndex = 0; private static final String TAG = "Dy_MainActivity"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); fragmentManager = getSupportFragmentManager(); // LitePal.deleteAll(PictureHistory.class); List<SimpleTitleTip> simpleTitleTips = LitePal.findAll(SimpleTitleTip.class); if (savedInstanceState != null) { // “内存重启”时调用 //获取“内存重启”时保存的索引下标 currentIndex = savedInstanceState.getInt(CURRENT_FRAGMENT, 0); //注意,添加顺序要跟下面添加的顺序一样!!!! fragments.removeAll(fragments); fragments.add(fragmentManager.findFragmentByTag(0 + "")); fragments.add(fragmentManager.findFragmentByTag(1 + "")); fragments.add(fragmentManager.findFragmentByTag(2 + "")); fragments.add(fragmentManager.findFragmentByTag(3 + "")); fragments.add(fragmentManager.findFragmentByTag(4 + "")); //恢复fragment页面 restoreFragment(); } else { //正常启动时调用 fragments.add(AcgFragment.createAcgFragment()); fragments.add(CollectFragment.createAcgFragment()); fragments.add(new HistoryFragment()); fragments.add(new FlowerFragment()); fragments.add(new Fragment_for3d()); } slidingRootNav = new SlidingRootNavBuilder(this) .withToolbarMenuToggle(toolbar) .withMenuOpened(false) .withContentClickableWhenMenuOpened(false) .withSavedState(savedInstanceState) .withMenuLayout(R.layout.menu_left_drawer) .inject(); screenIcons = loadScreenIcons(); screenTitles = loadScreenTitles(); DrawerAdapter adapter = new DrawerAdapter(Arrays.asList( createItemFor(POS_DASHBOARD).setChecked(true), createItemFor(POS_ACCOUNT), createItemFor(POS_MESSAGES), createItemFor(POS_CART), createItemFor(POS_3D), createItemFor(PSOS_MOVIE), new SpaceItem(48), createItemFor(POS_LOGOUT))); adapter.setListener(this); RecyclerView list = findViewById(R.id.list); list.setNestedScrollingEnabled(false); list.setLayoutManager(new LinearLayoutManager(this)); list.setAdapter(adapter); adapter.setSelected(POS_DASHBOARD); } @Override public void onItemSelected(int position) { switch (position) { case POS_LOGOUT: finish(); break; case POS_DASHBOARD: currentIndex = 0; break; case POS_ACCOUNT: currentIndex = 1; break; case POS_MESSAGES: currentIndex = 2; break; case POS_CART: currentIndex = 3; break; case POS_3D: currentIndex = 4; break; case PSOS_MOVIE: CircularAnim.fullActivity(MainActivity.this, (View) slidingRootNav) .colorOrImageRes(R.color.bluesky) //注释掉,因为该颜色已经在App.class 里配置为默认色 .go(new CircularAnim.OnAnimationEndListener() { @Override public void onAnimationEnd() { Intent intent = new Intent(MainActivity.this, Dy_MainActivity.class); startActivity(intent); } }); break; default: break; } showFragment(); // // if (position == POS_LOGOUT) { // // } else if (position == POS_DASHBOARD) { // if (map.containsKey("acg")) { // showFragment(map.get("acg")); // } else { // Log.d(TAG, "onItemSelected: " + "fragment被new了出来"); // slidingRootNav.closeMenu(); // acgFragment = AcgFragment.createAcgFragment(); // map.put("acg", acgFragment); // showFragment(map.get("acg")); // } // if (map.containsKey("collect")) { // showFragment(map.get("collect")); // // } else { // Log.d(TAG, "onItemSelected: " + "collectfragment被new了出来"); // slidingRootNav.closeMenu(); // collectFragment = CollectFragment.createAcgFragment(); // map.put("collect", collectFragment); // showFragment(map.get("collect")); // } // } // } // // private void showFragment(android.support.v4.app.Fragment fragment) { // fragmentManager.beginTransaction() // .replace(R.id.container, fragment) // .commit(); // // } private void showFragment() { FragmentTransaction transaction = fragmentManager.beginTransaction(); //如果之前没有添加过 if (!fragments.get(currentIndex).isAdded()) { transaction .hide(currentFragment) .add(R.id.container, fragments.get(currentIndex), "" + currentIndex); //第三个参数为添加当前的fragment时绑定一个tag } else { transaction .hide(currentFragment) .show(fragments.get(currentIndex)); } currentFragment = fragments.get(currentIndex); transaction.commit(); } private void restoreFragment() { FragmentTransaction mBeginTreansaction = fragmentManager.beginTransaction(); for (int i = 0; i < fragments.size(); i++) { if (i == currentIndex) { mBeginTreansaction.show(fragments.get(i)); } else { mBeginTreansaction.hide(fragments.get(i)); } } mBeginTreansaction.commit(); //把当前显示的fragment记录下来 currentFragment = fragments.get(currentIndex); } private DrawerItem createItemFor(int position) { return new SimpleItem(screenIcons[position], screenTitles[position]) .withIconTint(color(R.color.textColorSecondary)) .withTextTint(color(R.color.textColorPrimary)) .withSelectedIconTint(color(R.color.bule)) .withSelectedTextTint(color(R.color.bule)); } private String[] loadScreenTitles() { return getResources().getStringArray(R.array.ld_activityScreenTitles); } private Drawable[] loadScreenIcons() { TypedArray ta = getResources().obtainTypedArray(R.array.ld_activityScreenIcons); Drawable[] icons = new Drawable[ta.length()]; for (int i = 0; i < ta.length(); i++) { int id = ta.getResourceId(i, 0); if (id != 0) { icons[i] = ContextCompat.getDrawable(this, id); } } ta.recycle(); return icons; } @ColorInt private int color(@ColorRes int res) { return ContextCompat.getColor(this, res); } @Override protected void onSaveInstanceState(Bundle outState) { //“内存重启”时保存当前的fragment名字 outState.putInt(CURRENT_FRAGMENT, currentIndex); super.onSaveInstanceState(outState); } }
36.296703
120
0.617217
157970717f7d54537cf5291762962a94b0ffa44d
7,089
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.perftest.enterprise.util; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import static java.util.Collections.addAll; import static java.util.Collections.emptyList; public abstract class Setting<T> { public static Setting<String> stringSetting( String name ) { return stringSetting( name, null ); } public static Setting<String> stringSetting( String name, String defaultValue ) { return new Setting<String>( name, defaultValue ) { @Override String parse( String value ) { return value; } }; } public static Setting<Long> integerSetting( String name, long defaultValue ) { return new Setting<Long>( name, defaultValue ) { @Override Long parse( String value ) { return Long.parseLong( value ); } }; } public static Setting<Boolean> booleanSetting( String name, boolean defaultValue ) { return new Setting<Boolean>( name, defaultValue ) { @Override Boolean parse( String value ) { return Boolean.parseBoolean( value ); } @Override boolean isBoolean() { return true; } }; } public static <T> Setting<T> restrictSetting( Setting<T> setting, Predicate<? super T> firstPredicate, Predicate<? super T>... morePredicates ) { final Collection<Predicate<? super T>> predicates = new ArrayList<Predicate<? super T>>( 1 + (morePredicates == null ? 0 : morePredicates.length) ); predicates.add( firstPredicate ); addAll( predicates, morePredicates ); return new SettingAdapter<T, T>( setting ) { @Override T adapt( T value ) { for ( Predicate<? super T> predicate : predicates ) { if ( !predicate.matches( value ) ) { throw new IllegalArgumentException( String.format( "'%s' does not match %s", value, predicate ) ); } } return value; } }; } public static <T extends Enum<T>> Setting<T> enumSetting( final Class<T> enumType, String name ) { return new Setting<T>( name, null ) { @Override T parse( String value ) { return Enum.valueOf( enumType, value ); } }; } public static <T extends Enum<T>> Setting<T> enumSetting( String name, T defaultValue ) { final Class<T> enumType = defaultValue.getDeclaringClass(); return new Setting<T>( name, defaultValue ) { @Override T parse( String value ) { return Enum.valueOf( enumType, value ); } }; } public static <T> Setting<List<T>> listSetting( final Setting<T> singleSetting, final List<T> defaultValue ) { return new Setting<List<T>>( singleSetting.name(), defaultValue ) { @Override List<T> parse( String value ) { if ( value.trim().equals( "" ) ) { return emptyList(); } String[] parts = value.split( "," ); List<T> result = new ArrayList<T>( parts.length ); for ( String part : parts ) { result.add( singleSetting.parse( part ) ); } return result; } @Override public String asString( List<T> value ) { StringBuilder result = new StringBuilder(); Iterator<T> iterator = value.iterator(); while ( iterator.hasNext() ) { result.append( singleSetting.asString( iterator.next() ) ); if ( iterator.hasNext() ) { result.append( ',' ); } } return result.toString(); } }; } public static <FROM, TO> Setting<TO> adaptSetting( Setting<FROM> source, final Conversion<? super FROM, TO> conversion ) { return new SettingAdapter<FROM, TO>( source ) { @Override TO adapt( FROM value ) { return conversion.convert( value ); } }; } private final String name; private final T defaultValue; private Setting( String name, T defaultValue ) { this.name = name; this.defaultValue = defaultValue; } @Override public String toString() { return String.format( "Setting[%s]", name ); } public String name() { return name; } T defaultValue() { if ( defaultValue == null ) { throw new IllegalStateException( String.format( "Required setting '%s' not configured.", name ) ); } return defaultValue; } abstract T parse( String value ); boolean isBoolean() { return false; } void validateValue( String value ) { parse( value ); } public String asString( T value ) { return value.toString(); } private static abstract class SettingAdapter<FROM, TO> extends Setting<TO> { private final Setting<FROM> source; SettingAdapter( Setting<FROM> source ) { super( source.name, null ); this.source = source; } @Override TO parse( String value ) { return adapt( source.parse( value ) ); } abstract TO adapt( FROM value ); @Override TO defaultValue() { return adapt( source.defaultValue() ); } } }
28.243028
112
0.519961
08c9f11e492cc18a723888fd195399e9b48e6ea6
4,331
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.apiv1.currentuser; import com.thoughtworks.go.api.ApiController; import com.thoughtworks.go.api.ApiVersion; import com.thoughtworks.go.api.spring.ApiAuthenticationHelper; import com.thoughtworks.go.apiv1.user.representers.UserRepresenter; import com.thoughtworks.go.domain.User; import com.thoughtworks.go.server.service.UserService; import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult; import com.thoughtworks.go.spark.Routes; import com.thoughtworks.go.spark.spring.SparkSpringController; import com.thoughtworks.go.util.TriState; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import spark.Request; import spark.Response; import spark.Spark; import java.util.Collection; import java.util.Map; import static spark.Spark.*; @Component public class CurrentUserController extends ApiController implements SparkSpringController { private final ApiAuthenticationHelper apiAuthenticationHelper; private final UserService userService; @Autowired public CurrentUserController(ApiAuthenticationHelper apiAuthenticationHelper, UserService userService) { super(ApiVersion.v1); this.apiAuthenticationHelper = apiAuthenticationHelper; this.userService = userService; } @Override public String controllerBasePath() { return Routes.CurrentUser.BASE; } @Override public void setupRoutes() { Spark.path(controllerBasePath(), () -> { before("", mimeType, this::setContentType); before("/*", mimeType, this::setContentType); before("", mimeType, this::verifyContentType); before("/*", mimeType, this::verifyContentType); before("", mimeType, apiAuthenticationHelper::checkNonAnonymousUser); before("/*", mimeType, apiAuthenticationHelper::checkNonAnonymousUser); get("", mimeType, this::show); head("", mimeType, this::show); patch("", mimeType, this::update); }); } public String show(Request req, Response res) { User user = userService.findUserByName(currentUserLoginName().toString()); String json = jsonizeAsTopLevelObject(req, writer -> UserRepresenter.toJSON(writer, user)); String etag = etagFor(json); if (fresh(req, etag)) { return notModified(res); } setEtagHeader(res, etag); return json; } public String update(Request req, Response res) { User user = userService.findUserByName(currentUserLoginName().toString()); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); Map map = readRequestBodyAsJSON(req); String checkinAliases = null; if (map.containsKey("checkin_aliases")) { Object newAliases = map.get("checkin_aliases"); if (newAliases instanceof Collection) { checkinAliases = StringUtils.join((Collection) newAliases, ", "); } else if (newAliases instanceof String) { checkinAliases = (String) newAliases; } } TriState emailMe = TriState.from(String.valueOf(map.get("email_me"))); String email = (String) map.get("email"); User serializedUser = userService.save(user, TriState.from(null), emailMe, email, checkinAliases, result); res.status(result.httpCode()); String json = jsonizeAsTopLevelObject(req, writer -> UserRepresenter.toJSON(writer, serializedUser, result)); String etag = etagFor(json); setEtagHeader(res, etag); return json; } }
36.394958
117
0.699377
2ca52ec7e6b49f614a163246b0c503f5afeed426
224
package dev.anhcraft.craftkit.callbacks.bungee; import dev.anhcraft.craftkit.common.callbacks.Callback; import java.util.List; public interface ServerListCallback extends Callback { void call(List<String> servers); }
22.4
55
0.803571
aed7ff98cbde0e6ec70825006e1331ad2fd3b550
1,307
package clinica; public class Chefe extends Funcionario { private String departamento; public Chefe (String _nome, double _identidade, Data _dataDeNascimento, double _salario, Data _dataAdmissao, String _departamento) { //super(_nome, _identidade, _dataDeNascimento, _salario, _dataAdmissao,); setPessoa(_nome, _identidade, _dataDeNascimento); setSalario(_salario); setDataAdmissao(_dataAdmissao); setDepartamento(_departamento); } public Chefe() { Data data = new Data(); setPessoa("Unamed", 0, data); setSalario(0); setDataAdmissao(data); setDepartamento("noDepartament"); } public String getDepartamento() { return this.departamento; } public void setDepartamento(String _departamento) { this.departamento = _departamento; } @Override public double maxEmprestimo() { return super.maxEmprestimo() * 2; } public String toString() { StringBuilder chefe = new StringBuilder(); chefe.append(" | "); chefe.append("Departamento:"); chefe.append(this.getDepartamento()); chefe.append(" | "); return super.toString() + chefe.toString(); } public boolean equals (Object objeto) { Chefe aux = (Chefe) objeto; boolean b = super.equals(objeto); if (aux.getDepartamento() == this.departamento && b==true) return true; else return false; } }
25.627451
133
0.722265
81b35a2e514f691d53ad3c5a0a0435f1c7a7b95a
2,473
package uk.ac.ebi.biosamples.legacy.json.controller; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.hasKey; import static org.springframework.hateoas.MediaTypes.HAL_JSON; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import uk.ac.ebi.biosamples.legacy.json.repository.SampleRepository; @RunWith(SpringRunner.class) @AutoConfigureMockMvc @SpringBootTest public class LegacyExternalLinksControllerIntegrationTest { @MockBean private SampleRepository sampleRepositoryMock; @Autowired private MockMvc mockMvc; @Test public void testExternalLinksIndexReturnPagedResourcesOfExternalLinks() throws Exception { mockMvc.perform(get("/externallinksrelations").accept(HAL_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType("application/hal+json;charset=UTF-8")) .andExpect(jsonPath("$").value( allOf(hasKey("_embedded"), hasKey("_links"), hasKey("page") ))); } @Test @Ignore public void testReturnExternalLinkByLinkName() throws Exception { /*TODO */ } @Test @Ignore public void textExternalLinksContainsExpectedLinks() throws Exception { /* TODO */ } @Test public void testExternalLinksIndexContainsSearchLink() throws Exception { mockMvc.perform(get("/externallinksrelations").accept(HAL_JSON)) .andExpect(jsonPath("$._links").value(hasKey("search"))); } @Test @Ignore public void testExternalLinksSearchContainsFindOneByUrlLink() throws Exception { /*TODO */ } @Test @Ignore public void testFindOneByUrlSearchReturnExternalLink() throws Exception { /*TODO */ } @Test @Ignore public void testOrganizationIsRootField() throws Exception { /*TODO */ } }
29.440476
91
0.78892
c908b5ab707efa85d84726f1da30454edfafc28d
11,403
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.taverna.workbench.views.graph.config; import static java.awt.GridBagConstraints.HORIZONTAL; import static java.awt.GridBagConstraints.NORTHWEST; import static java.awt.GridBagConstraints.RELATIVE; import static java.awt.GridBagConstraints.REMAINDER; import static java.awt.GridBagConstraints.WEST; import static javax.swing.SwingConstants.LEFT; import static org.apache.taverna.workbench.helper.Helper.showHelp; import static org.apache.taverna.workbench.icons.WorkbenchIcons.allportIcon; import static org.apache.taverna.workbench.icons.WorkbenchIcons.blobIcon; import static org.apache.taverna.workbench.icons.WorkbenchIcons.horizontalIcon; import static org.apache.taverna.workbench.icons.WorkbenchIcons.noportIcon; import static org.apache.taverna.workbench.icons.WorkbenchIcons.verticalIcon; import static org.apache.taverna.workbench.views.graph.config.GraphViewConfiguration.ALIGNMENT; import static org.apache.taverna.workbench.views.graph.config.GraphViewConfiguration.ANIMATION_ENABLED; import static org.apache.taverna.workbench.views.graph.config.GraphViewConfiguration.ANIMATION_SPEED; import static org.apache.taverna.workbench.views.graph.config.GraphViewConfiguration.PORT_STYLE; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSlider; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; import org.apache.taverna.workbench.models.graph.Graph.Alignment; import org.apache.taverna.workbench.models.graph.GraphController.PortStyle; /** * UI for GraphViewConfiguration. * * @author David Withers */ public class GraphViewConfigurationPanel extends JPanel { private static final long serialVersionUID = 3779779432230124131L; private static final int ANIMATION_SPEED_MIN = 100; private static final int ANIMATION_SPEED_MAX = 3100; private GraphViewConfiguration configuration; private JRadioButton noPorts; private JRadioButton allPorts; private JRadioButton blobs; private JRadioButton vertical; private JRadioButton horizontal; private JCheckBox animation; private JLabel animationSpeedLabel; private JSlider animationSpeedSlider; public GraphViewConfigurationPanel(GraphViewConfiguration configuration) { this.configuration = configuration; GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridbag); // Title describing what kind of settings we are configuring here JTextArea descriptionText = new JTextArea( "Default settings for the workflow diagram"); descriptionText.setLineWrap(true); descriptionText.setWrapStyleWord(true); descriptionText.setEditable(false); descriptionText.setFocusable(false); descriptionText.setBorder(new EmptyBorder(10, 10, 10, 10)); JLabel defaultLayoutLabel = new JLabel("Service display"); noPorts = new JRadioButton(); allPorts = new JRadioButton(); blobs = new JRadioButton(); JLabel noPortsLabel = new JLabel("Name only", noportIcon, LEFT); JLabel allPortsLabel = new JLabel("Name and ports", allportIcon, LEFT); JLabel blobsLabel = new JLabel("No text", blobIcon, LEFT); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(noPorts); buttonGroup.add(allPorts); buttonGroup.add(blobs); JLabel defaultAlignmentLabel = new JLabel("Diagram alignment"); vertical = new JRadioButton(); horizontal = new JRadioButton(); JLabel verticalLabel = new JLabel("Vertical", verticalIcon, LEFT); JLabel horizontalLabel = new JLabel("Horizontal", horizontalIcon, LEFT); ButtonGroup alignmentButtonGroup = new ButtonGroup(); alignmentButtonGroup.add(horizontal); alignmentButtonGroup.add(vertical); animation = new JCheckBox("Enable animation"); animationSpeedLabel = new JLabel("Animation speed"); animationSpeedSlider = new JSlider(ANIMATION_SPEED_MIN, ANIMATION_SPEED_MAX); animationSpeedSlider.setMajorTickSpacing(500); animationSpeedSlider.setMinorTickSpacing(100); animationSpeedSlider.setPaintTicks(true); animationSpeedSlider.setPaintLabels(true); animationSpeedSlider.setInverted(true); animationSpeedSlider.setSnapToTicks(true); Hashtable<Integer, JLabel> labelTable = new Hashtable<>(); labelTable.put(new Integer(ANIMATION_SPEED_MIN), new JLabel("Fast")); labelTable.put(new Integer( ((ANIMATION_SPEED_MAX - ANIMATION_SPEED_MIN) / 2) + ANIMATION_SPEED_MIN), new JLabel("Medium")); labelTable.put(new Integer(ANIMATION_SPEED_MAX), new JLabel("Slow")); animationSpeedSlider.setLabelTable(labelTable); animation.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { boolean animationEnabled = animation.isSelected(); animationSpeedLabel.setEnabled(animationEnabled); animationSpeedSlider.setEnabled(animationEnabled); } }); // Set current configuration values setFields(configuration); c.anchor = WEST; c.gridx = 0; c.gridwidth = REMAINDER; c.weightx = 1d; c.weighty = 0d; c.fill = HORIZONTAL; add(descriptionText, c); c.insets = new Insets(10, 0, 10, 0); add(defaultLayoutLabel, c); c.insets = new Insets(0, 20, 0, 0); c.gridwidth = 1; c.weightx = 0d; add(noPorts, c); c.insets = new Insets(0, 5, 0, 0); c.gridx = RELATIVE; add(noPortsLabel, c); c.insets = new Insets(0, 10, 0, 0); add(allPorts, c); c.insets = new Insets(0, 5, 0, 0); add(allPortsLabel, c); c.insets = new Insets(0, 10, 0, 0); add(blobs, c); c.insets = new Insets(0, 5, 0, 0); c.gridwidth = REMAINDER; c.weightx = 1d; add(blobsLabel, c); // alignment c.insets = new Insets(20, 0, 10, 0); c.gridx = 0; add(defaultAlignmentLabel, c); c.insets = new Insets(0, 20, 0, 0); c.gridx = 0; c.gridwidth = 1; c.weightx = 0d; add(vertical, c); c.insets = new Insets(0, 5, 0, 0); c.gridx = RELATIVE; add(verticalLabel, c); c.insets = new Insets(0, 10, 0, 0); add(horizontal, c); c.insets = new Insets(0, 5, 0, 0); c.gridwidth = REMAINDER; c.weightx = 1d; add(horizontalLabel, c); // animation c.gridx = 0; c.gridwidth = REMAINDER; c.insets = new Insets(20, 0, 10, 0); add(animation, c); c.insets = new Insets(0, 20, 0, 0); add(animationSpeedLabel, c); c.insets = new Insets(0, 20, 10, 30); c.anchor = NORTHWEST; c.weighty = 0d; add(animationSpeedSlider, c); // Buttons c.gridx = 0; c.insets = new Insets(0, 20, 10, 30); c.anchor = NORTHWEST; c.weighty = 1d; add(createButtonPanel(), c); } /** * Create the panel with the buttons. */ @SuppressWarnings("serial") private JPanel createButtonPanel() { final JPanel panel = new JPanel(); /** * The helpButton shows help about the current component */ JButton helpButton = new JButton(new AbstractAction("Help") { @Override public void actionPerformed(ActionEvent arg0) { showHelp(panel); } }); panel.add(helpButton); /** * The resetButton changes the property values shown to those * corresponding to the configuration currently applied. */ JButton resetButton = new JButton(new AbstractAction("Reset") { @Override public void actionPerformed(ActionEvent arg0) { setFields(configuration); } }); panel.add(resetButton); /** * The applyButton applies the shown field values to the * {@link HttpProxyConfiguration} and saves them for future. */ JButton applyButton = new JButton(new AbstractAction("Apply") { @Override public void actionPerformed(ActionEvent arg0) { applySettings(); setFields(configuration); } }); panel.add(applyButton); return panel; } /** * Save the currently set field values to the {@link GraphViewConfiguration} * . Also apply those values to the currently running Taverna. */ private void applySettings() { // Service display if (noPorts.isSelected()) { configuration.setProperty(PORT_STYLE, PortStyle.NONE.toString()); } else if (allPorts.isSelected()) { configuration.setProperty(PORT_STYLE, PortStyle.ALL.toString()); } else if (blobs.isSelected()) { configuration.setProperty(PORT_STYLE, PortStyle.BLOB.toString()); } // Diagram alignment if (vertical.isSelected()) { configuration.setProperty(ALIGNMENT, Alignment.VERTICAL.toString()); } else if (horizontal.isSelected()) { configuration.setProperty(ALIGNMENT, Alignment.HORIZONTAL.toString()); } // Animation and its speed if (animation.isSelected()) { configuration.setProperty(ANIMATION_ENABLED, String.valueOf(true)); } else { configuration.setProperty(ANIMATION_ENABLED, String.valueOf(false)); } int speed = animationSpeedSlider.getValue(); configuration.setProperty(ANIMATION_SPEED, String.valueOf(speed)); } /** * Set the shown configuration field values to those currently in use (i.e. * last saved configuration). */ private void setFields(GraphViewConfiguration configurable) { PortStyle portStyle = PortStyle.valueOf(configurable .getProperty(PORT_STYLE)); if (portStyle.equals(PortStyle.NONE)) { noPorts.setSelected(true); } else if (portStyle.equals(PortStyle.ALL)) { allPorts.setSelected(true); } else { blobs.setSelected(true); } Alignment alignment = Alignment.valueOf(configurable .getProperty(ALIGNMENT)); if (alignment.equals(Alignment.VERTICAL)) { vertical.setSelected(true); } else { horizontal.setSelected(true); } boolean animationEnabled = Boolean.parseBoolean(configurable .getProperty(ANIMATION_ENABLED)); animation.setSelected(animationEnabled); Integer animationSpeed = Integer.valueOf(configurable .getProperty(ANIMATION_SPEED)); if (animationSpeed > ANIMATION_SPEED_MAX) { animationSpeed = ANIMATION_SPEED_MAX; } else if (animationSpeed < ANIMATION_SPEED_MIN) { animationSpeed = ANIMATION_SPEED_MIN; } animationSpeedSlider.setValue(animationSpeed); animationSpeedSlider.setEnabled(animationEnabled); animationSpeedLabel.setEnabled(animationEnabled); } // for testing only public static void main(String[] args) { JDialog dialog = new JDialog(); dialog.add(new GraphViewConfigurationPanel(null)); dialog.setModal(true); dialog.setSize(500, 400); dialog.setVisible(true); System.exit(0); } }
31.941176
103
0.746909
48b68f5864badb0dbd57c3277642c4eed63cad4a
4,349
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CRDelinquentAccountProcedureInitiateOutputModelDelinquentAccountProcedureInstanceRecord; import javax.validation.Valid; /** * CRDelinquentAccountProcedureExecuteOutputModel */ public class CRDelinquentAccountProcedureExecuteOutputModel { private CRDelinquentAccountProcedureInitiateOutputModelDelinquentAccountProcedureInstanceRecord delinquentAccountProcedureInstanceRecord = null; private String delinquentAccountProcessingSchedule = null; private String delinquentAccountProcedureExecuteActionTaskReference = null; private Object delinquentAccountProcedureExecuteActionTaskRecord = null; private String executeRecordReference = null; private Object executeResponseRecord = null; /** * Get delinquentAccountProcedureInstanceRecord * @return delinquentAccountProcedureInstanceRecord **/ public CRDelinquentAccountProcedureInitiateOutputModelDelinquentAccountProcedureInstanceRecord getDelinquentAccountProcedureInstanceRecord() { return delinquentAccountProcedureInstanceRecord; } public void setDelinquentAccountProcedureInstanceRecord(CRDelinquentAccountProcedureInitiateOutputModelDelinquentAccountProcedureInstanceRecord delinquentAccountProcedureInstanceRecord) { this.delinquentAccountProcedureInstanceRecord = delinquentAccountProcedureInstanceRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details the schedule of actions to be applied to the delinquent account * @return delinquentAccountProcessingSchedule **/ public String getDelinquentAccountProcessingSchedule() { return delinquentAccountProcessingSchedule; } public void setDelinquentAccountProcessingSchedule(String delinquentAccountProcessingSchedule) { this.delinquentAccountProcessingSchedule = delinquentAccountProcessingSchedule; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to a Delinquent Account Procedure instance execute service call * @return delinquentAccountProcedureExecuteActionTaskReference **/ public String getDelinquentAccountProcedureExecuteActionTaskReference() { return delinquentAccountProcedureExecuteActionTaskReference; } public void setDelinquentAccountProcedureExecuteActionTaskReference(String delinquentAccountProcedureExecuteActionTaskReference) { this.delinquentAccountProcedureExecuteActionTaskReference = delinquentAccountProcedureExecuteActionTaskReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The execute service call consolidated processing record * @return delinquentAccountProcedureExecuteActionTaskRecord **/ public Object getDelinquentAccountProcedureExecuteActionTaskRecord() { return delinquentAccountProcedureExecuteActionTaskRecord; } public void setDelinquentAccountProcedureExecuteActionTaskRecord(Object delinquentAccountProcedureExecuteActionTaskRecord) { this.delinquentAccountProcedureExecuteActionTaskRecord = delinquentAccountProcedureExecuteActionTaskRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the execute transaction/record * @return executeRecordReference **/ public String getExecuteRecordReference() { return executeRecordReference; } public void setExecuteRecordReference(String executeRecordReference) { this.executeRecordReference = executeRecordReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: Details of the execute action service response * @return executeResponseRecord **/ public Object getExecuteResponseRecord() { return executeResponseRecord; } public void setExecuteResponseRecord(Object executeResponseRecord) { this.executeResponseRecord = executeResponseRecord; } }
38.149123
213
0.829386
9a5f60e0b83eb4d5d09c77da152e0b30279549af
1,222
package cz.cuni.mff.cgg.teichmaa.chaosultra.cudarenderer.modules; import com.google.gson.JsonObject; import cz.cuni.mff.cgg.teichmaa.chaosultra.rendering.model.DefaultFractalModel; import cz.cuni.mff.cgg.teichmaa.chaosultra.util.JsonHelpers; public class ModuleNewtonIterations extends ModuleNewtonGeneric { public static final String COLOR_MAGNIFIER_PARAM_NAME = "colorMagnifier"; public ModuleNewtonIterations() { super("newton_iterations", "newton colored by iterations"); } @Override public void setFractalCustomParameters(String params) { super.setFractalCustomParameters(params); JsonObject json = JsonHelpers.parse(params); if(json.has(COLOR_MAGNIFIER_PARAM_NAME)){ int colorMagnifier = json.get(COLOR_MAGNIFIER_PARAM_NAME).getAsInt(); writeToConstantMemory(COLOR_MAGNIFIER_PARAM_NAME, colorMagnifier); } } @Override protected void supplyDefaultValues(DefaultFractalModel model) { super.supplyDefaultValues(model); String params = "{\"" + COLOR_MAGNIFIER_PARAM_NAME + "\": 11," + model.getFractalCustomParams().substring(1); model.setFractalCustomParams(params); } }
34.914286
81
0.726678
8302466a5d60bad906c56200d0689db1cfe3ebc2
1,370
package com.briefbytes.remoteplayer.videoplayer; import com.briefbytes.remoteplayer.utils.OsUtils; import java.io.*; /** * OMXPlayer is controlled by writing to the stdin */ public class OmxPlayer implements VideoPlayer { private Writer writer; protected OmxPlayer() { } @Override public void play(File video) throws IOException { quit(); Process process = OsUtils.exec("omxplayer", "-b", "-o", "hdmi", video.getAbsolutePath()); OutputStream stdin = process.getOutputStream(); writer = new BufferedWriter(new OutputStreamWriter(stdin)); } @Override public void toggleSubtitles() { write('s'); } @Override public void togglePause() { write('p'); } @Override public void quit() { write('q'); if (writer != null) { try { writer.close(); writer = null; } catch (IOException e) { System.out.println("Error closing stream. " + e.getMessage()); } } } private void write(char c) { if (writer != null) { try { writer.write(c); writer.flush(); } catch (IOException e) { System.out.println("Error writing to stream. " + e.getMessage()); } } } }
23.220339
97
0.539416
ef839f5c2350c139a94ff543ddbfc5a013685fab
3,329
package edu.msu.cse.eventual.server; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import edu.msu.cse.dkvf.ClientMessageAgent; import edu.msu.cse.dkvf.DKVFServer; import edu.msu.cse.dkvf.Storage.StorageStatus; import edu.msu.cse.dkvf.config.ConfigReader; import edu.msu.cse.dkvf.metadata.Metadata.ClientReply; import edu.msu.cse.dkvf.metadata.Metadata.GetMessage; import edu.msu.cse.dkvf.metadata.Metadata.GetReply; import edu.msu.cse.dkvf.metadata.Metadata.PutReply; import edu.msu.cse.dkvf.metadata.Metadata.Record; import edu.msu.cse.dkvf.metadata.Metadata.ReplicateMessage; import edu.msu.cse.dkvf.metadata.Metadata.ServerMessage; public class EventualServer extends DKVFServer { ConfigReader cnfReader; int numOfDatacenters; int dcId; int pId; public EventualServer(ConfigReader cnfReader) { super(cnfReader); this.cnfReader = cnfReader; HashMap<String, List<String>> protocolProperties = cnfReader.getProtocolProperties(); numOfDatacenters = new Integer(protocolProperties.get("num_of_datacenters").get(0)); dcId = new Integer(protocolProperties.get("dc_id").get(0)); pId = new Integer(protocolProperties.get("p_id").get(0)); } public void handleClientMessage(ClientMessageAgent cma) { if (cma.getClientMessage().hasGetMessage()) { handleGetMessage(cma); } else if (cma.getClientMessage().hasPutMessage()) { handlePutMessage(cma); } } private void handlePutMessage(ClientMessageAgent cma) { Record.Builder builder = Record.newBuilder(); builder.setValue(cma.getClientMessage().getPutMessage().getValue()); builder.setUt(System.currentTimeMillis()); Record rec = builder.build(); StorageStatus ss = insert(cma.getClientMessage().getPutMessage().getKey(), rec); ClientReply cr = null; if (ss == StorageStatus.SUCCESS) { cr = ClientReply.newBuilder().setStatus(true).setPutReply(PutReply.newBuilder().setUt(rec.getUt())).build(); } else { cr = ClientReply.newBuilder().setStatus(false).build(); } cma.sendReply(cr); sendReplicateMessages(cma.getClientMessage().getPutMessage().getKey(), rec); } private void sendReplicateMessages(String key, Record recordToReplicate) { ServerMessage sm = ServerMessage.newBuilder().setReplicateMessage(ReplicateMessage.newBuilder().setKey(key).setRec(recordToReplicate)).build(); for (int i = 0; i < numOfDatacenters; i++) { if (i == dcId) continue; String id = i + "_" + pId; protocolLOGGER.finer(MessageFormat.format("Sendng replicate message to {0}: {1}", id, sm.toString())); sendToServerViaChannel(id, sm); } } private void handleGetMessage(ClientMessageAgent cma) { GetMessage gm = cma.getClientMessage().getGetMessage(); List<Record> result = new ArrayList<>(); StorageStatus ss = read(gm.getKey(), p -> { return true; }, result); ClientReply cr = null; if (ss == StorageStatus.SUCCESS) { Record rec = result.get(0); cr = ClientReply.newBuilder().setStatus(true).setGetReply(GetReply.newBuilder().setValue(rec.getValue())).build(); } else { cr = ClientReply.newBuilder().setStatus(false).build(); } cma.sendReply(cr); } public void handleServerMessage(ServerMessage sm) { Record newRecord = sm.getReplicateMessage().getRec(); insert(sm.getReplicateMessage().getKey(), newRecord); } }
34.677083
145
0.744968
326e893a5337bab17df9a197003ea91ef497d981
5,050
// -*- mode: java; coding: utf-8; indent-tabs-mode: nil; c-basic-offset: 4 -*- // vim: set ft=c fenc=utf-8 ts=4 sw=4 et : // javac nbody.java // time java -server nbody 50000000 public final class nbody { public static void main(String[] args) { Body[] bodies = new Body[] { // sun Body.sun(), Body.jupiter(), Body.saturn(), Body.uranus(), Body.neptune() }; int n = args.length > 0 ? Integer.parseInt(args[0]) : 0; offset(bodies); System.out.printf("%.9f\n", energy(bodies)); for (int i = 0; i < n; ++i) { advance(bodies, 0.01); } System.out.printf("%.9f\n", energy(bodies)); } private static void offset(Body[] bodies) { double px = 0; double py = 0; double pz = 0; for (Body b : bodies) { double m = b.mass; px += b.vx * m; py += b.vy * m; pz += b.vz * m; } bodies[0].offset(px, py, pz); } private static double energy(Body[] bodies) { double e = 0; for (int i = 0; i < bodies.length; ++i) { Body bi = bodies[i]; e += bi.mass * (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) / 2.0; for (int j = i + 1; j < bodies.length; ++j) { Body bj = bodies[j]; double dx = bi.x - bj.x; double dy = bi.y - bj.y; double dz = bi.z - bj.z; double d = Math.sqrt(dx * dx + dy * dy + dz * dz); e -= (bi.mass * bj.mass) / d; } } return e; } private static void advance(Body[] bodies, double dt) { for (int i = 0; i < bodies.length; ++i) { Body bi = bodies[i]; for (int j = i + 1; j < bodies.length; ++j) { Body bj = bodies[j]; double dx = bi.x - bj.x; double dy = bi.y - bj.y; double dz = bi.z - bj.z; double d2 = dx * dx + dy * dy + dz * dz; double mag = dt / (d2 * Math.sqrt(d2)); double mj = bj.mass * mag; bi.vx -= dx * mj; bi.vy -= dy * mj; bi.vz -= dz * mj; double mi = bi.mass * mag; bj.vx += dx * mi; bj.vy += dy * mi; bj.vz += dz * mi; } } for (Body b : bodies) { b.x += dt * b.vx; b.y += dt * b.vy; b.z += dt * b.vz; } } private static final class Body { private static final double PI = 3.141592653589793; private static final double SOLAR_MASS = 4 * PI * PI; private static final double DAYS_PER_YEAR = 365.24; public double x, y, z, vx, vy, vz, mass; static Body sun(){ Body b = new Body(); b.mass = SOLAR_MASS; return b; } static Body jupiter(){ Body b = new Body(); b.x = 4.84143144246472090e+00; b.y = -1.16032004402742839e+00; b.z = -1.03622044471123109e-01; b.vx = 1.66007664274403694e-03 * DAYS_PER_YEAR; b.vy = 7.69901118419740425e-03 * DAYS_PER_YEAR; b.vz = -6.90460016972063023e-05 * DAYS_PER_YEAR; b.mass = 9.54791938424326609e-04 * SOLAR_MASS; return b; } static Body saturn(){ Body b = new Body(); b.x = 8.34336671824457987e+00; b.y = 4.12479856412430479e+00; b.z = -4.03523417114321381e-01; b.vx = -2.76742510726862411e-03 * DAYS_PER_YEAR; b.vy = 4.99852801234917238e-03 * DAYS_PER_YEAR; b.vz = 2.30417297573763929e-05 * DAYS_PER_YEAR; b.mass = 2.85885980666130812e-04 * SOLAR_MASS; return b; } static Body uranus(){ Body b = new Body(); b.x = 1.28943695621391310e+01; b.y = -1.51111514016986312e+01; b.z = -2.23307578892655734e-01; b.vx = 2.96460137564761618e-03 * DAYS_PER_YEAR; b.vy = 2.37847173959480950e-03 * DAYS_PER_YEAR; b.vz = -2.96589568540237556e-05 * DAYS_PER_YEAR; b.mass = 4.36624404335156298e-05 * SOLAR_MASS; return b; } static Body neptune(){ Body b = new Body(); b.x = 1.53796971148509165e+01; b.y = -2.59193146099879641e+01; b.z = 1.79258772950371181e-01; b.vx = 2.68067772490389322e-03 * DAYS_PER_YEAR; b.vy = 1.62824170038242295e-03 * DAYS_PER_YEAR; b.vz = -9.51592254519715870e-05 * DAYS_PER_YEAR; b.mass = 5.15138902046611451e-05 * SOLAR_MASS; return b; } void offset(double px, double py, double pz) { vx = -px / SOLAR_MASS; vy = -py / SOLAR_MASS; vz = -pz / SOLAR_MASS; } } }
31.962025
81
0.46495
7a406a85dbc66812d97a6eb1fd0266d96a1e0482
1,178
package com.weatherapp.viewmodel; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MediatorLiveData; import com.weatherapp.models.MapRequestResponse; import com.weatherapp.repository.RemoteDataRepository; public class CityNameViewModel extends AndroidViewModel { private final MediatorLiveData<MapRequestResponse> mObservableForecast; public CityNameViewModel(Application application, double lat, double lon) { super(application); mObservableForecast = new MediatorLiveData<>(); // set by default null, until we get data from the database. mObservableForecast.setValue(null); String s = String.valueOf(lat) + "," + String.valueOf(lon); LiveData<MapRequestResponse> cities = RemoteDataRepository.getRepoInstance().getCitynameFromLatLong(s); mObservableForecast.addSource(cities, mObservableForecast::setValue); } /** * Expose the LiveData Products query so the UI can observe it. */ public LiveData<MapRequestResponse> getCityName() { return mObservableForecast; } }
30.205128
111
0.748727
937259ffed2e16615608071e921f94adffcc7cf1
3,299
package com.knowledge.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.knowledge.body.SubjectFieldReq; import com.knowledge.body.vo.SubjectFieldVo; import com.knowledge.dao.SubjectFieldDao; import com.knowledge.domain.Response; import com.knowledge.entity.SubjectField; import com.knowledge.entity.SubjectRelation; import com.knowledge.repo.SubjectFieldRepo; import com.knowledge.repo.SubjectRelationRepo; import com.knowledge.service.SubjectFieldService; @Service public class SubjectFieldServiceImpl implements SubjectFieldService{ @Autowired private SubjectRelationRepo subjectRelationRepo; @Autowired private SubjectFieldRepo subjectFieldRepo; @Autowired private SubjectFieldDao subjectFieldDao; /** * 查询元数据管理左边菜单栏下所对应的主题域信息 */ @Override public List<SubjectFieldVo> querySubjectInfo(SubjectFieldReq req) { List<SubjectFieldVo> list = subjectFieldDao.getSubjectInfo(req); if(null == list || list.isEmpty()) { return null; } return list; } /** * 新增or修改主题域 * @param req * @return */ @Transactional @Override public Response saveSubjectField(SubjectFieldReq req) { SubjectField subject = new SubjectField(); //存入主题域信息 List<SubjectField> subjectList = new ArrayList<SubjectField>(); //存入主题域关系信息 List<SubjectRelation> subjecRelationtList = new ArrayList<SubjectRelation>(); for(Map<String, String> enumMap : req.getEnumList()) { //[{"elementId":"1","type":"1","sort":"1"}] Long elementId = Long.parseLong(enumMap.get("elementId")); String type = enumMap.get("type"); String sort = enumMap.get("sort"); //编辑情况下,页面点保存后删除数据,重新保存 if(null != req.getId()) { //这里根据主题域id删除信息 subjectFieldRepo.deleteById(req.getId()); } //类别 subject.setCategory(req.getCategory()); //主题域名称 subject.setSubjectName(req.getSubjectName()); //知识标题 subject.setKnowledgeTitle(req.getKnowledgeTitle()); //创建人 subject.setCreateBy("admin"); //创建时间 subject.setCreatedTime(new Date()); subjectList.add(subject); subjectFieldRepo.saveAll(subjectList); if(null != subject) { //元数据/主题域关系表 SubjectRelation subjectRelation= new SubjectRelation(); //编辑情况下,页面点保存后删除数据,重新保存 if(null != req.getId()) { //这里根据主题域id-外键删除信息 subjectRelationRepo.deleteBySubjectId(req.getId()); } //主题域ID subjectRelation.setSubjectId(subject.getId()); //元数据ID subjectRelation.setElementId(elementId); //区分数据来源:1.元数据、2.元数据组 subjectRelation.setType(type); //排序 subjectRelation.setSort(sort); //创建人 subjectRelation.setCreateBy("admin"); //创建时间 subjectRelation.setCreatedTime(new Date()); subjecRelationtList.add(subjectRelation); subjectRelationRepo.saveAll(subjecRelationtList); } } return Response.ok("00","新增/修改主题域成功"); } /** * 查询主题域信息(下拉框)--针对新增元数据/新增元数据组页面 * */ @Override public List<SubjectField> querySubjectField() { List<SubjectField> list = subjectFieldRepo.getSubjectField(); if(null == list || list.isEmpty()) { return null; } return list; } }
23.06993
79
0.7184