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 |
|---|---|---|---|---|---|
051dbd7c7547a0d35456dd1d93866c76aa7e42b6 | 4,241 | /*
* 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 DAO;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import models.*;
import org.hibernate.Session;
/**
*
* @author Aluno
*/
public class HibernatePopulate {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
INSERIRALUNO();
}
public static void INSERIRALUNO(){
Session actualSession = NewHibernateUtil.getSessionFactory().openSession();
//Inicializa a trasição
actualSession.beginTransaction();
//Cria uma query
Query q = actualSession.createQuery("from Pessoa");
//Pega os resultados da query em uma lista
List<Pessoa> pessoas = q.getResultList();
//Cria uma nova pessoa
Date data = new Date();
data.setDate(10);
data.setMonth(8);
data.setYear(1992);/*
data.setHours(18);
data.setMinutes(0);
data.setSeconds(0);*/
Pessoa pessoa = new Pessoa();
pessoa.setNomePessoa("Waldiskleyson");
pessoa.setCpfPessoa("123.456.789-10");
pessoa.setMatriculaPessoa("1234567890");
pessoa.setDtnascimento(data);
Contato contao = new Contato();
contao.setCelularContato("9999-8888");
contao.setEmailContato("waldin@milk.shake");
contao.setTelefoneContato("3333-1010");
contao.setPessoa(pessoa);
Endereco endereco = new Endereco();
endereco.setBairroEndereco("Bairro Celona");
endereco.setCep("12340-580");
endereco.setCidadeEndereco("Morro");
endereco.setComplementoEndereco("Atras dá boate Drags Albergs");
endereco.setLogradouroEndereco("Rua das Manas");
endereco.setNumeroEndereco(1124);
endereco.setPessoa(pessoa);
Aluno aluno = new Aluno();
aluno.setPessoa(pessoa);
Modulo modes = new Modulo();
modes.setDescricaoModulo("IV");
Turno turno = new Turno();
turno.setDescricaoTurno("Matutino");
Curso curso = new Curso();
curso.setDescricaoCurso("Necromancia");
curso.setModulo(modes);
curso.setTurno(turno);
AlunoHasCurso ahc = new AlunoHasCurso();
ahc.setAluno(aluno);
ahc.setCurso(curso);
//Salva o objeto na sessão
actualSession.saveOrUpdate(pessoa);
actualSession.saveOrUpdate(contao);
actualSession.saveOrUpdate(endereco);
actualSession.saveOrUpdate(aluno);
actualSession.saveOrUpdate(turno);
actualSession.saveOrUpdate(modes);
actualSession.saveOrUpdate(curso);
actualSession.saveOrUpdate(ahc);
actualSession.getTransaction().commit();
//Fecha a conexão com o banco
actualSession.close();
NewHibernateUtil.getSessionFactory().close();
}
public static void INSERIR(){
//Faz a chamada da sessão
Session actualSession = NewHibernateUtil.getSessionFactory().openSession();
//Inicializa a trasição
actualSession.beginTransaction();
//Cria os objeto
Date data = new Date();
data.setDate(10);
data.setMonth(8);
data.setYear(1992);/*
data.setHours(18);
data.setMinutes(0);
data.setSeconds(0);*/
Pessoa pessoa = new Pessoa();
pessoa.setNomePessoa("Waldiskleyson");
pessoa.setCpfPessoa("123.456.789-10");
pessoa.setMatriculaPessoa("1234567890");
pessoa.setDtnascimento(data);
//Salva o objeto na sessão
actualSession.save(pessoa);
//Confirma a transação
actualSession.getTransaction().commit();
//Fecha a conexão com o banco
actualSession.close();
NewHibernateUtil.getSessionFactory().close();
}
}
| 29.657343 | 83 | 0.599623 |
fd0e33b3641ec38c1e8886e396f5ec154705c23c | 2,739 | package ru.job4j.pro.tree;
import org.junit.Test;
import java.util.Iterator;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* This class tests Tree class.
*
* @author Kutsykh Vasily (mailto:basil135@mail.ru)
* @version $Id
* @since 3.10.2017
*/
public class TreeTest {
/**
* method tests Tree of integer.
*/
@Test
public void whenFillTreeThenIteratorGetRightElements() {
Tree<Integer> tree = new Tree<>();
tree.add(1, 2);
tree.add(1, 17);
tree.add(1, 22);
tree.add(2, 53);
tree.add(2, 77);
tree.add(77, 81);
Integer[] expected = {1, 2, 17, 22, 53, 77, 81};
Integer[] actual = new Integer[7];
Iterator<Integer> iter = tree.iterator();
int count = 0;
while (iter.hasNext()) {
actual[count++] = iter.next();
}
assertThat(expected, is(actual));
}
/**
* method test isBinary method of class Tree by positive scenario.
*/
@Test
public void whenIsBinaryPositiveScenarioThenTrue() {
Tree<Integer> tree = new Tree<>();
tree.add(1, 2);
tree.add(1, 17);
tree.add(2, 53);
tree.add(2, 77);
tree.add(77, 81);
tree.add(77, 82);
tree.add(53, 89);
boolean expected = true;
boolean actual = tree.isBinary();
assertThat(expected, is(actual));
}
/**
* method test isBinary method of class Tree by negative scenario.
*/
@Test
public void whenIsBinaryNegativeScenarioThenFalse() {
Tree<Integer> tree = new Tree<>();
tree.add(1, 2);
tree.add(1, 17);
tree.add(2, 53);
tree.add(2, 77);
tree.add(77, 81);
tree.add(77, 82);
tree.add(53, 89);
tree.add(53, 143);
tree.add(53, 73);
boolean expected = false;
boolean actual = tree.isBinary();
assertThat(expected, is(actual));
}
/**
* method tests search binary tree.
*/
@Test
public void whenAddFifteenNumbersToSearchBinaryTreeThenIteratorsReturnWriteOrder() {
SearchBinaryTree<Integer> sbt = new SearchBinaryTree<>();
Integer[] toAdd = {9, 1, 5, 13, 10, 4, 7, 14, 15, 12, 3, 2, 11, 6, 8, 0};
for (Integer in: toAdd) {
sbt.add(in);
}
Integer[] expected = {9, 1, 13, 0, 5, 10, 14, 4, 7, 12, 15, 3, 6, 8, 11, 2};
Integer[] actual = new Integer[16];
Iterator<Integer> iter = sbt.iterator();
int i = 0;
while (iter.hasNext()) {
actual[i++] = iter.next();
}
assertThat(actual, is(expected));
}
}
| 20.908397 | 88 | 0.540343 |
bd5f2aaf73b757163d71398996b2c8552a172104 | 7,079 | /*
* Copyright 2004-2010 the Seasar Foundation and the Others.
*
* 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 example.dao;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.List;
import javax.annotation.Generated;
import javax.sql.DataSource;
import org.seasar.doma.internal.jdbc.command.DeleteCommand;
import org.seasar.doma.internal.jdbc.command.EntityIterationHandler;
import org.seasar.doma.internal.jdbc.command.EntityResultListHandler;
import org.seasar.doma.internal.jdbc.command.EntitySingleResultHandler;
import org.seasar.doma.internal.jdbc.command.InsertCommand;
import org.seasar.doma.internal.jdbc.command.ScriptCommand;
import org.seasar.doma.internal.jdbc.command.SelectCommand;
import org.seasar.doma.internal.jdbc.command.UpdateCommand;
import org.seasar.doma.internal.jdbc.dao.AbstractDao;
import org.seasar.doma.internal.jdbc.query.AutoDeleteQuery;
import org.seasar.doma.internal.jdbc.query.AutoInsertQuery;
import org.seasar.doma.internal.jdbc.query.AutoUpdateQuery;
import org.seasar.doma.internal.jdbc.query.SqlFileScriptQuery;
import org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery;
import org.seasar.doma.internal.jdbc.util.SqlFileUtil;
import org.seasar.doma.jdbc.IterationCallback;
import org.seasar.doma.jdbc.SelectOptions;
import example.entity.Emp;
import example.entity._Emp;
/**
* @author taedium
*
*/
@Generated("")
public class EmpDaoImpl extends AbstractDao implements EmpDao {
public EmpDaoImpl() {
super(new ExampleConfig());
}
public EmpDaoImpl(Connection connection) {
super(new ExampleConfig(), connection);
}
public EmpDaoImpl(DataSource dataSource) {
super(new ExampleConfig(), dataSource);
}
@Override
public Emp selectById(Integer id, SelectOptions option) {
SqlFileSelectQuery query = new SqlFileSelectQuery();
query.setConfig(config);
query.setSqlFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"selectById"));
query.addParameter("id", Integer.class, id);
query.setOptions(option);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("selectById");
query.prepare();
SelectCommand<Emp> command = new SelectCommand<Emp>(query,
new EntitySingleResultHandler<Emp>(_Emp.getSingletonInternal()));
return command.execute();
}
@Override
public List<Emp> selectByNameAndSalary(String name, BigDecimal salary,
SelectOptions option) {
SqlFileSelectQuery query = new SqlFileSelectQuery();
query.setConfig(config);
query.setSqlFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"selectByNameAndSalary"));
query.addParameter("name", String.class, name);
query.addParameter("salary", BigDecimal.class, salary);
query.setOptions(option);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("selectByNameAndSalary");
query.prepare();
SelectCommand<List<Emp>> command = new SelectCommand<List<Emp>>(query,
new EntityResultListHandler<Emp>(_Emp.getSingletonInternal()));
return command.execute();
}
@Override
public List<Emp> selectByExample(Emp emp) {
SqlFileSelectQuery query = new SqlFileSelectQuery();
query.setConfig(config);
query.setSqlFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"selectByNameAndSalary"));
query.addParameter("emp", Emp.class, emp);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("selectByNameAndSalary");
query.prepare();
SelectCommand<List<Emp>> command = new SelectCommand<List<Emp>>(query,
new EntityResultListHandler<Emp>(_Emp.getSingletonInternal()));
return command.execute();
}
@Override
public int insert(Emp entity) {
AutoInsertQuery<Emp> query = new AutoInsertQuery<Emp>(
_Emp.getSingletonInternal());
query.setConfig(config);
query.setEntity(entity);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("insert");
query.prepare();
InsertCommand command = new InsertCommand(query);
return command.execute();
}
@Override
public int update(Emp entity) {
AutoUpdateQuery<Emp> query = new AutoUpdateQuery<Emp>(
_Emp.getSingletonInternal());
query.setConfig(config);
query.setEntity(entity);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("update");
query.prepare();
UpdateCommand command = new UpdateCommand(query);
return command.execute();
}
@Override
public int delete(Emp entity) {
AutoDeleteQuery<Emp> query = new AutoDeleteQuery<Emp>(
_Emp.getSingletonInternal());
query.setConfig(config);
query.setEntity(entity);
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("update");
query.prepare();
DeleteCommand command = new DeleteCommand(query);
return command.execute();
}
@Override
public Integer iterate(IterationCallback<Integer, Emp> callback) {
SqlFileSelectQuery query = new SqlFileSelectQuery();
query.setConfig(config);
query.setSqlFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"selectById"));
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("selectById");
query.prepare();
SelectCommand<Integer> command = new SelectCommand<Integer>(query,
new EntityIterationHandler<Integer, Emp>(
_Emp.getSingletonInternal(), callback));
return command.execute();
}
@Override
public void execute() {
SqlFileScriptQuery query = new SqlFileScriptQuery();
query.setConfig(config);
query.setScriptFilePath(SqlFileUtil.buildPath("example.dao.EmpDao",
"selectById"));
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("selectById");
query.prepare();
ScriptCommand command = new ScriptCommand(query);
command.execute();
}
}
| 38.895604 | 82 | 0.671846 |
2f55913258bc473b29eec89141472f30733c93e8 | 441 | package com.bakerbeach.market.shop.model.forms;
import org.hibernate.validator.constraints.NotEmpty;
public class SimpleNameRegistrationForm extends AbstractRegistrationForm {
@NotEmpty(message = "register.error.first_name")
public String getRegisterFirstName() {
return registerFirstName;
}
@NotEmpty(message = "register.error.last_name")
public String getRegisterLastName() {
return registerLastName;
}
}
| 24.5 | 75 | 0.764172 |
05e54fdffe54d786e144aeb278cd535c5d797b48 | 923 | package main.java.sort.partition;
/**
* Created by Administrator on 2017/9/6.
*/
public class PartitionApp {
public static void main(String[] args) {
int maxSize = 16; // array size
ArrayPar arr; // reference to array
arr = new ArrayPar(maxSize); // create the array
for(int j=0; j<maxSize; j++) { // fill array with random numbers
long n = (int) (java.lang.Math.random() * 199);
arr.insert(n);
}
arr.display(); // display unsorted array
long pivot = 99; // pivot value
System.out.print("Pivot is " + pivot);
int size = arr.size();
int partDex = arr.partitionIt(0, size-1, pivot); // partition array
System.out.println(", Partition is at index " + partDex);
arr.display(); // display partitioned array
}
}
| 30.766667 | 82 | 0.530878 |
d5017d82fb7a62ad9529ac1db66162557a48cbd8 | 1,494 | package com.moesol.url;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class Config {
private boolean useWindowsTrust = false;
private String defaultCertificateName = null;
public boolean isUseWindowsTrust() {
return useWindowsTrust;
}
public void setUseWindowsTrust(boolean useWindowsTrust) {
this.useWindowsTrust = useWindowsTrust;
}
public String getDefaultCertificateName() {
return defaultCertificateName;
}
public void setDefaultCertificateName(String defaultCertificateName) {
this.defaultCertificateName = defaultCertificateName;
}
public static Config loadFromUserHome() {
String userHome = System.getProperty("user.home");
if (userHome == null) { return new Config(); }
try {
return doLoadProperties(userHome);
} catch (IOException e) {
e.printStackTrace(System.err);
return new Config();
}
}
private static Config doLoadProperties(String userHome) throws IOException, FileNotFoundException {
File file = new File(userHome, ".mscapi.properties");
if (!file.exists()) { return new Config(); }
try (FileInputStream fis = new FileInputStream(file)) {
Properties p = new Properties();
p.load(fis);
Config result = new Config();
result.setDefaultCertificateName(p.getProperty("default.cert.name"));
result.setUseWindowsTrust(Boolean.parseBoolean(p.getProperty("use.windows.trust")));
return result;
}
}
}
| 29.88 | 100 | 0.752343 |
7a621412a6085af132476cfef3ca10e45a9ed13e | 514 | package cache;
import java.util.List;
public interface CacheDao<T> {
boolean save(String key, String value);
boolean save(String key, String value, int expire);
boolean save(String key, T entity);
boolean delete(String key);
long delete(String... keys);
boolean update(String key, String value);
boolean update(String key, String value, int expire);
boolean update(String key, T entity);
String get(String key);
T getEntity(String key);
List<T> getList(String key);
}
| 28.555556 | 57 | 0.692607 |
0ce6f19a0d8b3a54e51905a1e1e664fc9203bbcf | 1,322 | /*
* Copyright 2017 Alex Thomson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.lxgaming.equity;
import io.github.lxgaming.equity.configuration.Config;
import io.github.lxgaming.equity.managers.CommandManager;
import io.github.lxgaming.equity.util.Reference;
import io.github.lxgaming.equity.util.TerminalConsoleAppender;
public class Main {
public static void main(String[] args) {
Thread.currentThread().setName("Main Thread");
Equity equity = new Equity();
equity.loadEquity();
TerminalConsoleAppender.buildTerminal(Reference.APP_NAME, equity.getConfig().map(Config::isJlineOverride).orElse(true));
while (equity.isRunning()) {
TerminalConsoleAppender.readline().ifPresent(CommandManager::process);
}
}
} | 36.722222 | 128 | 0.728442 |
98411c88d71a0eeaab116ae56e62e442423bc864 | 2,536 | /*
* Copyright 2015 the original author or 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
*
* 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.gradle.platform.base;
import org.gradle.api.Incubating;
import org.gradle.model.internal.core.UnmanagedStruct;
import java.util.Collection;
/**
* A container for dependency specifications.
*/
@Incubating @UnmanagedStruct
public interface DependencySpecContainer {
/**
* Defines a new dependency, based on a project path. The returned dependency can be mutated.
*
* @param path the project path
*
* @return a mutable dependency, added to this container
*/
ProjectDependencySpecBuilder project(String path);
/**
* Defines a new dependency, based on a library name. The returned dependency can be mutated.
*
* @param name of the library
*
* @return a mutable dependency, added to this container
*/
ProjectDependencySpecBuilder library(String name);
/**
* Defines a new module dependency, based on a module id or a simple name. The returned dependency can be mutated.
*
* @param moduleIdOrName of the module
*
* @return a mutable module dependency, added to this container
*/
ModuleDependencySpecBuilder module(String moduleIdOrName);
/**
* Defines a new module dependency, based on a module group name. The returned dependency can be mutated.
*
* @param name of the module group
*
* @return a mutable module dependency, added to this container
*/
ModuleDependencySpecBuilder group(String name);
/**
* Returns an immutable view of dependencies stored in this container.
*
* @return an immutable view of dependencies. Each dependency in the collection is itself immutable.
*/
Collection<DependencySpec> getDependencies();
/**
* Returns true if this container doesn't hold any dependency.
*
* @return true if this container doesn't contain any dependency specification.
*/
boolean isEmpty();
}
| 31.7 | 118 | 0.700315 |
e8306c1a470a828751a387e258a25873829cf869 | 10,405 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.console.navtree;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.ToolTipManager;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.jboss.console.manager.interfaces.SimpleTreeNodeMenuEntry;
import org.jboss.console.manager.interfaces.TreeAction;
import org.jboss.console.manager.interfaces.TreeNodeMenuEntry;
import org.jboss.console.manager.interfaces.impl.SeparatorTreeNodeMenuEntry;
/**
* Holder of the browser tree and associated handlers. Can then be embedded
* in any code such as applet code. Specific actions are handled
* through a TreeContext callback object used to communicate between this object
* and its container.
*
* @see org.jboss.console.navtree.TreeContext
* @see AppletBrowser
*
* @author <a href="mailto:sacha.labourey@cogito-info.ch">Sacha Labourey</a>.
* @version $Revision: 57191 $
*
*/
public class AdminTreeBrowser
{
TreeContext ctx = null;
ConsoleTreeModel tm = null;
TreeCellRenderer cellRenderer = null;
TreeSelectionListener selectionListener = null;
OpenNodeAccounter openNodeAccounter = null;
String webHost = null;
public static final String RIGHT_FRAME_NAME = "right";
/** Creates new form AppletTreeBrowser */
public AdminTreeBrowser (TreeContext ctx) throws Exception
{
this.ctx = ctx;
tm = new ConsoleTreeModel (ctx);
cellRenderer = new TreeCellRenderer (ctx);
//selectionListener = new SelectionListener ();
initComponents ();
openNodeAccounter = new OpenNodeAccounter(getTree());
//getTree().addTreeSelectionListener (selectionListener);
getTree().addMouseListener (new PopupMenuMgr());
//getTree().addTreeExpansionListener (openNodeAccounter);
getTree().getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);
ToolTipManager.sharedInstance().registerComponent(getTree());
}
public void refreshTree (boolean force)
{
try
{
this.tm.refreshTree (force);
}
catch (Exception displayed)
{
displayed.printStackTrace();
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents()//GEN-BEGIN:initComponents
{
tree = new javax.swing.JTree();
tree.setCellRenderer(getCellRenderer());
tree.setModel(getTreeModel());
tree.setAutoscrolls(true);
}//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTree tree;
// End of variables declaration//GEN-END:variables
public TreeCellRenderer getCellRenderer ()
{
return this.cellRenderer;
}
public TreeModel getTreeModel ()
{
return this.tm;
}
public TreeSelectionListener getSelectionListener ()
{
return this.selectionListener;
}
public JTree getTree ()
{
return this.tree;
}
/*
* Don't use SelectionListener as I am not able to detect clicks on an
* already selected tree node i.e. no refresh is possible by clicking!
* => Instead I use the PopupMenuMgr below to do the work
*
public class SelectionListener implements TreeSelectionListener
{
public SelectionListener () {}
public void valueChanged (TreeSelectionEvent e)
{
System.out.println ("in valueChanged");
Object node = getTree ().getLastSelectedPathComponent ();
if (node == null) return;
if (node instanceof NodeWrapper)
{
NodeWrapper who = (NodeWrapper)node;
TreeAction act = who.getAssociatedAction ();
ctx.doAdminTreeAction (act);
}
}
}
*/
// -----------------------------------
public class OpenNodeAccounter
implements javax.swing.event.TreeExpansionListener, javax.swing.event.TreeModelListener
{
protected java.util.TreeSet openNodes = new java.util.TreeSet ();
public OpenNodeAccounter (JTree tree)
{
tree.getModel ().addTreeModelListener (this);
}
public void treeExpanded(javax.swing.event.TreeExpansionEvent event)
{
openNodes.add (((NodeWrapper)(event.getSource ())).getPath ());
//System.out.println (event.getPath().getClass ().toString ());
//openNodes.add (event.getPath ());
}
public void treeCollapsed(javax.swing.event.TreeExpansionEvent event)
{
openNodes.remove (((NodeWrapper)(event.getSource ())).getPath ());
//openNodes.remove (event.getPath ());
}
public void treeNodesChanged (javax.swing.event.TreeModelEvent e)
{
/*
java.util.Iterator iter = openNodes.iterator ();
while (iter.hasNext ())
{
javax.swing.tree.TreePath path = (javax.swing.tree.TreePath)iter.next ();
tree.expandPath (path);
}
*/
/*
RootWrapper root = (RootWrapper)tm.getRoot ();
int max = root.getChildCount ();
for (int i=0; i<max ; i++)
{
StdNodeWrapper son = (StdNodeWrapper)root.getChild (i);
if (openNodes.contains (son.getPath ()))
recursivelyOpen (son);
}
*/
}
public void recursivelyOpen (NodeWrapper son)
{
}
public void treeNodesInserted (javax.swing.event.TreeModelEvent e){}
public void treeNodesRemoved (javax.swing.event.TreeModelEvent e){}
public void treeStructureChanged (javax.swing.event.TreeModelEvent e) { }
}
// -----------------------------------
public class PopupMenuMgr extends MouseAdapter
{
HashMap menus = new HashMap ();
public PopupMenuMgr (){}
public void mousePressed( MouseEvent e )
{
mouseReleased(e);
}
public void mouseReleased( MouseEvent e )
{
TreePath loc = getTree().getPathForLocation(e.getX(), e.getY());
if (loc == null)//Path not found because
return;//right click does not occur on a node or a leaf
getTree().setSelectionPath (loc);
if ( e.isPopupTrigger())
{
Object node = getTree ().getLastSelectedPathComponent ();
if (node == null) return;
JPopupMenu popup = null;
if (menus.containsKey (node))
{
popup = (JPopupMenu)menus.get (node);
}
else if (node instanceof NodeWrapper)
{
NodeWrapper who = (NodeWrapper)node;
TreeNodeMenuEntry[] entries = who.getMenuEntries ();
if (entries != null && entries.length > 0)
{
popup = new JPopupMenu();
popup.setOpaque(true);
popup.setLightWeightPopupEnabled(true);
menus.put (node, popup);
// we must lazy-create the menu
//
for (int i=0; i<entries.length; i++)
{
if (entries[i] instanceof SeparatorTreeNodeMenuEntry)
{
popup.addSeparator ();
}
else if (entries[i] instanceof SimpleTreeNodeMenuEntry)
{
final SimpleTreeNodeMenuEntry txt = (SimpleTreeNodeMenuEntry)entries[i];
JMenuItem mi = new JMenuItem(txt.getText ());
mi.addActionListener ( new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
ctx.doPopupMenuAction (txt);
}
}
);
popup.add(mi);
}
}
}
}
if (popup != null)
popup.show( (JComponent)e.getSource(), e.getX(), e.getY() );
}
else
{
Object node = getTree ().getLastSelectedPathComponent ();
if (node != null && node instanceof NodeWrapper)
{
NodeWrapper who = (NodeWrapper)node;
TreeAction act = who.getAssociatedAction ();
ctx.doAdminTreeAction (act);
}
}
}
}
}
| 32.617555 | 96 | 0.58222 |
744ff897d2c864d887adb3c2f38e90f914450eaf | 1,879 | package thito.nodejfx.parameter;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.paint.*;
import thito.nodejfx.NodeParameter;
import thito.nodejfx.parameter.converter.TypeCaster;
import thito.nodejfx.parameter.type.JavaParameterType;
public class ObjectParameter extends NodeParameter implements UserInputParameter<Object> {
private ObjectProperty<Object> value = new SimpleObjectProperty<>();
private ObjectProperty<TypeCaster<Object>> typeCaster = new SimpleObjectProperty<>(TypeCaster.PASSTHROUGH_TYPE_CASTER);
private BooleanProperty disable = new SimpleBooleanProperty();
private Label label;
public ObjectParameter(String text) {
this();
label.setTextFill(Color.WHITE);
label.setText(text);
}
public ObjectParameter() {
this.label = new Label();
getContainer().getChildren().add(label);
getInputType().set(JavaParameterType.getType(Object.class));
getOutputType().set(JavaParameterType.getType(Object.class));
}
@Override
public Node getInputComponent() {
return null;
}
@Override
public void setName(String name) {
label.setText(name);
}
public Label getLabel() {
return label;
}
@Override
public BooleanProperty disableInputProperty() {
return disable;
}
@Override
protected Pos defaultAlignment() {
return Pos.CENTER;
}
@Override
public ObjectProperty<Object> valueProperty() {
return value;
}
@Override
public ObjectProperty<TypeCaster<Object>> typeCaster() {
return typeCaster;
}
}
| 28.044776 | 123 | 0.711016 |
806723009f6398e7e0eb6f13ddb574ba7d5a8045 | 1,599 | /**
* Copyright 2017 3TUSK, et al.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.tritusk.beerelease;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.item.ItemTossEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@Mod(modid = "beerelease", name = "Bee Release", version = "1.0.0", useMetadata = true)
public enum BeeRelease {
INSTANCE;
@Mod.InstanceFactory
public static BeeRelease getInstance() {
return INSTANCE;
}
BeeRelease() {
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onItemToss(ItemTossEvent event) {
if (event.getEntityItem().getEntityItem().getItem().getClass().getName().equals(BEE)) {
event.setCanceled(true);
}
}
private static final String BEE = "forestry.apiculture.items.ItemBeeGE"; // It is the same since ForestryMC 3.1
}
| 34.021277 | 115 | 0.724203 |
d3323d1826cc7a1817d63888381c9d6b44a03111 | 3,371 | package com.intellij.vssSupport.ui;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.UnnamedConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.VcsDirectoryMapping;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.ui.DocumentAdapter;
import com.intellij.vssSupport.VssBundle;
import com.intellij.vssSupport.VssRootSettings;
import com.intellij.vssSupport.commands.VssCommandAbstract;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
public class VssRootConfigurable implements UnnamedConfigurable
{
private final static String VSS_PROJECT_PREFIX = "$/";
private final Project project;
private final VcsDirectoryMapping myMapping;
private JPanel myPanel;
private JComboBox myComboBox1;
private JButton btnTest;
public VssRootConfigurable( final VcsDirectoryMapping mapping, final Project project )
{
myMapping = mapping;
this.project = project;
// Add custom editor so that we can control the shallow validness of the
// string describing the vss project path.
BasicComboBoxEditor editor = new BasicComboBoxEditor(){
{
editor.getDocument().addDocumentListener( new DocumentAdapter() {
protected void textChanged(final DocumentEvent e)
{
btnTest.setEnabled( validProject() );
}
});
}
};
myComboBox1.setEditor( editor );
btnTest.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent e )
{
List<VcsException> errors = new ArrayList<>();
VssCommandAbstract cmd = new CPCommand( project, errors );
cmd.execute();
if( errors.size() == 0 )
Messages.showInfoMessage( project, VssBundle.message( "message.project.valid" ), VssBundle.message( "message.title.check.status" ) );
else
Messages.showErrorDialog( project, VssBundle.message( "message.project.not.valid" ), VssBundle.message( "message.title.check.status" ) );
}
});
VssRootSettings rootSettings = (VssRootSettings) mapping.getRootSettings();
if (rootSettings != null)
myComboBox1.setSelectedItem( rootSettings.getVssProject() );
btnTest.setEnabled( validProject() );
}
public JComponent createComponent() { return myPanel; }
public boolean isModified() { return false; }
public void apply() {
myMapping.setRootSettings( new VssRootSettings( (String)myComboBox1.getSelectedItem() ) );
}
public void reset() {}
private boolean validProject()
{
String text = (String)myComboBox1.getEditor().getItem();
return (text != null) && text.startsWith( VSS_PROJECT_PREFIX );
}
private class CPCommand extends VssCommandAbstract
{
public CPCommand( Project project, List <VcsException> errors )
{
super( project, errors );
}
public void execute()
{
String vssPath = (String)myComboBox1.getSelectedItem();
List<String> options = formOptions( "Properties", "-R-", vssPath, _I_Y_OPTION );
runProcess( options, project.getBaseDir().getPath() );
}
}
}
| 33.04902 | 147 | 0.716108 |
33b6a2f97acc04db91502f1a68fb79778aa339ac | 1,583 | package seedu.address.model.person;
import static java.util.Objects.requireNonNull;
import static seedu.address.commons.util.AppUtil.checkArgument;
/**
* Represents a Student's tuition rate in the address book.
*/
public class Rate {
public static final String MESSAGE_CONSTRAINTS =
"Rate should not be negative and can "
+ "at most be up to 2 decimal places. You also cannot enter a decimal point without"
+ "following it up with at least one digit.";
public static final String VALIDATION_REGEX = "\\d+(\\.\\d{1,2})?";
public final String value;
/**
* Constructs a {@code Rate}
*
* @param rate A valid tuition per hour rate.
*/
public Rate(String rate) {
requireNonNull(rate);
checkArgument(isValidRate(rate), MESSAGE_CONSTRAINTS);
value = rate;
}
/**
* Returns true if a given string is a valid tuition rate.
*
* @param test String representing rate to be tested.
* @return A boolean value.
*/
public static boolean isValidRate(String test) {
return test.matches(VALIDATION_REGEX);
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Rate // instanceof handles nulls
&& value.equals(((Rate) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| 27.77193 | 104 | 0.617814 |
ad1fe67e478f587f5aafb768ebd40878f7a08307 | 1,302 | package il.ac.hac.cs.customlistener;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
/**
* A number streamer is an object that creates random integers on 1-second delays.
*
* Other components may listen on number generation events via the NumberGeneratedListener interface.
*/
public class NumberStreamer {
public static final int DELAY = 1000;
public static final int PERIOD = 1000;
private final ArrayList<NumberGeneratedListener> listeners = new ArrayList<>();
/**
* Notice that generateNumber is an instance of an anonymous class, not a class.
*/
private final TimerTask generateNumber = new TimerTask() {
@Override
public void run() {
int randNum = (int)(Math.random() * 10);
for (NumberGeneratedListener listener : listeners) {
listener.numberGenerated(randNum);
}
}
};
public void stream() {
Timer timer = new Timer();
timer.schedule(generateNumber, DELAY, PERIOD);
}
/**
* This method is used to add a listener to the streamer.
* @param listener this is the listener to add.
*/
public void addNumberGeneratedListener(NumberGeneratedListener listener) {
listeners.add(listener);
}
}
| 28.933333 | 101 | 0.66129 |
3ed64f9da2e99779087dc967fcfcac01c8ad423e | 3,345 | package email.com.gmail.cosmoconsole.forge.photoniccraft.common.registrar;
import java.util.ArrayList;
import email.com.gmail.cosmoconsole.forge.photoniccraft.ModPhotonicCraft;
import email.com.gmail.cosmoconsole.forge.photoniccraft.client.renderer.block.PrismBakedModel;
import email.com.gmail.cosmoconsole.forge.photoniccraft.common.PhotonicBlocks;
import email.com.gmail.cosmoconsole.forge.photoniccraft.common.PhotonicItems;
import email.com.gmail.cosmoconsole.forge.photoniccraft.common.block.BlockPrism;
import email.com.gmail.cosmoconsole.forge.photoniccraft.common.item.ItemPhotonicCoupler;
import email.com.gmail.cosmoconsole.forge.photoniccraft.util.NameAndItem;
import email.com.gmail.cosmoconsole.forge.photoniccraft.util.PhotonicUtils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.DefaultStateMapper;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ModelLoader;
/**
* PhotonicCraft's models for items and item blocks as well as other possible models are registered here.
*/
public class PhotonicModelRegistrar {
public static ArrayList<NameAndItem> modelItemList = new ArrayList<>();
public static void registerModels() {
for (NameAndItem it : PhotonicItems.blockItemList)
ModelLoader.setCustomModelResourceLocation(it.getItem(), 0,
new ModelResourceLocation(it.getItem().getRegistryName(), "inventory"));
for (NameAndItem it : modelItemList)
ModelLoader.setCustomModelResourceLocation(it.getItem(), 0,
new ModelResourceLocation(it.getItem().getRegistryName(), "inventory"));
for (int i = 0; i < 16; ++i)
ModelLoader.setCustomModelResourceLocation(PhotonicItems.photonicCoupler, i,
new ModelResourceLocation(
PhotonicItems.photonicCoupler.getRegistryName() + "_" + ItemPhotonicCoupler.colors[i],
"inventory"));
PhotonicItems.blockItemList.clear();
modelItemList.clear();
}
public static void bakePrismModels(IRegistry<ModelResourceLocation, IBakedModel> registry) {
StateMapperBase b = new DefaultStateMapper();
PrismBakedModel.glassSprite = Minecraft.getMinecraft().getTextureMapBlocks()
.getAtlasSprite(new ResourceLocation(ModPhotonicCraft.MODID_MINECRAFT, "blocks/glass").toString());
PrismBakedModel.prismSprite = Minecraft.getMinecraft().getTextureMapBlocks()
.registerSprite(new ResourceLocation(ModPhotonicCraft.MODID, "blocks/prism_top"));
PrismBakedModel.initTextures();
for (IBlockState validState : PhotonicBlocks.prism.getBlockState().getValidStates()) {
String variant = b.getPropertyString(validState.getProperties());
ModelResourceLocation prismLoc = new ModelResourceLocation(PhotonicBlocks.prism.getRegistryName(), variant);
registry.putObject(prismLoc,
new PrismBakedModel(registry.getObject(prismLoc),
(new int[] { 0, 0, 2, 0, 3, 1 })[PhotonicUtils.readDirectionPropertyAsInteger(validState,
BlockPrism.FACING)]));
}
}
private PhotonicModelRegistrar() {
}
}
| 51.461538 | 112 | 0.787444 |
429a87a5a0263b4a7d141f2e7713b23e8f003700 | 2,495 | package com.tianyu.customgps;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button mBtnCity;
Button mBtnNext;
SharedPreferencesUtil mPreferencesUtil;
// GPS标记
private boolean mGpsFlag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
getGpsposition();
}
private void initView() {
mPreferencesUtil = new SharedPreferencesUtil(this);
mBtnCity = (Button) findViewById(R.id.btn_main_city);
// 设置城市名
mBtnCity.setText(mPreferencesUtil.getcityname());
System.out.println(mPreferencesUtil.getcityname());
mBtnNext = (Button) findViewById(R.id.btn_main_next);
mBtnNext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
RepairActivity.class);
intent.putExtra("Longitude", mPreferencesUtil.getLongitude());
intent.putExtra("Latitude", mPreferencesUtil.getLatitude());
intent.putExtra("username", mPreferencesUtil.getcityname()
.trim());
startActivity(intent);
}
});
}
/**
* Handler
*/
@SuppressLint("HandlerLeak")
private final Handler handler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MessageBox.GET_QUERYGPS_SU: {// 定位
GpsModel gpsbean = (GpsModel) msg.obj;
mPreferencesUtil.saveString("cityname", gpsbean.getCity_name());
SaveShareThread saveapthread = new SaveShareThread("cityname",
mPreferencesUtil.getcityname(), mPreferencesUtil);
saveapthread.execute();
SaveShareThread saveapthreadef = new SaveShareThread(
"gps_Longitude", gpsbean.getLongitude() + "",
mPreferencesUtil);
saveapthreadef.execute();
SaveShareThread saveapthreadg = new SaveShareThread(
"gps_Latitude", gpsbean.getLatitude() + "",
mPreferencesUtil);
saveapthreadg.execute();
}
break;
default:
break;
}
};
};
/**
* 获取gps坐标
*/
private void getGpsposition() {
mGpsFlag = false;
GetGpsThread mGpsThread = new GetGpsThread(this, handler, "50",
mPreferencesUtil.getUserName());
mGpsThread.start();
}
}
| 25.721649 | 68 | 0.72505 |
1f8668774fea6b0ee3f0372b8adbdb31f1ee28e1 | 8,143 | package com.friedrice.cubus.activity;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.friedrice.cubus.R;
import com.friedrice.cubus.util.Bus;
import com.friedrice.cubus.util.MapUtils;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class BusActivity extends AppCompatActivity implements OnMapReadyCallback {
Bundle extras;
String routeName;
String busId;
double busLat = 0;
double busLon = 0;
double stopLat = 0;
double stopLon = 0;
float direction;
String shapeId;
String stopName;
String eta;
String color;
FrameLayout layout;
Snackbar snackbar;
private GoogleMap mMap;
MapUtils mapUtils = new MapUtils();
Activity activity = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bus);
layout = (FrameLayout) findViewById(R.id.busActivityFrame);
initializeBusValues();
setupActionBar();
refreshData();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.busMap);
assert mapFragment != null;
mapFragment.getMapAsync(this);
}
public void initializeBusValues() {
Intent intent = getIntent();
extras = intent.getExtras();
stopLat = extras.getDouble("stopLat");
stopLon = extras.getDouble("stopLon");
stopName = extras.getString("stopName");
Bus bus = (Bus) extras.get("bus");
if(bus != null) {
busId = bus.busId;
routeName = bus.routeName;
eta = bus.eta;
color = bus.color;
}
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(routeName);
}
}
/**
* Refreshes the bus's location, heading, and route on the map.
*/
private void refreshData() {
Uri urlUri = Uri.parse("https://developer.cumtd.com/api/v2.2/json/GetVehicle")
.buildUpon()
.appendQueryParameter("key", getResources().getString(R.string.api_key))
.appendQueryParameter("vehicle_id", busId)
.build();
String url = urlUri.toString();
final RequestQueue queue = Volley.newRequestQueue(this);
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray vehiclesArray = response.getJSONArray("vehicles");
JSONObject vehicle = vehiclesArray.getJSONObject(0); //0 is the only vehicle
JSONObject trip = vehicle.getJSONObject("trip");
shapeId = trip.getString("shape_id");
mapUtils.drawRouteShape(mMap, shapeId, activity, null, color);
drawBusMarker(vehicle, trip);
createBusSnackBar();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(busLat, busLon), 16));
drawStopMarker();
} catch (JSONException e) {e.printStackTrace();}
}
}, new Response.ErrorListener() {@Override public void onErrorResponse(VolleyError error) {}});
queue.add(request);
}
/**
* Draws an arrow representing the bus. The arrow heading depends on the heading obtained
* in the cumtd api call.
*/
private void drawBusMarker(JSONObject vehicle, JSONObject trip) throws JSONException {
switch(trip.getString("direction")){
case "North":
direction = 0;
break;
case "East":
direction = 90;
break;
case "South":
direction = 180;
break;
case "West":
direction = 270;
break;
default:
direction = 0;
}
JSONObject location = vehicle.getJSONObject("location");
busLat = location.getDouble("lat");
busLon = location.getDouble("lon");
BitmapDescriptor arrow = BitmapDescriptorFactory.fromResource(R.drawable.arrowbig);
mMap.addGroundOverlay(new GroundOverlayOptions()
.image(arrow)
.bearing(direction)
.position(new LatLng(busLat, busLon), 100));
}
/**
* Creates a SnackBar at the bottom of the screen that displays bus status
*/
private void createBusSnackBar() {
String unit = "Minute";
if(Integer.parseInt(eta) > 1 || Integer.parseInt(eta) == 0) {
unit = "Minutes";
}
snackbar = Snackbar.make(layout,
routeName + " Arrives in " + eta + " " + unit,
Snackbar.LENGTH_INDEFINITE);
snackbar.show();
}
/**
* Places a marker that represents the stop that the user was looking at at the previous
* screen.
*
* May display all stops on this route at a future time
*/
private void drawStopMarker() {
Marker stopMarker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(stopLat, stopLon))
.title(stopName));
stopMarker.setTag(extras.getString("stopId"));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(getBaseContext(), DeparturesActivity.class);
intent.putExtra("title", marker.getTitle());
intent.putExtra("id", (String) marker.getTag());
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_bus, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.refresh_bus:
if(mMap != null) mMap.clear();
if(snackbar != null) snackbar.dismiss();
refreshData();
return true;
}
return(super.onOptionsItemSelected(item));
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
}
| 34.504237 | 132 | 0.62741 |
58fe0aba28d688a0b02476a5ce9b88aeaffc87a1 | 296 | package org.fluxtream.core.services.impl;
import org.fluxtream.core.domain.AbstractFacet;
/**
*
* @author Candide Kemmler (candide@fluxtream.com)
*/
public interface FieldConverter {
String convertField(final long guestId, AbstractFacet facet);
String getBodytrackChannelName();
} | 19.733333 | 65 | 0.760135 |
60daa3b926227b9fc8136c8a7a3503da4a39c1ca | 7,573 | /*
* Copyright (c) 2008-2017, Hazelcast, 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.hazelcast.config;
import com.hazelcast.nio.serialization.BinaryInterface;
import javax.cache.configuration.CacheEntryListenerConfiguration;
import javax.cache.configuration.Factory;
import javax.cache.expiry.ExpiryPolicy;
import javax.cache.integration.CacheLoader;
import javax.cache.integration.CacheWriter;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Readonly version of {@link com.hazelcast.config.CacheConfig}
*
* @param <K> type of the key
* @param <V> type of the value
*
* @deprecated this class will be removed in 4.0; it is meant for internal usage only.
*/
@BinaryInterface
public class CacheConfigReadOnly<K, V> extends CacheConfig<K, V> {
CacheConfigReadOnly(CacheConfig config) {
super(config);
}
// TODO: change to "EvictionConfig" in the future since "CacheEvictionConfig" is deprecated
@Override
public CacheEvictionConfig getEvictionConfig() {
final CacheEvictionConfig evictionConfig = super.getEvictionConfig();
if (evictionConfig == null) {
return null;
}
return evictionConfig.getAsReadOnly();
}
@Override
public WanReplicationRef getWanReplicationRef() {
final WanReplicationRef wanReplicationRef = super.getWanReplicationRef();
if (wanReplicationRef == null) {
return null;
}
return wanReplicationRef.getAsReadOnly();
}
@Override
public String getQuorumName() {
return super.getQuorumName();
}
@Override
public Iterable<CacheEntryListenerConfiguration<K, V>> getCacheEntryListenerConfigurations() {
Iterable<CacheEntryListenerConfiguration<K, V>> listenerConfigurations = super.getCacheEntryListenerConfigurations();
return Collections.unmodifiableSet((Set<CacheEntryListenerConfiguration<K, V>>) listenerConfigurations);
}
@Override
public CacheConfig<K, V> addCacheEntryListenerConfiguration(
CacheEntryListenerConfiguration<K, V> cacheEntryListenerConfiguration) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> removeCacheEntryListenerConfiguration(
CacheEntryListenerConfiguration<K, V> cacheEntryListenerConfiguration) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setName(final String name) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setManagerPrefix(final String managerPrefix) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setUriString(final String uriString) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setBackupCount(final int backupCount) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setAsyncBackupCount(final int asyncBackupCount) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setEvictionConfig(final EvictionConfig evictionConfig) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setInMemoryFormat(final InMemoryFormat inMemoryFormat) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setManagementEnabled(final boolean enabled) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfiguration<K, V> setStatisticsEnabled(boolean enabled) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setTypes(final Class<K> keyType, final Class<V> valueType) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setStoreByValue(final boolean storeByValue) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setWanReplicationRef(final WanReplicationRef wanReplicationRef) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setQuorumName(String quorumName) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfiguration<K, V> setHotRestartConfig(HotRestartConfig hotRestartConfig) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfig<K, V> setPartitionLostListenerConfigs(
List<CachePartitionLostListenerConfig> partitionLostListenerConfigs) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public void setMergePolicy(String mergePolicy) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfiguration<K, V> setExpiryPolicyFactory(Factory<? extends ExpiryPolicy> expiryPolicyFactory) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfiguration<K, V> setCacheLoaderFactory(Factory<? extends CacheLoader<K, V>> cacheLoaderFactory) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfiguration<K, V> setCacheWriterFactory(
Factory<? extends CacheWriter<? super K, ? super V>> cacheWriterFactory) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfiguration<K, V> setWriteThrough(boolean isWriteThrough) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public CacheConfiguration<K, V> setReadThrough(boolean isReadThrough) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
@Override
public void setDisablePerEntryInvalidationEvents(boolean disablePerEntryInvalidationEvents) {
throw new UnsupportedOperationException("This config is read-only cache: " + getName());
}
}
| 38.055276 | 125 | 0.715965 |
e2c2fd655a8e04b75439ff91cf57ec95e0c0c169 | 1,237 | package com.metroApp.config;
import com.metroApp.model.Metro;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class Configurations {
private int fareIncrementStrategy;
private int defaultBalance;
private int minBalance;
public int getMinBalance() {
return minBalance;
}
public void setFareIncrementStrategy(int fareIncrementStrategy) {
this.fareIncrementStrategy = fareIncrementStrategy;
}
public void setDefaultBalance(int defaultBalance) {
this.defaultBalance = defaultBalance;
}
public void setMinBalance(int minBalance) {
this.minBalance = minBalance;
}
public int getDefaultBalance() {
return defaultBalance;
}
public int getFareIncrementStrategy() {
return fareIncrementStrategy;
}
}
| 26.319149 | 81 | 0.769604 |
6f7083e1a27dcfb0b9a2791c6ebc731ea0759264 | 1,548 | package ca.corefacility.bioinformatics.irida.ria.config;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
/**
* Interceptor to determine if the {@link HttpServletRequest} is from a Galaxy Instance.
* If it is this gets added to the session so that the user is presented with the appropriate
* information, and cart page.
*/
public class GalaxySessionInterceptor implements AsyncHandlerInterceptor {
// HTTP session variable name for Galaxy callback variable
public static final String GALAXY_CALLBACK_URL = "galaxyCallbackUrl";
public static final String GALAXY_CLIENT_ID = "galaxyClientID";
@Autowired
private HttpSession session;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
Map<String, String[]> requestMap = request.getParameterMap();
boolean galaxyRequest = requestMap.containsKey(GALAXY_CALLBACK_URL) && requestMap.containsKey(GALAXY_CLIENT_ID);
boolean alreadySeen = session.getAttribute(GALAXY_CALLBACK_URL) != null;
if (galaxyRequest && !alreadySeen) {
session.setAttribute(GALAXY_CALLBACK_URL, requestMap.get(GALAXY_CALLBACK_URL)[0]);
session.setAttribute(GALAXY_CLIENT_ID, requestMap.get(GALAXY_CLIENT_ID)[0]);
response.sendRedirect(request.getRequestURI());
}
return true;
}
}
| 37.756098 | 114 | 0.804264 |
6e98a01500e624b808ad57c90753675ed0918bb5 | 8,495 | /* Class655 - Decompiled by JODE
* Visit http://jode.sourceforge.net/
*/
package com.jagex;
public class Class655 {
static Class375 aClass375_8420 = null;
static Class10 aClass10_8421;
public static Class58_Sub1 aClass58_Sub1_8422;
public static BodyDefinitions aClass630_8423;
public static void method10723() {
if (null != aClass375_8420)
aClass375_8420.method6368(-787346054);
}
public static void method10724(Class652 class652) {
if (Class379.aClass379_3931 == class652.aClass379_8397)
aClass375_8420 = new Class375_Sub1(class652);
else if (Class379.aClass379_3930 == class652.aClass379_8397)
aClass375_8420 = new Class375_Sub2(class652);
else
throw new RuntimeException();
}
public static void method10725(Class652 class652) {
if (Class379.aClass379_3931 == class652.aClass379_8397)
aClass375_8420 = new Class375_Sub1(class652);
else if (Class379.aClass379_3930 == class652.aClass379_8397)
aClass375_8420 = new Class375_Sub2(class652);
else
throw new RuntimeException();
}
public static boolean method10726(int i, int i_0_) {
if (aClass375_8420 == null || aClass375_8420.method6357((byte) 36) == null)
return false;
if (i_0_ == i)
return true;
Class366 class366 = aClass375_8420.method6357((byte) 36).method6333(i, -1324879515);
Class366 class366_1_ = aClass375_8420.method6357((byte) 36).method6333(i_0_, -1837728145);
Class366 class366_2_ = class366;
while_149_: do {
do {
if (class366_2_ == null)
break while_149_;
class366_2_ = class366_2_.method6319((byte) 14);
if (class366_1_ == class366_2_)
return true;
} while (class366_2_ != class366);
return false;
} while (false);
class366_2_ = class366_1_;
while_150_: do {
do {
if (class366_2_ == null)
break while_150_;
class366_2_ = class366_2_.method6319((byte) 14);
if (class366_2_ == class366)
return true;
} while (class366_2_ != class366_1_);
return false;
} while (false);
return false;
}
public static void method10727() {
if (null != aClass375_8420) {
aClass375_8420.method6369(-1414713927);
aClass375_8420 = null;
}
}
public static Interface71 method10728(Class472 class472, int i, Interface69 interface69, boolean bool, Class209 class209) {
if (null != aClass375_8420) {
if (bool)
return new Class598(class472, i, aClass375_8420, interface69);
return new Class605(class472, i, aClass375_8420, interface69, class209);
}
return null;
}
public static void method10729() {
if (null != aClass375_8420)
aClass375_8420.method6368(-1356349009);
}
public static Interface71 method10730(Class472 class472, int i, Interface69 interface69, boolean bool, Class209 class209) {
if (null != aClass375_8420) {
if (bool)
return new Class598(class472, i, aClass375_8420, interface69);
return new Class605(class472, i, aClass375_8420, interface69, class209);
}
return null;
}
public static Class366 method10731(int i) {
if (aClass375_8420 != null)
return aClass375_8420.method6357((byte) 36).method6333(i, 369391954);
return null;
}
public static void method10732(int i, int i_3_, float f, Interface44 interface44) {
if (null != aClass375_8420)
aClass375_8420.method6357((byte) 36).method6336(i, i_3_, f, interface44, -1090748824);
}
public static void method10733(int i, int i_4_, float f, Interface44 interface44) {
if (null != aClass375_8420)
aClass375_8420.method6357((byte) 36).method6336(i, i_4_, f, interface44, -1090748824);
}
Class655() throws Throwable {
throw new Error();
}
public static Class366 method10734(int i) {
if (aClass375_8420 != null)
return aClass375_8420.method6357((byte) 36).method6333(i, 1473037494);
return null;
}
public static Class366 method10735(int i) {
if (aClass375_8420 != null)
return aClass375_8420.method6357((byte) 36).method6333(i, -347972813);
return null;
}
public static void method10736() {
if (null != aClass375_8420) {
aClass375_8420.method6369(-1703837297);
aClass375_8420 = null;
}
}
public static boolean method10737(int i, int i_5_) {
if (aClass375_8420 == null || aClass375_8420.method6357((byte) 36) == null)
return false;
if (i_5_ == i)
return true;
Class366 class366 = aClass375_8420.method6357((byte) 36).method6333(i, 1874813547);
Class366 class366_6_ = aClass375_8420.method6357((byte) 36).method6333(i_5_, 1218372319);
Class366 class366_7_ = class366;
while_151_: do {
do {
if (class366_7_ == null)
break while_151_;
class366_7_ = class366_7_.method6319((byte) 14);
if (class366_6_ == class366_7_)
return true;
} while (class366_7_ != class366);
return false;
} while (false);
class366_7_ = class366_6_;
while_152_: do {
do {
if (class366_7_ == null)
break while_152_;
class366_7_ = class366_7_.method6319((byte) 14);
if (class366_7_ == class366)
return true;
} while (class366_7_ != class366_6_);
return false;
} while (false);
return false;
}
static final void method10738(Class669 class669, int i) {
class669.anInt8558 -= -17422498;
int i_8_ = class669.anIntArray8557[1357652815 * class669.anInt8558];
int i_9_ = class669.anIntArray8557[1 + class669.anInt8558 * 1357652815];
Class523_Sub27_Sub15 class523_sub27_sub15 = Class194_Sub3.method15490(i_8_, i_9_, -1790133114);
if (class523_sub27_sub15 != null) {
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = 1066462451 * class523_sub27_sub15.anInt11762;
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = Class217.method3955((class523_sub27_sub15.aLong11760 * 2598443596916794745L), (Class53_Sub20.aClass668_10979.anInt8549 * 1965832361), -1748382831);
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = class523_sub27_sub15.anInt11769 * -560691001;
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = (null != class523_sub27_sub15.aString11761 ? class523_sub27_sub15.aString11761 : "");
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = (class523_sub27_sub15.aString11764 != null ? class523_sub27_sub15.aString11764 : "");
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = (null != class523_sub27_sub15.aString11765 ? class523_sub27_sub15.aString11765 : "");
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = (class523_sub27_sub15.aString11766 != null ? class523_sub27_sub15.aString11766 : "");
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = class523_sub27_sub15.anInt11767 * 164921411;
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = (null != class523_sub27_sub15.aString11768 ? class523_sub27_sub15.aString11768 : "");
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = (class523_sub27_sub15.aClass421_11759 != null ? class523_sub27_sub15.aClass421_11759.method82() : -1);
} else {
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = -1;
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = "";
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = 0;
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = "";
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = "";
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = "";
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = "";
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = 0;
class669.anObjectArray8559[(class669.anInt8560 += 1235970069) * 240723773 - 1] = "";
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = -1;
}
}
static final void method10739(Class669 class669, byte i) {
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = (Class449.aClass523_Sub33_4946.aClass687_Sub39_10605.method17063(806595627) && Class31.aClass178_303.method3032()) ? 1 : 0;
}
static final void method10740(Class669 class669, int i) {
if (Class481.aClass551_5473.method9127(86, (byte) -72))
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = 1;
else
class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = 0;
}
}
| 40.645933 | 231 | 0.728075 |
9365c7636130273f60f07a973b39f59eb6fcebbb | 2,189 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// 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: 2012.12.05 at 01:12:38 PM EST
//
package org.slc.sli.sample.entitiesR1;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CourseRepeatCodeType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="CourseRepeatCodeType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="RepeatCounted"/>
* <enumeration value="RepeatNotCounted"/>
* <enumeration value="ReplacementCounted"/>
* <enumeration value="ReplacedNotCounted"/>
* <enumeration value="RepeatOtherInstitution"/>
* <enumeration value="NotCountedOther"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CourseRepeatCodeType")
@XmlEnum
public enum CourseRepeatCodeType {
@XmlEnumValue("RepeatCounted")
REPEAT_COUNTED("RepeatCounted"),
@XmlEnumValue("RepeatNotCounted")
REPEAT_NOT_COUNTED("RepeatNotCounted"),
@XmlEnumValue("ReplacementCounted")
REPLACEMENT_COUNTED("ReplacementCounted"),
@XmlEnumValue("ReplacedNotCounted")
REPLACED_NOT_COUNTED("ReplacedNotCounted"),
@XmlEnumValue("RepeatOtherInstitution")
REPEAT_OTHER_INSTITUTION("RepeatOtherInstitution"),
@XmlEnumValue("NotCountedOther")
NOT_COUNTED_OTHER("NotCountedOther");
private final String value;
CourseRepeatCodeType(String v) {
value = v;
}
public String value() {
return value;
}
public static CourseRepeatCodeType fromValue(String v) {
for (CourseRepeatCodeType c: CourseRepeatCodeType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| 30.830986 | 124 | 0.695295 |
444f6d6a1147ca8b3e63e4db2d332f4d0e893145 | 2,188 | package se.cgbystrom.netty.http.websocket;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import java.net.URI;
import java.util.concurrent.Executors;
/**
* A factory for creating WebSocket clients.
* The entry point for creating and connecting a client.
* Can and should be used to create multiple instances.
*
* @author <a href="http://www.pedantique.org/">Carl Byström</a>
*/
public class WebSocketClientFactory {
private NioClientSocketChannelFactory socketChannelFactory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
/**
* Create a new WebSocket client
* @param url URL to connect to.
* @param callback Callback interface to receive events
* @return A WebSocket client. Call {@link WebSocketClient#connect()} to connect.
*/
public WebSocketClient newClient(final URI url, final WebSocketCallback callback) {
ClientBootstrap bootstrap = new ClientBootstrap(socketChannelFactory);
String protocol = url.getScheme();
if (!protocol.equals("ws") && !protocol.equals("wss")) {
throw new IllegalArgumentException("Unsupported protocol: " + protocol);
}
final WebSocketClientHandler clientHandler = new WebSocketClientHandler(bootstrap, url, callback);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new HttpResponseDecoder());
pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("ws-handler", clientHandler);
return pipeline;
}
});
return clientHandler;
}
}
| 39.071429 | 106 | 0.709781 |
5438362484e9ed01d4264d9a41448dac6890666f | 98 | package com.xianyue.design.adapter;
public interface Adaptee {
public void ThreePoint();
}
| 12.25 | 35 | 0.734694 |
990853edfacc8de6d29619cbb68dcffb4e360867 | 1,412 | /*
* Copyright 2011 the original author or 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
*
* 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.github.javarch.persistence.orm.hibernate.envers;
import org.hibernate.envers.RevisionListener;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
/**
*
* @author Lucas Oliveira
*
*/
public class CustomRevisionEntityInforListener implements RevisionListener {
public void newRevision(Object revisionEntity) {
CustomRevisionEntityInfo revision = (CustomRevisionEntityInfo) revisionEntity;
Object princial = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if ( princial instanceof UserDetails ){
revision.setUsername(((UserDetails)princial).getUsername());
}else{
revision.setUsername( princial.toString() ); // anonimo.
}
}
}
| 32.837209 | 96 | 0.757082 |
bc37fb6b9f37882e25eeff7052f1c56785caae73 | 157 | package com.tuyu.exception;
/**
* @author tuyu
* @date 9/19/18
* Talk is cheap, show me the code.
*/
public class MyRunTimeException extends Error {
}
| 14.272727 | 47 | 0.681529 |
094edb3fc415767c62309ef7b6e6277e6e43b3ee | 1,784 | package application;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.cj.protocol.Resultset;
public class JDBCApp {
public static void main(String[] args) throws SQLException {
try(
Connection connection =// make connection to DB
// useSSL=false - connection use secure connection between use
//&serverTimezone=UTC - set time zone, used in MYSQL8, without this statement doesn`t work
DriverManager.getConnection("jdbc:mysql://localhost/telran2019?useSSL=false&serverTimezone=UTC",
"root",
"12345");){
//jdbc:mysql://localhost/ server adress
Statement statement=connection.createStatement(); // Class as writer - the object used for executing a static SQL statementand returning the results it produces.
String sql="SELECT*FROM person";
ResultSet resultset= statement.executeQuery(sql);
while(resultset.next()) {
System.out.println(new Person(resultset.getInt(1),resultset.getString(2),resultset.getInt(3),resultset.getDouble(4),resultset.getBoolean(5)));
}
Person alla= new Person(10, "Alla", 21, 155,false);
//INSERT INTO person VALUES (10, 'lisa', 28, 173, 1);
sql="INSERT INTO person VALUES("+
// lisa.getId()+","+
+0 +","+
"'"+alla.getName()+"'"+","+
alla.getAge()+","+
alla.getHeight()+","+
(alla.isMarried() ? 1: 0)+
")";
System.out.println(statement.executeUpdate(sql, statement.RETURN_GENERATED_KEYS));
ResultSet rs=statement.getGeneratedKeys();
rs.next();
System.out.println(rs.getInt(1));
}
}
}
| 31.298246 | 165 | 0.65583 |
319948b4385e6a46a1bd5d3331d0d925cb78df8c | 4,172 | /*
* 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.pdfbox.examples.pdmodel;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.xml.XmpSerializer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.GregorianCalendar;
import javax.xml.transform.TransformerException;
/**
* This is an example on how to add metadata to a document.
*
* @author Ben Litchfield
*
*/
public final class AddMetadataFromDocInfo
{
private AddMetadataFromDocInfo()
{
//utility class
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
* @throws TransformerException
*/
public static void main( String[] args ) throws IOException, TransformerException
{
if( args.length != 2 )
{
usage();
}
else
{
try (PDDocument document = PDDocument.load(new File(args[0])))
{
if (document.isEncrypted())
{
System.err.println( "Error: Cannot add metadata to encrypted document." );
System.exit( 1 );
}
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDDocumentInformation info = document.getDocumentInformation();
XMPMetadata metadata = XMPMetadata.createXMPMetadata();
AdobePDFSchema pdfSchema = metadata.createAndAddAdobePDFSchema();
pdfSchema.setKeywords( info.getKeywords() );
pdfSchema.setProducer( info.getProducer() );
XMPBasicSchema basicSchema = metadata.createAndAddXMPBasicSchema();
basicSchema.setModifyDate( info.getModificationDate() );
basicSchema.setCreateDate( info.getCreationDate() );
basicSchema.setCreatorTool( info.getCreator() );
basicSchema.setMetadataDate( new GregorianCalendar() );
DublinCoreSchema dcSchema = metadata.createAndAddDublinCoreSchema();
dcSchema.setTitle( info.getTitle() );
dcSchema.addCreator( "PDFBox" );
dcSchema.setDescription( info.getSubject() );
PDMetadata metadataStream = new PDMetadata(document);
catalog.setMetadata( metadataStream );
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(metadata, baos, false);
metadataStream.importXMPMetadata( baos.toByteArray() );
document.save( args[1] );
}
}
}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + AddMetadataFromDocInfo.class.getName() + " <input-pdf> <output-pdf>" );
}
}
| 37.25 | 116 | 0.652924 |
025190fa0037336b9bc8fb38146ea07f38f0e036 | 2,190 | package parsers;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
public class INITfile {
File file;
HashMap<String, HashMap<String, Object>> sections = new HashMap<String, HashMap<String, Object>>();
//Pass the .ini file in as an object
public INITfile(File file) {
this.file = file;
load();
}
//adds a section to the ini file
public void addSection(String category){
sections.put(category, new HashMap<String, Object>());
save();
}
//adds a key and value to a section, if section doesnt exist it will automatically create it
//doesnt create it
public void addValue(String category, String key, Object value){
if(!sections.containsKey(category)){
addSection(category);
}
sections.get(category).put(key, value);
save();
}
/*/hopefully returns a section
public String get(String str){
return sections<str>;
}*/
//returns the file as a string
public String toString(){
return sections.toString();
}
//writes the object to the file
public void save(){
try {
FileWriter fw = new FileWriter(file);
for(String category:sections.keySet()){
fw.write(category+"\n");
for(String key:sections.get(category).keySet()){
fw.write(key + "=" + sections.get(category).get(key) + "\n");
}
}
fw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
//reads the file to the object
public void load(){
try {
Scanner scan = new Scanner(file);
int line_count = 0;
String category = "[No Category]";
while(scan.hasNextLine()){
String line = scan.nextLine().trim();
line_count++;
if(line.startsWith("[")){
category = line;
addSection(line);
}
else{
String[] pair = line.split("=");
if(pair.length == 2){
addValue(category, pair[0], pair[1]);
}
else{
System.out.println("Error in inifile: " + line_count);
}
}
}
scan.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//saves the object then reopens
public void reload(){
save();
load();
}
} | 21.057692 | 100 | 0.642466 |
9a43c102d8c552eb3cfd253d8ce4a4a49c2bb319 | 3,838 | /*
* Copyright 2022 Creek Contributors (https://github.com/creek-service)
*
* 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.creekservice.internal.kafka.streams.extension;
import static java.util.Objects.requireNonNull;
import org.creekservice.api.base.annotation.VisibleForTesting;
import org.creekservice.api.kafka.metadata.KafkaTopicDescriptor;
import org.creekservice.api.kafka.streams.extension.KafkaStreamsExtensionOptions;
import org.creekservice.api.service.extension.CreekExtensionProvider;
import org.creekservice.api.service.extension.CreekService;
import org.creekservice.api.service.extension.model.ResourceHandler;
import org.creekservice.internal.kafka.streams.extension.resource.ResourceRegistry;
import org.creekservice.internal.kafka.streams.extension.resource.ResourceRegistryFactory;
/** Provider of {@link org.creekservice.api.kafka.streams.extension.KafkaStreamsExtension}. */
public final class KafkaStreamsExtensionProvider implements CreekExtensionProvider {
private final BuilderFactory builderFactory;
private final ExecutorFactory executorFactory;
private final ExtensionFactory extensionFactory;
private final ResourceRegistryFactory resourcesFactory;
public KafkaStreamsExtensionProvider() {
this(
KafkaStreamsBuilder::new,
KafkaStreamsExecutor::new,
StreamsExtension::new,
new ResourceRegistryFactory());
}
@VisibleForTesting
KafkaStreamsExtensionProvider(
final BuilderFactory builderFactory,
final ExecutorFactory executorFactory,
final ExtensionFactory extensionFactory,
final ResourceRegistryFactory resourcesFactory) {
this.builderFactory = requireNonNull(builderFactory, "builderFactory");
this.executorFactory = requireNonNull(executorFactory, "executorFactory");
this.extensionFactory = requireNonNull(extensionFactory, "extensionFactory");
this.resourcesFactory = requireNonNull(resourcesFactory, "resourcesFactory");
}
@Override
public StreamsExtension initialize(final CreekService api) {
api.model().addResource(KafkaTopicDescriptor.class, new ResourceHandler<>() {});
final KafkaStreamsExtensionOptions options =
api.options()
.get(KafkaStreamsExtensionOptions.class)
.orElseGet(() -> KafkaStreamsExtensionOptions.builder().build());
final ResourceRegistry resources = resourcesFactory.create(api.service(), options);
return extensionFactory.create(
options,
resources,
builderFactory.create(options),
executorFactory.create(options));
}
@VisibleForTesting
interface BuilderFactory {
KafkaStreamsBuilder create(KafkaStreamsExtensionOptions options);
}
@VisibleForTesting
interface ExecutorFactory {
KafkaStreamsExecutor create(KafkaStreamsExtensionOptions options);
}
@VisibleForTesting
interface ExtensionFactory {
StreamsExtension create(
KafkaStreamsExtensionOptions options,
ResourceRegistry resources,
KafkaStreamsBuilder builder,
KafkaStreamsExecutor executor);
}
}
| 40.4 | 94 | 0.726941 |
df455280ec34fb864d7013efb0a86742f510bce0 | 836 | package com.lmarket.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.common.utils.PageUtils;
import com.lmarket.product.entity.AttrGroupEntity;
import com.lmarket.product.vo.AttrGroupWithAttrsVo;
import com.lmarket.product.vo.SkuItemVo;
import com.lmarket.product.vo.SpuItemAttrGroupVo;
import java.util.List;
import java.util.Map;
/**
*
*
* @author branshlee
* @email branshLEE@gmail.com
* @date 2021-02-22 13:31:35
*/
public interface AttrGroupService extends IService<AttrGroupEntity> {
PageUtils queryPage(Map<String, Object> params);
PageUtils queryPage(Map<String, Object> params, Long catelogId);
List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId);
List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catelogId);
}
| 26.967742 | 86 | 0.79067 |
1443dafc4c868e7de8743a34517e1b5c49032d6e | 192 | package com.pnuema.java.barcode.barcodeapi.controllers.v1;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/v1")
public abstract class AbstractV1Resource {
}
| 24 | 62 | 0.822917 |
48c252ddc3594e61f7c239e04dbdd3ac7ebd2552 | 2,743 | /*******************************************************************************
* Copyright 2016 ContainX and OpenStack4j
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package com.huawei.openstack4j.api.identity.v3;
import java.util.List;
import com.huawei.openstack4j.common.RestService;
import com.huawei.openstack4j.model.common.ActionResponse;
import com.huawei.openstack4j.model.identity.v3.Region;
/**
* Identity V3 Region operations
*
*/
public interface RegionService extends RestService {
/**
* Create a new region
*
* @param region the region
* @return the newly created region
*/
Region create(Region region);
/**
* Create a new region
*
* @param regionId the user-defined region id
* @param description the description of the region
* @param parentRegionId the region id of the parent region
* @return the newly created region
*/
Region create(String regionId, String description, String parentRegionId);
/**
* Get details for a region specified by id
*
* @param regionId the region id
* @return the region
*/
Region get(String regionId);
/**
* Update a region
*
* @param region the region set to update
* @return the updated region
*/
Region update(Region region);
/**
* Delete a region specified by id
*
* @param regionId the id of the region
* @return the ActionResponse
*/
ActionResponse delete(String regionId);
/**
* List regions
*
* @return a list of regions
*/
List<? extends Region> list();
}
| 34.2875 | 85 | 0.505651 |
c93cb5c00b5da40218f0ce2103acfb04a1945527 | 6,179 | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2005, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import org.apache.bcel.Const;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import edu.umd.cs.findbugs.BugAccumulator;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.ch.Subtypes2;
import edu.umd.cs.findbugs.bcel.BCELUtil;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
public class ConfusionBetweenInheritedAndOuterMethod extends OpcodeStackDetector {
BugAccumulator bugAccumulator;
BugInstance iteratorBug;
public ConfusionBetweenInheritedAndOuterMethod(BugReporter bugReporter) {
this.bugAccumulator = new BugAccumulator(bugReporter);
}
@Override
public void visitJavaClass(JavaClass obj) {
isInnerClass = false;
// totally skip methods not defined in inner classes
if (obj.getClassName().indexOf('$') >= 0) {
super.visitJavaClass(obj);
bugAccumulator.reportAccumulatedBugs();
}
}
boolean isInnerClass;
@Override
public void visit(Field f) {
if (f.getName().startsWith("this$")) {
isInnerClass = true;
}
}
@Override
public void visit(Code obj) {
if (isInnerClass && !BCELUtil.isSynthetic(getMethod())) {
super.visit(obj);
iteratorBug = null;
}
}
@Override
public void sawOpcode(int seen) {
if (iteratorBug != null) {
if (isRegisterStore()) {
LocalVariableTable lvt = getMethod().getLocalVariableTable();
if (lvt != null) {
LocalVariable localVariable = lvt.getLocalVariable(getRegisterOperand(), getNextPC());
if (localVariable == null || localVariable.getName().endsWith("$")) {
// iterator() result is stored to the synthetic variable which has no name in LVT or name is suffixed with '$'
// Looks like it's for-each cycle like for(Object obj : this)
// Do not report such case
iteratorBug = null;
}
}
}
if (iteratorBug != null) {
bugAccumulator.accumulateBug(iteratorBug, this);
}
iteratorBug = null;
}
if (seen != Const.INVOKEVIRTUAL) {
return;
}
if (!getClassName().equals(getClassConstantOperand())) {
return;
}
XMethod invokedMethod = XFactory.createXMethod(getDottedClassConstantOperand(), getNameConstantOperand(),
getSigConstantOperand(), false);
if (invokedMethod.isResolved() && invokedMethod.getClassName().equals(getDottedClassConstantOperand())
|| invokedMethod.isSynthetic()) {
return;
}
if (getStack().getStackItem(getNumberArguments(getSigConstantOperand())).getRegisterNumber() != 0) {
// called not for this object
return;
}
// method is inherited
String possibleTargetClass = getDottedClassName();
String superClassName = getDottedSuperclassName();
while (true) {
int i = possibleTargetClass.lastIndexOf('$');
if (i <= 0) {
break;
}
possibleTargetClass = possibleTargetClass.substring(0, i);
if (possibleTargetClass.equals(superClassName)) {
break;
}
XMethod alternativeMethod = XFactory.createXMethod(possibleTargetClass, getNameConstantOperand(),
getSigConstantOperand(), false);
if (alternativeMethod.isResolved() && alternativeMethod.getClassName().equals(possibleTargetClass)) {
String targetPackage = invokedMethod.getPackageName();
String alternativePackage = alternativeMethod.getPackageName();
int priority = HIGH_PRIORITY;
if (targetPackage.equals(alternativePackage)) {
priority++;
}
if (targetPackage.startsWith("javax.swing") || targetPackage.startsWith("java.awt")) {
priority += 2;
}
if (invokedMethod.getName().equals(getMethodName())) {
priority++;
}
BugInstance bug = new BugInstance(this, "IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD", priority)
.addClassAndMethod(this).addMethod(invokedMethod).describe("METHOD_INHERITED")
.addMethod(alternativeMethod).describe("METHOD_ALTERNATIVE_TARGET");
if (invokedMethod.getName().equals("iterator") && invokedMethod.getSignature().equals("()Ljava/util/Iterator;")
&& Subtypes2.instanceOf(getDottedClassName(), "java.lang.Iterable")) {
iteratorBug = bug;
} else {
bugAccumulator.accumulateBug(bug, this);
}
break;
}
}
}
}
| 40.123377 | 134 | 0.616119 |
5d1d73b166ad5369adca31fd2f8736128207cf83 | 3,063 | package net.ludocrypt.backrooms.client;
import net.ludocrypt.backrooms.Backrooms;
import net.ludocrypt.backrooms.mixin.MinecraftClientAccessor;
import net.ludocrypt.backrooms.mixin.MusicTrackerAccessor;
import net.ludocrypt.backrooms.util.MathHelperUpdated;
import net.ludocrypt.backrooms.world.biome.BackroomsBiomeSource;
import net.ludocrypt.backrooms.world.biome.base.ConcreteBaseBiome;
import net.ludocrypt.backrooms.world.biome.base.MaintenanceBaseBiome;
import net.ludocrypt.backrooms.world.biome.base.PipesBaseBiome;
import net.minecraft.class_2388;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.sound.SoundCategory;
import net.minecraft.client.sound.TickableSoundInstance;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.biome.Biome;
public class BackroomsAmbienceSoundInstance implements TickableSoundInstance {
private final MinecraftClient client;
private double delta = 0.0D;
public Identifier idBefore;
public BackroomsAmbienceSoundInstance(MinecraftClient client) {
this.client = client;
idBefore = getIdentifier();
}
public boolean isOn() {
return BackroomsBiomeSource.isInside(getX(), getZ(), 1100);
}
@Override
public Identifier getIdentifier() {
if (biomeAt() instanceof PipesBaseBiome) {
return Backrooms.id("ambient.game.backrooms.pipes.bg");
}
if (biomeAt() instanceof ConcreteBaseBiome) {
return Backrooms.id("ambient.game.backrooms.concrete.bg");
}
if (biomeAt() instanceof MaintenanceBaseBiome) {
return Backrooms.id("ambient.game.backrooms.maintenance.bg");
}
if (!isOn()) {
return Backrooms.id("ambient.game.backrooms.lobby.bg_off");
}
return Backrooms.id("ambient.game.backrooms.lobby.bg_on");
}
@Override
public boolean isRepeatable() {
return (((MusicTrackerAccessor) ((MinecraftClientAccessor) client).getMusicTracker()).getField_10765() == null);
}
@Override
public int getRepeatDelay() {
return 0;
}
@Override
public float getVolume() {
return MathHelperUpdated.lerpF(delta, 1.0D, 0.4D);
}
public Biome biomeAt() {
return client.player.world.dimension.world.getBiomeAt(client.player.getBlockPos().x, client.player.getBlockPos().z);
}
@Override
public float getPitch() {
return 1.0F;
}
@Override
public float getX() {
return (float) client.player.x;
}
@Override
public float getY() {
return (float) client.player.y;
}
@Override
public float getZ() {
return (float) client.player.z;
}
@Override
public class_2388 getAttenuationType() {
return class_2388.field_10756;
}
@Override
public void tick() {
if (((MusicTrackerAccessor) ((MinecraftClientAccessor) client).getMusicTracker()).getField_10765() != null) {
delta += 0.015D;
} else {
delta -= 0.015D;
}
delta = MathHelper.clamp(delta, 0.0D, 1.0D);
if (idBefore != getIdentifier()) {
idBefore = getIdentifier();
}
this.client.getSoundManager().updateSoundVolume(SoundCategory.AMBIENT, getVolume());
}
@Override
public boolean isDone() {
return false;
}
}
| 26.405172 | 118 | 0.753836 |
16cb3d961674df08a39e46cc3b1de2a43e8eadd1 | 1,787 | package net.foulest.togepi.check.impl.killaura;
import net.foulest.togepi.Togepi;
import net.foulest.togepi.check.checks.PacketCheck;
import net.foulest.togepi.data.PlayerData;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PacketPlayInFlying;
import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity;
/**
* @author Foulest
* @project Togepi
*/
public class KillAuraA extends PacketCheck {
private int ticks;
private int lastTicks;
private int attacks;
private int streak;
private int buffer;
public KillAuraA(Togepi plugin, PlayerData playerData) {
super(plugin, playerData, "KillAura (A)", "No description.", 5, 30000L);
}
@Override
public void handleCheck(Packet packet) {
if (packet instanceof PacketPlayInUseEntity) {
PacketPlayInUseEntity wrapper = (PacketPlayInUseEntity) packet;
PacketPlayInUseEntity.EnumEntityUseAction action = wrapper.a();
if (action == PacketPlayInUseEntity.EnumEntityUseAction.ATTACK) {
if (ticks < 8 && ticks == lastTicks) {
buffer++;
}
if (++attacks == 25) {
if (buffer > 22) {
alert(true);
}
if (buffer > 15) {
if (++streak > 1) {
alert(true);
}
} else {
streak = 0;
}
attacks = 0;
buffer = 0;
}
lastTicks = ticks;
ticks = 0;
}
} else if (packet instanceof PacketPlayInFlying) {
ticks++;
}
}
}
| 28.365079 | 80 | 0.531617 |
5a9346ae1b50df88ae98d871201538d21a8f28bb | 345 | package org.jbpm.examples.util;
import java.util.Map;
import org.jbpm.services.task.utils.ContentMarshallerHelper;
import org.kie.api.task.model.Content;
import org.kie.api.task.model.Task;
import org.kie.internal.task.api.ContentMarshallerContext;
public class APIUtil {
public static void write(String text){
System.out.println(text);
}
}
| 23 | 60 | 0.797101 |
10cbd239666e50ea4e2d36fb5b0424ce350cea9d | 3,724 |
package mage.cards.c;
import java.util.UUID;
import mage.MageObject;
import mage.abilities.Ability;
import mage.abilities.effects.PreventionEffectData;
import mage.abilities.effects.PreventionEffectImpl;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.game.Controllable;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author emerald000
*/
public final class ChannelHarm extends CardImpl {
public ChannelHarm(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{5}{W}");
// Prevent all damage that would be dealt to you and permanents you control this turn by sources you don't control. If damage is prevented this way, you may have Channel Harm deal that much damage to target creature.
this.getSpellAbility().addEffect(new ChannelHarmEffect());
this.getSpellAbility().addTarget(new TargetCreaturePermanent());
}
public ChannelHarm(final ChannelHarm card) {
super(card);
}
@Override
public ChannelHarm copy() {
return new ChannelHarm(this);
}
}
class ChannelHarmEffect extends PreventionEffectImpl {
ChannelHarmEffect() {
super(Duration.EndOfTurn, Integer.MAX_VALUE, false, false);
staticText = "Prevent all damage that would be dealt to you and permanents you control this turn by sources you don't control. If damage is prevented this way, you may have {this} deal that much damage to target creature";
}
ChannelHarmEffect(final ChannelHarmEffect effect) {
super(effect);
}
@Override
public ChannelHarmEffect copy() {
return new ChannelHarmEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
return true;
}
@Override
public boolean replaceEvent(GameEvent event, Ability source, Game game) {
Player sourceController = game.getPlayer(source.getControllerId());
PreventionEffectData preventionData = preventDamageAction(event, source, game);
if (preventionData.getPreventedDamage() > 0) {
Permanent targetCreature = game.getPermanent(source.getFirstTarget());
if (targetCreature != null) {
if (sourceController != null && sourceController.chooseUse(outcome, "Would you like to have " + preventionData.getPreventedDamage() + " damage dealt to " + targetCreature.getLogName() + "?", source, game)) {
targetCreature.damage(preventionData.getPreventedDamage(), source.getSourceId(), source, game, false, true);
}
}
}
return true;
}
@Override
public boolean applies(GameEvent event, Ability source, Game game) {
if (super.applies(event, source, game)) {
Permanent targetPermanent = game.getPermanent(event.getTargetId());
if ((targetPermanent != null && targetPermanent.isControlledBy(source.getControllerId()))
|| event.getTargetId().equals(source.getControllerId())) {
MageObject damageSource = game.getObject(event.getSourceId());
if (damageSource instanceof Controllable) {
return !((Controllable) damageSource).isControlledBy(source.getControllerId());
}
else if (damageSource instanceof Card) {
return !((Card) damageSource).isOwnedBy(source.getControllerId());
}
}
}
return false;
}
}
| 37.616162 | 230 | 0.677497 |
435188c107308283c19c1d0815ab468686d8c38e | 1,968 | package cn.kunter.generator.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import java.util.List;
/**
* 对象工厂
* @author yangziran
* @version 1.0 2021/7/21
*/
@Slf4j
public class ObjectFactory {
private static final List<ClassLoader> externalClassLoaders;
static {
externalClassLoaders = Lists.newArrayList();
}
/**
* 工具类,私有构造
*/
private ObjectFactory() {
super();
}
/**
* 清理类加载器
*/
public static void reset() {
externalClassLoaders.clear();
}
/**
* 添加自定义类加载器到集合
* @param classLoader
*/
public static synchronized void addExternalClassLoader(ClassLoader classLoader) {
ObjectFactory.externalClassLoaders.add(classLoader);
}
/**
* 获取从上下文或者客户端提供的类加载器加载的类
* 用户JDBC驱动类的加载
* @param type
* @return
* @throws ClassNotFoundException
*/
public static Class<?> externalClassForName(String type) throws ClassNotFoundException {
for (var classLoader : externalClassLoaders) {
try {
return Class.forName(type, true, classLoader);
} catch (Exception e) {
log.warn("externalClassForName type: {} {}", type, e.getMessage());
}
}
return internalClassForName(type);
}
public static Class<?> internalClassForName(String type) throws ClassNotFoundException {
Class<?> clazz = null;
try {
var classLoader = Thread.currentThread().getContextClassLoader();
clazz = Class.forName(type, true, classLoader);
} catch (Exception e) {
log.warn("internalClassForName type: {} {}", type, e.getMessage());
}
if (ObjectUtils.isEmpty(clazz)) {
clazz = Class.forName(type, true, ObjectFactory.class.getClassLoader());
}
return clazz;
}
}
| 23.710843 | 92 | 0.609248 |
6679e76ed680da21d66f8014b97526889d406ab3 | 80 | package ru.job4j.tdd.cinema;
public class AccountCinema implements Account {
}
| 16 | 47 | 0.8 |
b32f1694fd4ab6dcf021b3d80b04093ad0f3268b | 4,335 | package com.docswebapps.homeinventoryservice.web.controller.v1;
import com.docswebapps.homeinventoryservice.service.MakeService;
import com.docswebapps.homeinventoryservice.web.model.MakeDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.ArrayList;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(MakeController.class)
class MakeControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private MakeService makeService;
private static final String URL= "/api/v1/make/";
private final MakeDto makeDto = MakeDto.builder()
.name("TestMake")
.build();
private final Long id = 1L;
@Test
void getAllMakes() throws Exception {
// Happy Path
when(this.makeService.getAllMakes()).thenReturn(Collections.singletonList(this.makeDto));
mockMvc.perform(get(URL)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Sad Path
when(this.makeService.getAllMakes()).thenReturn(new ArrayList<>());
mockMvc.perform(get(URL)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
@Test
void createNewMake() throws Exception {
String makeDtoJson = objectMapper.writeValueAsString(makeDto);
when(this.makeService.saveMake(any(MakeDto.class))).thenReturn(this.id);
mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(makeDtoJson))
.andExpect(status().isCreated());
}
@Test
void getMakeById() throws Exception {
// Happy Path
when(this.makeService.getMakeById(anyLong())).thenReturn(makeDto);
mockMvc.perform(get(URL + this.id)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Sad Path
when(this.makeService.getMakeById(anyLong())).thenReturn(null);
mockMvc.perform(get(URL + this.id)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
@Test
void updateMakeById() throws Exception {
String makeDtoJson = objectMapper.writeValueAsString(makeDto);
// Happy Path
when(this.makeService.updateMake(anyLong(), any(MakeDto.class))).thenReturn(true);
mockMvc.perform(put(URL + this.id)
.contentType(MediaType.APPLICATION_JSON)
.content(makeDtoJson))
.andExpect(status().isNoContent());
// Sad Path
when(this.makeService.updateMake(anyLong(), any(MakeDto.class))).thenReturn(false);
mockMvc.perform(put(URL + this.id)
.contentType(MediaType.APPLICATION_JSON)
.content(makeDtoJson))
.andExpect(status().isBadRequest())
.andExpect(result -> {
assertEquals("Error updating make, contact an administrator!", result.getResponse().getContentAsString());
});
}
@Test
void deleteMakeById() throws Exception {
// Happy Path
when(this.makeService.deleteMake(anyLong())).thenReturn(true);
mockMvc.perform(delete(URL + this.id)).andExpect(status().isNoContent());
// Sad Path
when(this.makeService.deleteMake(anyLong())).thenReturn(false);
mockMvc.perform(delete(URL + this.id))
.andExpect(status().isBadRequest())
.andExpect(result -> {
assertEquals("Error deleting make, contact an administrator!", result.getResponse().getContentAsString());
});
}
}
| 37.37069 | 126 | 0.656747 |
cc471440e7f7c5ef057e2b0eed258a48f55795a5 | 1,251 | package net.saisimon.agtms.core.domain.tag;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
/**
* 前端多选下拉列表
*
* @author saisimon
*
* @param <T> value 的类型
*/
@Getter
@Setter
public class MultipleSelect<T> extends Select<T> {
private List<T> selected;
public static <T> Select<T> multipleSelect(List<T> selected, List<T> optionValues, List<String> optionTexts) {
MultipleSelect<T> select = new MultipleSelect<>();
List<Option<T>> options = new ArrayList<>();
for (T optionValue : optionValues) {
Option<T> option = new Option<>(optionValue, optionValue.toString());
options.add(option);
}
select.setOptions(options);
select.setSelected(selected);
return select;
}
@SuppressWarnings("unchecked")
@Override
public Object clone() throws CloneNotSupportedException {
MultipleSelect<T> filterMultipleSelect = (MultipleSelect<T>) super.clone();
if (this.selected != null) {
List<T> cloneSelected = new ArrayList<>(this.selected.size());
for (T selectedOption : this.selected) {
cloneSelected.add(selectedOption);
}
filterMultipleSelect.selected = cloneSelected;
}
return filterMultipleSelect;
}
}
| 25.530612 | 112 | 0.689049 |
fea119cd9516796ad64e4d23b0bfd6ddc84ffe57 | 174 | package com.github.cjgmj.dynamicquery;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DynamicQueryApplication {
}
| 21.75 | 68 | 0.862069 |
05a3f263407907f5246c531e93347bf08afb70ab | 107 | package services;
/**
* Created by SOURAV SAMANTA on 23-01-2017.
*/
public class UserService {
}
| 13.375 | 44 | 0.64486 |
bb844a3da75d196c1f11469cad850f78a8f38c01 | 171 | package core;
import org.dom4j.Element;
public interface XMLPersistent {
Element toDOM() throws Exception;
void fromDOM(Element e) throws Exception;
}
| 14.25 | 43 | 0.707602 |
ecaf49f98b64f6140b0589e1a737cdd2a6b8f24f | 1,952 | /*
* 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 ChatClient;
import static ChatClient.Main.cl;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javax.swing.JOptionPane;
/**
* FXML Controller class
*
* @author Zishan
*/
public class SplashScreenController implements Initializable {
/**
* Initializes the controller class.
*/
@FXML
Label label;
@Override
public void initialize(URL url, ResourceBundle rb) {
new Splash().start();
}
class Splash extends Thread{
@Override
public void run(){
try{
new FindServerIP();
String server_ip1;
server_ip1 = FindServerIP.serverIP.split("/")[1];
cl=new Client();
System.out.println("connection is creating :"+server_ip1 );
if(!cl.connection(server_ip1,2002)) {
JOptionPane.showMessageDialog(null, "Conection Not Created");
System.exit(0);
} else {
Thread.sleep(1000);
Platform.runLater(() -> {
try {
Main.mainWindow();
} catch (IOException ex) {
Logger.getLogger(SplashScreenController.class.getName()).log(Level.SEVERE, null, ex);
}
label.getScene().getWindow().hide();
});
}
//thread close
}catch(Exception e){
e.printStackTrace();
}
}
}
}
| 27.885714 | 109 | 0.577869 |
581e061aedb7c5e0d90d74c85b99697dd4100532 | 21,639 | package com.ensoftcorp.open.slice.analysis;
import com.ensoftcorp.atlas.core.db.graph.Edge;
import com.ensoftcorp.atlas.core.db.graph.Graph;
import com.ensoftcorp.atlas.core.db.graph.Node;
import com.ensoftcorp.atlas.core.db.set.AtlasHashSet;
import com.ensoftcorp.atlas.core.db.set.AtlasSet;
import com.ensoftcorp.atlas.core.query.Q;
import com.ensoftcorp.atlas.core.query.Query;
import com.ensoftcorp.atlas.core.script.Common;
import com.ensoftcorp.atlas.core.xcsg.XCSG;
import com.ensoftcorp.open.commons.analysis.CommonQueries;
import com.ensoftcorp.open.slice.log.Log;
/**
* Compute Data Dependence Graph
*
* @author Payas Awadhutkar, Ben Holland
*/
public class DataDependenceGraph extends DependenceGraph {
/**
* Used to tag the edges between nodes that contain a data dependence
*/
public static final String DATA_DEPENDENCE_EDGE = "data-dependence";
/**
* Used to tag the edges between nodes that contain a data dependence due to a pointer
*/
public static final String POINTER_DEPENDENCE_EDGE = "pointer-dependence";
/**
* Used to tag the edges between nodes that contain a backwards data dependence
*/
public static final String BACKWARD_DATA_DEPENDENCE_EDGE = "backward-data-dependence";
/**
* Used to tag the edges representing interprocedural data dependence
*/
public static final String INTERPROCEDURAL_DATA_DEPENDENCE_EDGE = "data-dependence (inter)";
/**
* Used to simulate the implict data dependency from initialization to instantiation
*/
public static final String JIMPLE_INITIALIZATION_DATA_DEPENDENCE_EDGE = "jimple-initialization-data-dependence";
/**
* Used to identify the dependent variable
*/
public static final String DEPENDENT_VARIABLE = "dependent-variable";
private Graph dfg; // data flow graph (SSA form)
private Graph ddg; // data dependency graph
public DataDependenceGraph(Graph dfg){
// sanity checks
if(dfg.nodes().isEmpty() || dfg.edges().isEmpty()){
this.dfg = Common.toQ(dfg).eval();
this.ddg = Common.empty().eval();
return;
}
this.dfg = dfg;
AtlasSet<Edge> dataDependenceEdgeSet = new AtlasHashSet<Edge>();
AtlasSet<Edge> pointerDependenceEdgeSet = new AtlasHashSet<Edge>();
AtlasSet<Edge> backwardDataDependenceEdgeSet = new AtlasHashSet<Edge>();
AtlasSet<Edge> interDataDependenceEdgeSet = new AtlasHashSet<Edge>();
if(!CommonQueries.isEmpty(Common.toQ(dfg).nodes(XCSG.Language.Jimple))) {
// this is sort of a logical patch for an oddity in jimple
// 1. $r0 = new java.io.FileInputStream;
// 2. $r3 = args[0];
// 3. specialinvoke $r0.<java.io.FileInputStream: void <init>(java.lang.String)>($r3);
// 4. use of $r0
// consider the use of r0, the data flow that Atlas produces has an incoming edge from line 1
// but there is not dependency on line 3, even though line 3 is necessary to instantiate r0
// to this end we can add a fake local data flow edge from 3 to 1 to simulate the dependency
Q initializationCallsites = CommonQueries.nodesContaining(Common.toQ(dfg).nodes(XCSG.Language.Jimple).nodes(XCSG.ObjectOrientedStaticCallSite), "<init>");
for(Node initializationCallsite : initializationCallsites.eval().nodes()) {
Node initializationStatement = Common.toQ(initializationCallsite).parent().nodes(XCSG.ControlFlow_Node).eval().nodes().one();
if(initializationStatement != null) {
Node identityPass = Common.toQ(initializationStatement).children().nodes(XCSG.IdentityPass).eval().nodes().one();
if(identityPass != null) {
Q instantiationStatements = Common.toQ(dfg).nodes(XCSG.Language.Jimple).nodes(XCSG.Instantiation).parent().nodes(XCSG.ControlFlow_Node);
Node instantiationStatement = Common.toQ(dfg).predecessors(Common.toQ(identityPass)).parent()
.intersection(instantiationStatements).eval().nodes().one();
if(instantiationStatement != null) {
// create a data dependency edge from the initialization statement to the instantiation statement
// if one does not already exist
if(!initializationStatement.equals(instantiationStatement)) {
if(CommonQueries.isEmpty(Query.universe().edges(DataDependenceGraph.JIMPLE_INITIALIZATION_DATA_DEPENDENCE_EDGE).between(Common.toQ(initializationStatement), Common.toQ(instantiationStatement)))) {
Edge dataDependenceEdge = Graph.U.createEdge(initializationStatement, instantiationStatement);
dataDependenceEdge.tag(DataDependenceGraph.DATA_DEPENDENCE_EDGE);
dataDependenceEdge.tag(DataDependenceGraph.JIMPLE_INITIALIZATION_DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, DataDependenceGraph.DATA_DEPENDENCE_EDGE);
dataDependenceEdgeSet.add(dataDependenceEdge);
}
}
}
}
}
}
}
for(Edge dfEdge : dfg.edges()){
Node from = dfEdge.from();
if(from.taggedWith(XCSG.Identity) || from.taggedWith(XCSG.Parameter)){
continue;
}
Node fromStatement = CommonQueries.getContainingControlFlowNode(from);
Node to = dfEdge.to();
if(to.taggedWith(XCSG.ReturnValue)){
continue;
}
Node toStatement = CommonQueries.getContainingControlFlowNode(to);
// sanity checks
if(fromStatement == null){
Log.warning("From node has no parent or is null: " + from.address().toAddressString());
continue;
}
if(toStatement == null){
Log.warning("To node has no parent or is null: " + to.address().toAddressString());
continue;
}
// statement contains both data flow nodes
// this is a little noisy to create relationships to all the time
// example: "x = 1;" is a single statement with a data dependence from 1 to x
// skip the trivial edges
if(fromStatement.equals(toStatement)){
continue;
}
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(toStatement)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, toStatement);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(DEPENDENT_VARIABLE, from.getAttr(XCSG.name).toString());
// Log.info(fromStatement.getAttr(XCSG.name) + " -> " + toStatement.getAttr(XCSG.name));
}
dataDependenceEdgeSet.add(dataDependenceEdge);
}
// consider field reads
Q interproceduralDataFlowEdges = Query.universe().edges(XCSG.InterproceduralDataFlow);
Q fields = Query.universe().nodes(XCSG.Field, XCSG.ArrayComponents);
Q parameters = Query.universe().nodes(XCSG.Parameter);
Q returns = Query.universe().nodes(XCSG.Return);
Q localDFG = Common.toQ(dfg).difference(parameters, returns);
for(Node field : interproceduralDataFlowEdges.between(fields, localDFG).nodes(XCSG.Field).eval().nodes()){
for(Node localDFNode : interproceduralDataFlowEdges.forward(Common.toQ(field)).intersection(localDFG).eval().nodes()){
Node toStatement = localDFNode;
if(!toStatement.taggedWith(XCSG.ReturnValue)){
toStatement = getStatement(localDFNode);
}
Node fromStatement = field;
if(fromStatement == null || toStatement == null || fromStatement.equals(toStatement)){
continue;
}
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(toStatement)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, toStatement);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, DATA_DEPENDENCE_EDGE);
}
dataDependenceEdgeSet.add(dataDependenceEdge);
}
}
// add data dependencies for array references
Q arrayIdentityForEdges = Query.universe().edges(XCSG.ArrayIdentityFor);
for(Node arrayRead : Common.toQ(dfg).nodes(XCSG.ArrayRead).eval().nodes()){
for(Node arrayIdentityFor : arrayIdentityForEdges.predecessors(Common.toQ(arrayRead)).eval().nodes()){
Node fromStatement = arrayIdentityFor;
if(!fromStatement.taggedWith(XCSG.Parameter) && !fromStatement.taggedWith(XCSG.Field)){
fromStatement = getStatement(arrayIdentityFor);
}
Node toStatement = getStatement(arrayRead);
if(fromStatement == null || toStatement == null || fromStatement.equals(toStatement)){
continue;
}
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(toStatement)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, toStatement);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, DATA_DEPENDENCE_EDGE);
}
dataDependenceEdgeSet.add(dataDependenceEdge);
}
}
// add data dependencies for array indexes
Q arrayIndexForEdges = Query.universe().edges(XCSG.ArrayIndexFor);
for(Node arrayRead : Common.toQ(dfg).nodes(XCSG.ArrayRead).eval().nodes()){
for(Node arrayIndexFor : arrayIndexForEdges.predecessors(Common.toQ(arrayRead)).eval().nodes()){
Node fromStatement = arrayIndexFor;
if(!fromStatement.taggedWith(XCSG.Parameter) && !fromStatement.taggedWith(XCSG.Field)){
fromStatement = getStatement(arrayIndexFor);
}
Node toStatement = getStatement(arrayRead);
if(fromStatement == null || toStatement == null || fromStatement.equals(toStatement)){
continue;
}
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(toStatement)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, toStatement);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, DATA_DEPENDENCE_EDGE);
}
dataDependenceEdgeSet.add(dataDependenceEdge);
}
}
/**
* Handle Pointers
*/
Q pointerFlows = Common.toQ(dfg).nodes(XCSG.C.Provisional.Star,XCSG.C.Provisional.Ampersand);
for(Node pointerFlow : pointerFlows.eval().nodes()) {
Node toStatement = CommonQueries.getContainingControlFlowNode(pointerFlow);
Q predecessors = Query.universe().edges("pointerDereference","addressOf",XCSG.InterproceduralDataFlow).predecessors(Common.toQ(pointerFlow));
Q edgesToProcess = Common.empty();
if(!CommonQueries.isEmpty(predecessors.nodes(XCSG.C.Provisional.Star))) {
// check if the current node is part of a double pointer dereference
// If so, ignore as it should be processed at the outermost dereferencing
continue;
} else {
edgesToProcess = Query.universe().edges("pointerDereference","addressOf",XCSG.InterproceduralDataFlow).reverseStep(Common.toQ(pointerFlow));
// Check if there is an incoming pointer. In which case, we should ignore the direct link from the dereferenced variable
Q pointers = getPointersContained(predecessors);
if(!CommonQueries.isEmpty(pointers)) {
edgesToProcess = edgesToProcess.forward(pointers);
}
}
// Q edgesToProcess = Query.universe().edges("pointerDereference","addressOf",XCSG.InterproceduralDataFlow).reverseStep(Common.toQ(pointerFlow));
for(Edge edgeToProcess : edgesToProcess.eval().edges()) {
Node dependentVariable = edgeToProcess.from();
if(dependentVariable.taggedWith(XCSG.Assignment)) {
Node fromStatement = CommonQueries.getContainingControlFlowNode(dependentVariable);
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(toStatement)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, toStatement);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.tag(POINTER_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(DEPENDENT_VARIABLE, dependentVariable.getAttr(XCSG.name).toString());
}
dataDependenceEdgeSet.add(dataDependenceEdge);
pointerDependenceEdgeSet.add(dataDependenceEdge);
}
}
// if it is an ampersand node, then potentially we may have to process some backwards data flow
if(pointerFlow.taggedWith(XCSG.C.Provisional.Ampersand)) {
Q target = Query.universe().edges("addressOf").predecessors(Common.toQ(pointerFlow));
Q stackVariable = Query.universe().edges("identifier").successors(target);
Q possibleTargetDefinitions = Query.universe().edges("identifier").predecessors(stackVariable);
for(Node possibleTargetDefinition : possibleTargetDefinitions.eval().nodes()) {
Node fromStatement = CommonQueries.getContainingControlFlowNode(possibleTargetDefinition);
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(toStatement)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, toStatement);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.tag(BACKWARD_DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(DEPENDENT_VARIABLE, stackVariable.eval().nodes().one().getAttr(XCSG.name).toString());
}
dataDependenceEdgeSet.add(dataDependenceEdge);
backwardDataDependenceEdgeSet.add(dataDependenceEdge);
}
}
}
try {
if(!pointerDependenceEdgeSet.isEmpty()) {
for(Edge pointerDependenceEdge : pointerDependenceEdgeSet) {
Node fromStatement = pointerDependenceEdge.from();
Node toStatement = pointerDependenceEdge.to();
String dependentVariableName = pointerDependenceEdge.getAttr(DEPENDENT_VARIABLE).toString().replace("=", "");
if(!toStatement.getAttr(XCSG.name).toString().contains(dependentVariableName)) {
// We need to redirect this edge. This is not the right data dependence edge
pointerDependenceEdge.untag(DATA_DEPENDENCE_EDGE);
dataDependenceEdgeSet.remove(pointerDependenceEdge);
AtlasSet<Node> redirectionTargets = getRedirectionTargets(toStatement, dependentVariableName);
for(Node redirectionTarget : redirectionTargets) {
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(redirectionTarget)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, redirectionTarget);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.tag(BACKWARD_DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(DEPENDENT_VARIABLE, dependentVariableName);
}
dataDependenceEdgeSet.add(dataDependenceEdge);
backwardDataDependenceEdgeSet.add(dataDependenceEdge);
}
}
}
}
} catch (NullPointerException e) {
//ignore
}
/**
* Interprocedural Data Dependence
* TODO: Java has different categories of parameters.
* Currently we don't handle the Identity Pass (passing of a 'this' object to the callsite)
*/
// Handle parameters and returns
Q callSites = Common.toQ(dfg).nodes(XCSG.CallSite);
Q dataFlowEdges = Common.universe().edges(XCSG.DataFlow_Edge);
Q passedToEdges = Common.universe().edges(XCSG.PassedTo);
for(Node callSite : callSites.eval().nodes()) {
// Can there be more than one return values to a callsite?
Node returnVariable = Common.toQ(callSite).predecessorsOn(dataFlowEdges).predecessorsOn(dataFlowEdges).eval().nodes().one();
if(returnVariable != null) {
String returnVariableName = returnVariable.getAttr(XCSG.name).toString();
Node fromStatement = CommonQueries.getContainingControlFlowNode(returnVariable);
Node toStatement = CommonQueries.getContainingControlFlowNode(callSite);
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(toStatement)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, toStatement);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.tag(INTERPROCEDURAL_DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, INTERPROCEDURAL_DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(DEPENDENT_VARIABLE, returnVariableName);
}
dataDependenceEdgeSet.add(dataDependenceEdge);
interDataDependenceEdgeSet.add(dataDependenceEdge);
}
AtlasSet<Node> parameterVariables = new AtlasHashSet<Node>();
if(!CommonQueries.isEmpty(Common.toQ(dfg).nodes(XCSG.Language.C))) {
parameterVariables.addAll(Common.toQ(callSite).predecessorsOn(passedToEdges).eval().nodes());
} else {
parameterVariables.addAll(Common.toQ(callSite).predecessorsOn(passedToEdges).nodes(XCSG.Parameter).eval().nodes());
}
for(Node parameterVariable : parameterVariables) {
Node fromStatement = CommonQueries.getContainingControlFlowNode(callSite);
Q targets = Common.toQ(parameterVariable).successorsOn(dataFlowEdges).successorsOn(dataFlowEdges);
String parameterVariableName = parameterVariable.getAttr(XCSG.name).toString();
for(Node target : targets.eval().nodes()) {
Node toStatement = CommonQueries.getContainingControlFlowNode(target);
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(toStatement)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, toStatement);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.tag(INTERPROCEDURAL_DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, INTERPROCEDURAL_DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(DEPENDENT_VARIABLE, parameterVariableName);
}
dataDependenceEdgeSet.add(dataDependenceEdge);
interDataDependenceEdgeSet.add(dataDependenceEdge);
}
}
}
// Handle global variables
Q definitions = Common.toQ(dfg).nodes(XCSG.Assignment);
Q globalVariables = definitions.successorsOn(Common.universe().edges(XCSG.C.Provisional.NominalDataFlow)).nodes(XCSG.C.Provisional.TentativeGlobalVariableDefinition);
for(Node globalVariable : globalVariables.eval().nodes()) {
String globalVariableName = globalVariable.getAttr(XCSG.name).toString();
Q globalVariableUses = Common.toQ(globalVariable).successorsOn(Common.universe().edges(XCSG.C.Provisional.NominalDataFlow));
for(Node globalVariableUse : globalVariableUses.eval().nodes()) {
for(Node definition : definitions.eval().nodes()) {
Node fromStatement = CommonQueries.getContainingControlFlowNode(definition);
Node toStatement = CommonQueries.getContainingControlFlowNode(globalVariableUse);
Q dataDependenceEdges = Query.universe().edges(DATA_DEPENDENCE_EDGE);
Edge dataDependenceEdge = dataDependenceEdges.betweenStep(Common.toQ(fromStatement), Common.toQ(toStatement)).eval().edges().one();
if(dataDependenceEdge == null){
dataDependenceEdge = Graph.U.createEdge(fromStatement, toStatement);
dataDependenceEdge.tag(DATA_DEPENDENCE_EDGE);
dataDependenceEdge.tag(INTERPROCEDURAL_DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(XCSG.name, INTERPROCEDURAL_DATA_DEPENDENCE_EDGE);
dataDependenceEdge.putAttr(DEPENDENT_VARIABLE, globalVariableName);
}
}
}
}
this.ddg = Common.toQ(dataDependenceEdgeSet).eval();
}
public static Q getPointersContained(Q variables) {
Q pointers = Common.empty();
for(Node variable : variables.eval().nodes()) {
Node type = Query.universe().edges(XCSG.TypeOf).successors(Common.toQ(variable)).eval().nodes().one();
if(type.taggedWith(XCSG.Pointer)) {
pointers = pointers.union(Common.toQ(variable));
}
}
return pointers;
}
public AtlasSet<Node> getRedirectionTargets(Node statement, String variable) {
// Log.info(statement.getAttr(XCSG.name) + " : " + variable);
AtlasSet<Node> redirectionTargets = new AtlasHashSet<Node>();
Q predecessors = Query.universe().edges(DATA_DEPENDENCE_EDGE).predecessors(Common.toQ(statement));
for(Node predecessor : predecessors.eval().nodes()) {
if(predecessor.getAttr(XCSG.name).toString().contains(variable)) {
// this is a redirection candidate
// Log.info(predecessor.getAttr(XCSG.name) + "");
redirectionTargets.add(predecessor);
}
}
return redirectionTargets;
}
@Override
public Q getGraph() {
return Common.toQ(ddg);
}
/**
* Returns the underlying data flow graph
* @return
*/
public Q getDataFlowGraph(){
return Common.toQ(dfg);
}
}
| 48.409396 | 205 | 0.732982 |
e32814dbdafaab91903538a234027d0edc11b5b9 | 650 | package com.learning.linnyk.jb._3_annotation_event.event;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
/**
* @author LinnykOleh
*/
@Component
public class MyEventPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher eventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.eventPublisher = applicationEventPublisher;
}
public void publish(){
eventPublisher.publishEvent(new DrawEvent(this));
}
}
| 27.083333 | 96 | 0.84 |
e4cb4ed5c863f922ad29adab8bc7d1e89b290b44 | 2,188 | /*-
*
* This file is part of Oracle NoSQL Database
* Copyright (C) 2011, 2015 Oracle and/or its affiliates. All rights reserved.
*
* Oracle NoSQL Database 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, version 3.
*
* Oracle NoSQL Database 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 in the LICENSE file along with Oracle NoSQL Database. If not,
* see <http://www.gnu.org/licenses/>.
*
* An active Oracle commercial licensing agreement for this product
* supercedes this license.
*
* For more information please contact:
*
* Vice President Legal, Development
* Oracle America, Inc.
* 5OP-10
* 500 Oracle Parkway
* Redwood Shores, CA 94065
*
* or
*
* berkeleydb-info_us@oracle.com
*
* [This line intentionally left blank.]
* [This line intentionally left blank.]
* [This line intentionally left blank.]
* [This line intentionally left blank.]
* [This line intentionally left blank.]
* [This line intentionally left blank.]
* EOF
*
*/
package oracle.kv.impl.api.lob;
import java.util.concurrent.TimeUnit;
import oracle.kv.Consistency;
import oracle.kv.Key;
import oracle.kv.impl.api.KVStoreImpl;
/**
* Superclass of all LOB read operations
*/
public class ReadOperation extends Operation {
protected final Consistency consistency;
public ReadOperation(KVStoreImpl kvsImpl,
Key appLobKey,
Consistency consistency,
long chunkTimeout,
TimeUnit timeoutUnit) {
super(kvsImpl, appLobKey, chunkTimeout, timeoutUnit);
this.consistency = (consistency == null) ?
kvsImpl.getDefaultConsistency() : consistency;
}
public Consistency getConsistency() {
return consistency;
}
}
| 29.173333 | 80 | 0.686472 |
df4f4dec9460646d0a8edae3b396a99a56bb0188 | 377 | package io.vertx.test.codegen.testapi;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
@VertxGen
public interface MethodWithHandlerReturn {
Handler<String> methodWithHandlerStringReturn();
}
| 22.176471 | 65 | 0.782493 |
3bd9a860e6813b83e5062f42c7d43a49e5dd231b | 2,353 | package com.grumpierodin.asap;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import com.grumpierodin.asap.repository.data.Event;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import static org.junit.Assert.assertTrue;
public class EventSerializeText {
@org.junit.Rule
public TestRule watcher = new TestWatcher() {
protected void starting(Description description) {
System.out.println(System.lineSeparator()+"====== " + description.getMethodName());
}
protected void finished(Description description) {
System.out.println(System.lineSeparator()+"finishing " + description.getMethodName());
}
};
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false)
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
@Test
public void CheckEventJsonString() {
try {
String s = "{\"message\":\"testing 1\", \"timestamp\":\"2021-06-06T17:17:00.000\", \"host\":\"localhost\", \"application\":\"app\"}";
Event event = mapper.readValue(s, Event.class);
System.out.println(event.getMessage());
assertTrue("testing 1".equals(event.getMessage()));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Test
public void CheckPartialEventJsonString() {
try {
String s = "{\"message\":\"testing 1\"}";
Event event = mapper.readValue(s, Event.class);
System.out.println(event.getMessage());
System.out.println(event.getTimestamp());
assertTrue("testing 1".equals(event.getMessage()));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
| 39.881356 | 145 | 0.674883 |
b56d080daf9e45ab64a7869ae8cc0e405de4b8a2 | 2,053 | package github.com.adalrsjr1.ltl.events;
import java.util.Objects;
import com.google.common.base.MoreObjects;
public class LabelTransitionSystemEventImpl implements LabelTransitionSystem {
public static final LabelTransitionSystemEventImpl EMPTY_EVENT = new LabelTransitionSystemEventImpl();
private String id = "";
private String name = "";
private String source = "";
private String message = "";
private LabelTransitionSystemEventImpl() { }
private LabelTransitionSystemEventImpl(String id, String name, String source, String message) {
this.id = id;
this.name = name;
this.source = source;
this.message = message;
}
private LabelTransitionSystemEventImpl(LabelTransitionSystemEventImpl event) {
this(event.getId(), event.getName(), event.getSource(), event.getMessage());
}
public static LabelTransitionSystemEventImpl newEvent(String containerId, String containerName, String source, String message) {
return new LabelTransitionSystemEventImpl(containerId, containerName, source, message);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("containerId", id)
.add("containerName", name)
.add("source", source)
.toString();
}
@Override
public boolean equals(Object o) {
if(o == this) return true;
if(! (o instanceof LabelTransitionSystemEventImpl)) return false;
LabelTransitionSystem event = (LabelTransitionSystem) o;
return Objects.equals(id, event.getId()) &&
Objects.equals(name, event.getName()) &&
Objects.equals(message, event.getMessage()) &&
Objects.equals(source, event.getSource());
}
@Override
public int hashCode() {
return Objects.hash(id, name, source, message);
}
@Override
public LabelTransitionSystem getEmpty() {
return EMPTY_EVENT;
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getSource() {
return source;
}
@Override
public String getMessage() {
return message;
}
}
| 25.036585 | 129 | 0.724793 |
330ac986f36ff2d9bd72fcfc2065faee38b733ac | 2,000 | package controllers;
import models.MedicoEntity;
import models.PacienteEntity;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.*;
import java.util.List;
/**
* This controller contains an action to handle HTTP requests
* to the application's home page.
*/
public class HomeController extends Controller {
/**
* An action that renders an HTML page with a welcome message.
* The configuration in the <code>routes</code> file means that
* this method will be called when the application receives a
* <code>GET</code> request with a path of <code>/</code>.
*/
public Result index()
{
MedicoEntity medico = MedicoEntity.FINDER.byId(1L);
return ok(index.render(medico));
}
// public Result index2()
// {
// MedicoEntity medico = MedicoEntity.FINDER.byId(1L);
// return ok(index2.render());
// }
public Result home()
{
MedicoEntity medico = MedicoEntity.FINDER.byId(1L);
return ok(home.render(medico));
}
public Result pacientes()
{
MedicoEntity medico = MedicoEntity.FINDER.byId(1L);
List<PacienteEntity> listaPacientes = MedicoEntity.FINDER.byId(1L).getPacientes();
return ok(pacientes.render(medico,listaPacientes));
}
public Result historial(Long pId)
{
PacienteEntity paciente = PacienteEntity.FINDER.byId(pId);
return ok(historial.render(paciente));
}
public Result marcapasos(Long pId)
{
PacienteEntity paciente = PacienteEntity.FINDER.byId(pId);
return ok(marcapasos.render(paciente));
}
public Result mensajes(Long pId)
{
PacienteEntity paciente = PacienteEntity.FINDER.byId(pId);
MedicoEntity medico = MedicoEntity.FINDER.byId(1L);
return ok(mensajes.render(paciente, medico));
}
public Result citas()
{
MedicoEntity medico = MedicoEntity.FINDER.byId(1L);
return ok(citas.render(medico));
}
}
| 25.641026 | 90 | 0.659 |
39058691f0e19a6c5669f6df53632c374d1e4fee | 1,625 | package unsw.loopmania;
import java.io.File;
import java.util.List;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
/**
* represents an equipped or unequipped Stake in the backend world
*/
public class Stake extends ItemProperty {
private final int damage = 150;
public static IntegerProperty price = new SimpleIntegerProperty(1500);
public Stake(SimpleIntegerProperty x, SimpleIntegerProperty y) {
super(x, y, ItemType.STAKE);
}
public int getDamage(EnemyProperty enemy) {
if (enemy.getType().equals("Vampire")) {
return 2 * damage;
} else {
return damage;
}
}
@Override
public void useDuringBattle(EnemyProperty e, Character c, ModeType mode) {
// TODO Auto-generated method stub
if (e.getType().equals("Vampire")) {
c.setDamage(c.getDamage() + 2 * damage);
} else {
c.setDamage(c.getDamage() + damage);
}
}
@Override
public void characterStepOn(LoopManiaWorld l, List<ItemProperty> toRemoveGold,
List<ItemProperty> toRemoveHealthPotion) {
// TODO Auto-generated method stub
}
@Override
public ImageView onLoadItems() {
return new ImageView(new Image((new File("src/images/stake.png")).toURI().toString()));
}
@Override
public boolean canBePurchased() {
// TODO Auto-generated method stub
return true;
}
} | 28.017241 | 96 | 0.628923 |
c2e291b8229716087cbb1f09806fb431f28d8393 | 4,711 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.security.keyvault.keys.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.BinaryData;
import com.azure.security.keyvault.keys.implementation.BinaryDataJsonDeserializer;
import com.azure.security.keyvault.keys.implementation.BinaryDataJsonSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.Objects;
/**
* A model that represents the policy rules under which the key can be exported.
*/
@Fluent
public final class KeyReleasePolicy {
/**
* The policy rules under which the key can be released. Encoded based on the {@link KeyReleasePolicy#contentType}.
*
* For more information regarding the release policy grammar for Azure Key Vault, please refer to:
* - https://aka.ms/policygrammarkeys for Azure Key Vault release policy grammar.
* - https://aka.ms/policygrammarmhsm for Azure Managed HSM release policy grammar.
*/
@JsonProperty(value = "data")
@JsonSerialize(using = BinaryDataJsonSerializer.class)
@JsonDeserialize(using = BinaryDataJsonDeserializer.class)
private BinaryData encodedPolicy;
/*
* Content type and version of key release policy.
*/
@JsonProperty(value = "contentType")
private String contentType;
/*
* Defines the mutability state of the policy. Once marked immutable on the service side, this flag cannot be reset
* and the policy cannot be changed under any circumstances.
*/
@JsonProperty(value = "immutable")
private Boolean immutable;
KeyReleasePolicy() {
// Empty constructor for Jackson Deserialization
}
/**
* Creates an instance of {@link KeyReleasePolicy}.
*
* @param encodedPolicy The policy rules under which the key can be released. Encoded based on the
* {@link KeyReleasePolicy#contentType}.
*
* For more information regarding the release policy grammar for Azure Key Vault, please refer to:
* - https://aka.ms/policygrammarkeys for Azure Key Vault release policy grammar.
* - https://aka.ms/policygrammarmhsm for Azure Managed HSM release policy grammar.
*/
public KeyReleasePolicy(BinaryData encodedPolicy) {
Objects.requireNonNull(encodedPolicy, "'encodedPolicy' cannot be null.");
this.encodedPolicy = encodedPolicy;
}
/**
* Get a blob encoding the policy rules under which the key can be released.
*
* @return encodedPolicy The policy rules under which the key can be released. Encoded based on the
* {@link KeyReleasePolicy#contentType}.
*
* For more information regarding the release policy grammar for Azure Key Vault, please refer to:
* - https://aka.ms/policygrammarkeys for Azure Key Vault release policy grammar.
* - https://aka.ms/policygrammarmhsm for Azure Managed HSM release policy grammar.
*/
public BinaryData getEncodedPolicy() {
return encodedPolicy;
}
/**
* Get the content type and version of key release policy.
*
* @return The content type and version of key release policy.
*/
public String getContentType() {
return this.contentType;
}
/**
* Set the content type and version of key release policy.
*
* <p>The service default is "application/json; charset=utf-8".</p>
*
* @param contentType The content type and version of key release policy to set.
*
* @return The updated {@link KeyReleasePolicy} object.
*/
public KeyReleasePolicy setContentType(String contentType) {
this.contentType = contentType;
return this;
}
/**
* Get a value indicating if the policy is immutable. Once marked immutable on the service side, this flag cannot
* be reset and the policy cannot be changed under any circumstances.
*
* @return If the {@link KeyReleasePolicy} is immutable.
*/
public Boolean isImmutable() {
return this.immutable;
}
/**
* Get a value indicating if the policy is immutable. Defines the mutability state of the policy. Once marked
* immutable on the service side, this flag cannot be reset and the policy cannot be changed under any
* circumstances.
*
* @param immutable The immutable value to set.
* @return The updated {@link KeyReleasePolicy} object.
*/
public KeyReleasePolicy setImmutable(Boolean immutable) {
this.immutable = immutable;
return this;
}
}
| 36.804688 | 119 | 0.701762 |
44d927caf502aae9683cce619e5806ac5a73afbc | 1,260 | package draw;
/**
* Created by VitRocket on 22.05.2018.
*/
public class Triangle {
public static void main(String[] args) {
drawTriangle(5);
drawTriangle(3);
}
/**
* Вывести треугольник из звездочек в консоли
*
* @param line количество строк
*/
private static void drawTriangle(int line) {
System.out.println("===============================");
for (int i = 0; i < line; i++) {
for (int j = 0; j < line; j++) {
if (j < line - i - 1) {
System.out.print(" ");
} else {
System.out.print("Х");
}
}
System.out.println();
}
System.out.println("===============================");
System.out.println("===============================");
for (int i = 0; i < line; i++) {
for (int j = 0; j < line * 2; j++) {
if (j >= (line) - i - 1 & j <= (line) + i) {
System.out.print("X");
} else {
System.out.print("*");
}
}
System.out.println();
}
System.out.println("===============================");
}
}
| 26.808511 | 62 | 0.360317 |
f08bdd566650b863a226d71b6631771cfd8e09b2 | 147 | package org.omnaest.utils.exception.handler;
public interface RethrowingExceptionHandler
{
public void accept(Exception e) throws Exception;
} | 24.5 | 53 | 0.816327 |
1f29c5411654d226b50017c34ec2cccd41775403 | 923 | // Java program to find n-th Fibonacci number
// Adapted from code by Anant Agarwal.
class Nth_fibonacci_using_goldenratio
{
// Approximate value of golden ratio
static double PHI = 1.6180339;
// Fibonacci numbers upto n = 5
static int f[] = { 0, 1, 1, 2, 3, 5 };
// Function to find nth
// Fibonacci number
static int fib (int n)
{
// Fibonacci numbers for n < 6
if (n < 6)
return f[n];
// Else start counting from
// 5th term
int t = 5;
int fn = 5;
while (t < n) {
fn = (int)Math.round(fn * PHI);
t++;
}
return fn;
}
public static void main (String[] args)
{
int fibNo;
fibNo = fib(9); //RETURNS 34
fibNo = fib(8); //RETURNS 21
fibNo = fib(7); //RETURNS 13
}
}
| 23.075 | 46 | 0.473456 |
faedd0d42f7879db9039b80b772ea139102e7089 | 9,337 | package com.evenuk.evenukapp;
import android.app.SearchManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.evenuk.business.Comentario;
import com.evenuk.business.Feed;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.api.model.StringList;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import static java.text.SimpleDateFormat.*;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemClickListener {
private ListView listView;
private AdapterFeedListView adapterFeedListView;
private ArrayList<Feed> itens;
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
FirebaseUser user;
FirebaseDatabase database;
DatabaseReference reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("authStateListener", "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d("authStateListener", "onAuthStateChanged:signed_out");
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
finish();
}
// ...
}
};
if (user != null) {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//SearchView searchToolBar = (SearchView) toolbar.findViewById(R.id.action_search);
//searchToolBar.setIconifiedByDefault(true);
//searchToolBar.setQueryHint(getResources().getString(R.string.hint_search));
//FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//fab.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
//});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//((TextView) getWindow().findViewById(R.id.user_name_view)).setText(user.getDisplayName());
View headerView = navigationView.getHeaderView(0);
((TextView) headerView.findViewById(R.id.user_email_view)).setText(user.getEmail());
listView = (ListView) findViewById(R.id.listItemFeed);
listView.setOnItemClickListener(this);
createListView();
} else {
startActivity(new Intent(this, LoginActivity.class));
finish();
}
}
private void createListView() {
itens = new ArrayList<Feed>();
//itens.add(new Feed(1, "Danilo Avilez", "Estilo Night", new Date(), "Lorem ipsum not have tilt", new ArrayList<Comentario>(), new ArrayList<String>()));
//itens.add(new Feed(2, "Adriel Andrade", "Estilo Tanga", new Date(), "Lorem ipsum not have tilt", new ArrayList<Comentario>(), new ArrayList<String>()));
database = FirebaseDatabase.getInstance();
Query reference = database.getReference("feeds").limitToLast(10);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot feedSnapshot : dataSnapshot.getChildren()) {
Feed feed = new Feed();
feed.setAutor((String) feedSnapshot.child("Autor").getValue());
feed.setDescricaoEvento((String) feedSnapshot.child("DescricaoEvento").getValue());
feed.setTituloEvento((String) feedSnapshot.child("TituloEvento").getValue());
try {
feed.setDataEvento(simpleDateFormat.parse(feedSnapshot.child("DataEvento").getValue().toString()));
} catch (ParseException e) {
e.printStackTrace();
}
itens.add(feed);
}
adapterFeedListView = new AdapterFeedListView(getApplicationContext(), itens);
listView.setAdapter(adapterFeedListView);
listView.setCacheColorHint(Color.TRANSPARENT);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "The read failed: " + databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_manage) {
// Handle settings
startActivity(new Intent(this, SettingsActivity.class));
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Feed item = (Feed) adapterFeedListView.getItem(i);
Toast.makeText(getApplicationContext(), "Você clicou em: " + item.getTituloEvento(), Toast.LENGTH_SHORT).show();
}
} | 37.955285 | 162 | 0.656099 |
ce53f07d07adebf65605b9bfd5a55a9b99b75488 | 1,689 | package com.decompiler.bytecode.opcode;
import com.decompiler.bytecode.analysis.opgraph.Op01WithProcessedDataAndByteJumps;
import com.decompiler.entities.constantpool.ConstantPool;
import com.decompiler.util.ConfusedDecompilerException;
import com.decompiler.util.bytestream.ByteData;
public class OperationFactoryWide extends OperationFactoryDefault {
private static JVMInstr getWideInstrVersion(JVMInstr instr) {
switch (instr) {
case IINC:
return JVMInstr.IINC_WIDE;
case ILOAD:
return JVMInstr.ILOAD_WIDE;
case FLOAD:
return JVMInstr.FLOAD_WIDE;
case ALOAD:
return JVMInstr.ALOAD_WIDE;
case LLOAD:
return JVMInstr.LLOAD_WIDE;
case DLOAD:
return JVMInstr.DLOAD_WIDE;
case ISTORE:
return JVMInstr.ISTORE_WIDE;
case FSTORE:
return JVMInstr.FSTORE_WIDE;
case ASTORE:
return JVMInstr.ASTORE_WIDE;
case LSTORE:
return JVMInstr.LSTORE_WIDE;
case DSTORE:
return JVMInstr.DSTORE_WIDE;
case RET:
return JVMInstr.RET_WIDE;
default:
throw new ConfusedDecompilerException("Wide is not defined for instr " + instr);
}
}
@Override
public Op01WithProcessedDataAndByteJumps createOperation(JVMInstr instr, ByteData bd, ConstantPool cp, int offset) {
JVMInstr widenedInstr = getWideInstrVersion(JVMInstr.find(bd.getS1At(1)));
return widenedInstr.createOperation(bd, cp, offset);
}
}
| 35.93617 | 120 | 0.626998 |
dd5a924ec0b8974ab673c9aeb50eecdfe779327c | 390 | package com.macro.mall.dto;
import java.util.List;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class PmsCloudProductAddParam {
@ApiModelProperty(value = "商品ID")
private List<Long> productIds;
@ApiModelProperty(value = "佣金配置ID")
private Long commissionConfigId;
@ApiModelProperty(hidden = true)
private String merchantCode;
}
| 21.666667 | 47 | 0.751282 |
a4b3ffcf68233b2451690f078e7622f174986197 | 1,306 | package fi.om.municipalityinitiative.dto.service;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import fi.om.municipalityinitiative.json.JsonId;
import fi.om.municipalityinitiative.util.Locales;
import fi.om.municipalityinitiative.web.Urls;
import java.util.Locale;
@JsonPropertyOrder(alphabetic = true)
public class Municipality {
private final Long id;
private final String finnishName;
private final String swedishName;
private final boolean active;
public Municipality(long id, String finnishName, String swedishName, Boolean active) {
this.id = id;
this.finnishName = finnishName;
this.swedishName = swedishName;
this.active = active;
}
@JsonId(path= Urls.MUNICIPALITY, useApiUrl = true)
public Long getId() {
return id;
}
public String getNameFi() {
return finnishName;
}
public String getNameSv() {
return swedishName;
}
public String getLocalizedName(Locale locale) {
return Locales.LOCALE_FI.equals(locale)
? getNameFi()
: getNameSv();
}
public String getName(String locale) {
return getLocalizedName(Locale.forLanguageTag(locale));
}
public boolean isActive() {
return active;
}
}
| 25.607843 | 90 | 0.67611 |
2a60776b1b533f37e570b584f01c6e03212f3a47 | 10,248 | /* =======================================================
Copyright 2014 - ePortfolium - Licensed under the
Educational Community License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.osedu.org/licenses/ECL-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 ca.mati.portfolio.fileserveur;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A servlet to store and retrieve files from different persistent backends.
* Implemented: SQL backend (MySQL) and File System backend
*/
// @WebServlet("/user/*")
// Moved to <servlet> in the web.xml
// @MultipartConfig(maxFileSize = 104857600) // upload file's size up to 100 MB
// Moved to <multipart-config> in the web.xml
public class FileServerServlet extends HttpServlet
{
public static final String KARUTA_ENV_HOME = "KARUTA_HOME";
public static final String KARUTA_PROP_HOME = "karuta.home";
final Logger logger = LoggerFactory.getLogger(FileServerServlet.class);
private String serverType;
private String configPath;
private String baseFolder;
public static final boolean TRACE = false;
private static final long serialVersionUID = 1L;
// size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
@Override
public void init() throws ServletException {
logger.info("FileServerServlet starting");
serverType = getServletConfig().getServletContext().getInitParameter("serverType");
try {
this.loadConfigDirectory();
} catch (Exception e) {
logger.error("Error in initializing servlet: ", e);
throw new ServletException(e);
}
}
private void loadConfigDirectory() throws IOException, InternalError {
final String configEnvDir = System.getenv(KARUTA_ENV_HOME);
final String configPropDir = System.getProperty(KARUTA_PROP_HOME);
// The jvm property override the environment property if set
final String configDir = (configPropDir != null && !configPropDir.trim().isEmpty()) ? configPropDir : configEnvDir;
final String servName = getServletConfig().getServletContext().getContextPath();
if (configDir != null && !configDir.trim().isEmpty()) {
final File base = new File(configDir.trim());
if (base.exists() && base.isDirectory() && base.canWrite()) {
try {
baseFolder = base.getCanonicalPath();
configPath = baseFolder + servName +"_config" + File.separatorChar;
logger.info("FileServerServlet configpath @ " + configPath);
} catch (IOException e) {
logger.error("The Configuration directory '" + configDir + "' wasn't defined", e);
throw e;
}
} else {
throw new IllegalArgumentException("The environment variable '" + KARUTA_ENV_HOME + "' '" + configEnvDir
+ "' or the jvm property '" + KARUTA_PROP_HOME + "' '" + configPropDir
+ "' doesn't exist or isn't writable. Please provide a writable directory path !");
}
} else {
throw new IllegalArgumentException("The environment variable '" + KARUTA_ENV_HOME
+ "' or the jvm property '" + KARUTA_PROP_HOME + "' wasn't set.");
}
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String uuid = request.getPathInfo();
uuid = uuid.substring(1);
try
{
// String path = getServletContext().getRealPath("/");
PersistenceFactory factory = new PersistenceFactory(serverType);
String app = request.getHeader("app");
ApiFilePersistence filePersistence = factory.createFilePersistence(baseFolder, configPath, app);
String message;
if ( filePersistence.isFileDeleted(uuid) ) {
response.setStatus(400);
message = "400 - ERROR - resource: " + uuid + " is already deleted";
} else {
message = "200 - " + filePersistence.deleteFile(uuid);
}
PrintWriter out = response.getWriter();
out.println(message);
out.close();
request.getInputStream().close();
} catch (Exception e) {
response.setStatus(500);
response.getWriter().print("500 - ERROR: " + e.getMessage());
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String uuid = request.getPathInfo();
uuid = uuid.substring(1);
if( "".equals(uuid) )
{
request.getInputStream().close();
response.getWriter().close();
return;
}
String split[] = uuid.split("/");
uuid = split[0];
String thumbvar=null;
if( split.length > 1 )
thumbvar = split[1];
boolean isThumbnail = false;
if("thumb".equals(thumbvar))
isThumbnail = true;
OutputStream outStream = response.getOutputStream();
try
{
// String path = getServletContext().getRealPath("/");
PersistenceFactory factory = new PersistenceFactory(serverType);
String app = request.getHeader("app");
ApiFilePersistence filePersistence = factory.createFilePersistence(baseFolder, configPath, app);
InputStream inputStream = filePersistence.getFileInputStream(uuid, isThumbnail);
int fileLength = inputStream.available();
if (TRACE) logger.info("fileLength = " + fileLength);
response.setContentLength(fileLength);
// write the file to the client
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
int total = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
total += bytesRead;
}
logger.info("Total = " + total);
outStream.flush();
outStream.close();
inputStream.close();
} catch (IOException exIO) {
response.setStatus(500);
PrintWriter writer = new PrintWriter(outStream);
writer.print("500 - ERROR - IO Error: " + exIO.getMessage());
} catch (SQLException exSql ) {
response.setStatus(500);
PrintWriter writer = new PrintWriter(outStream);
writer.print("500 - ERROR - SQL Error: " + exSql.getMessage());
} catch (Exception e) {
response.setStatus(500);
PrintWriter writer = new PrintWriter(outStream);
writer.print("500 - ERROR: " + e.getMessage());
}
finally
{
outStream.close();
request.getInputStream().close();
}
}
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String uuid = request.getPathInfo();
uuid = uuid.substring(1);
/// Ensure file id is a uuid
if( "".equals(uuid) )
uuid = UUID.randomUUID().toString();
else
try
{
UUID test = UUID.fromString(uuid);
uuid = test.toString();
}
catch( IllegalArgumentException e )
{
// Invalid create a new one
uuid = UUID.randomUUID().toString();
}
try
{
// String path = getServletContext().getRealPath("/");
PersistenceFactory factory = new PersistenceFactory(serverType);
String app = request.getHeader("app");
logger.debug("APP: "+app+" "+configPath);
ApiFilePersistence filePersistence = factory.createFilePersistence(baseFolder, configPath, app);
// get input stream of the upload file
String doCopy = request.getParameter("copy");
InputStream inputStream = null;
if( doCopy != null )
{
/// Read file directly
inputStream = filePersistence.getFileInputStream(uuid, false);
/// Generate a new legit uuid
uuid = UUID.randomUUID().toString();
}
else
inputStream = request.getInputStream();
logger.debug("Input stream for: "+uuid);
uuid = filePersistence.saveFile(uuid, inputStream);
} catch (SQLException exSql) {
response.setStatus(500);
response.getWriter().print("500 - ERROR - IO Error: " + exSql.getMessage());
} catch (Exception e) {
response.setStatus(500);
response.getWriter().print("500 - ERROR: " + e.getMessage());
}
PrintWriter writer = response.getWriter();
writer.write(uuid);
writer.close();
request.getInputStream().close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String uuid = request.getPathInfo();
uuid = uuid.substring(1);
/// Ensure file id is a uuid
if( "".equals(uuid) )
uuid = UUID.randomUUID().toString();
else
try
{
UUID test = UUID.fromString(uuid);
uuid = test.toString();
}
catch( IllegalArgumentException e )
{
// Invalid create a new one
uuid = UUID.randomUUID().toString();
}
try
{
// String path = getServletContext().getRealPath("/");
PersistenceFactory factory = new PersistenceFactory(serverType);
String app = request.getHeader("app");
logger.debug("APP: "+app+" "+configPath);
ApiFilePersistence filePersistence = factory.createFilePersistence(baseFolder, configPath, app);
// get input stream of the upload file
String doCopy = request.getParameter("copy");
InputStream inputStream = null;
if( doCopy != null )
{
/// Read file directly
inputStream = filePersistence.getFileInputStream(uuid, false);
/// Generate a new legit uuid
uuid = UUID.randomUUID().toString();
}
else
inputStream = request.getInputStream();
logger.debug("Input stream for: "+uuid);
uuid = filePersistence.saveFile(uuid, inputStream);
} catch (SQLException exSql) {
response.setStatus(500);
response.getWriter().print("500 - ERROR - IO Error: " + exSql.getMessage());
} catch (Exception e) {
e.printStackTrace();
response.setStatus(500);
response.getWriter().print("500 - ERROR: " + e.getMessage());
}
PrintWriter writer = response.getWriter();
writer.write(uuid);
writer.close();
request.getInputStream().close();
}
} | 31.727554 | 119 | 0.69555 |
9902e78c07a859d896ca74966b656406bdd40d28 | 5,576 | package com.chutneytesting.task.micrometer;
import static com.chutneytesting.task.micrometer.MicrometerCounterTask.OUTPUT_COUNTER;
import static com.chutneytesting.task.micrometer.MicrometerTaskTestHelper.assertSuccessAndOutputObjectType;
import static com.chutneytesting.task.micrometer.MicrometerTaskTestHelper.buildMeterName;
import static io.micrometer.core.instrument.Metrics.globalRegistry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.chutneytesting.task.TestLogger;
import com.chutneytesting.task.spi.TaskExecutionResult;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.List;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;
public class MicrometerCounterTaskTest {
private MicrometerCounterTask sut;
private final String METER_NAME_PREFIX = "counterName";
@Test
public void counter_increment_must_be_number() {
MicrometerCounterTask no_number = new MicrometerCounterTask(null, buildMeterName(METER_NAME_PREFIX), null, null, null, null, null, "no number");
List<String> errors = no_number.validateInputs();
assertThat(errors.size()).isEqualTo(1);
assertThat(errors.get(0)).isEqualTo("[increment parsing] not applied because of exception java.lang.NumberFormatException(For input string: \"no number\")");
}
@Test
public void counter_name_is_mandatory_if_no_given_counter() {
assertThatThrownBy(() ->
new MicrometerCounterTask(null, null, null, null, null, null, null, null).execute()
).isExactlyInstanceOf(NullPointerException.class);
}
@Test
public void should_create_micrometer_counter() {
// Given
MeterRegistry registry = new SimpleMeterRegistry();
String meterName = buildMeterName(METER_NAME_PREFIX);
sut = new MicrometerCounterTask(new TestLogger(), meterName, null, null, null, null, registry, null);
// When
TaskExecutionResult result = sut.execute();
// Then
assertSuccessAndCounterObjectType(result);
Counter outputCounter = (Counter) result.outputs.get(OUTPUT_COUNTER);
assertThat(registry.find(meterName).counter()).isEqualTo(outputCounter);
assertThat(outputCounter.count()).isEqualTo(0);
}
@Test
public void should_create_micrometer_counter_and_register_it_on_given_registry() {
// Given
MeterRegistry givenMeterRegistry = new SimpleMeterRegistry();
String meterName = buildMeterName(METER_NAME_PREFIX);
sut = new MicrometerCounterTask(new TestLogger(), meterName, "description", "my unit", Lists.list("tag", "my tag value"), null, givenMeterRegistry, null);
// When
TaskExecutionResult result = sut.execute();
// Then
assertSuccessAndCounterObjectType(result);
Counter outputCounter = (Counter) result.outputs.get(OUTPUT_COUNTER);
assertThat(globalRegistry.find(meterName).counters()).isEmpty();
assertThat(givenMeterRegistry.find(meterName).counter()).isEqualTo(outputCounter);
assertThat(outputCounter.getId().getDescription()).isEqualTo("description");
assertThat(outputCounter.getId().getBaseUnit()).isEqualTo("my unit");
assertThat(outputCounter.getId().getTag("tag")).isEqualTo("my tag value");
}
@Test
public void should_create_and_increment_micrometer_counter() {
// Given
MeterRegistry registry = new SimpleMeterRegistry();
sut = new MicrometerCounterTask(new TestLogger(), buildMeterName(METER_NAME_PREFIX), null, null, null, null, registry, "5.0");
// When
TaskExecutionResult result = sut.execute();
// Then
assertSuccessAndCounterObjectType(result);
Counter outputCounter = (Counter) result.outputs.get(OUTPUT_COUNTER);
assertThat(outputCounter.count()).isEqualTo(5);
}
@Test
public void should_increment_given_counter() {
// Given
MeterRegistry registry = new SimpleMeterRegistry();
Counter givenCounter = registry.counter(buildMeterName(METER_NAME_PREFIX));
givenCounter.increment(3);
sut = new MicrometerCounterTask(new TestLogger(), null, null, null, null, givenCounter, registry, "5.0");
// When
TaskExecutionResult result = sut.execute();
// Then
assertSuccessAndCounterObjectType(result);
Counter outputCounter = (Counter) result.outputs.get(OUTPUT_COUNTER);
assertThat(outputCounter).isEqualTo(givenCounter);
assertThat(outputCounter.count()).isEqualTo(8);
}
@Test
public void should_log_increment_and_current_count() {
// Given
TestLogger logger = new TestLogger();
sut = new MicrometerCounterTask(logger, buildMeterName(METER_NAME_PREFIX), null, null, null, null, new SimpleMeterRegistry(), "5.0");
// When
TaskExecutionResult result = sut.execute();
// Then
assertSuccessAndCounterObjectType(result);
assertThat(logger.info).hasSize(2);
assertThat(logger.info.get(0)).isEqualTo("Counter incremented by 5.0");
assertThat(logger.info.get(1)).isEqualTo("Counter current count is 5.0");
}
private void assertSuccessAndCounterObjectType(TaskExecutionResult result) {
assertSuccessAndOutputObjectType(result, OUTPUT_COUNTER, Counter.class);
}
}
| 41 | 165 | 0.718257 |
0ee4f0e80225804c9657b8ed7efd7cc835da78b3 | 4,244 | package cn.itcast.travel.web.servlet;
import cn.itcast.travel.domain.PageBean;
import cn.itcast.travel.domain.Route;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.service.FavoriteService;
import cn.itcast.travel.service.RouteService;
import cn.itcast.travel.service.impl.FavoriteServiceImpl;
import cn.itcast.travel.service.impl.RouteServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/route/*")
public class RouteServlet extends BaseServlet {
private RouteService routeService = new RouteServiceImpl();
private FavoriteService favoriteService = new FavoriteServiceImpl();
/**
* 分页查询
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void pageQuery(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接受客户端参数
String currentPageStr = request.getParameter("currentPage");
String pageSizeStr = request.getParameter("pageSize");
String cidStr = request.getParameter("cid");
String rname = request.getParameter("rname");
// System.out.println("current"+currentPageStr);
//2.处理参数
int currentPage = 0;
int pageSize = 0;
int cid = 0;
if (currentPageStr != null && currentPageStr.length() > 0) {
currentPage = Integer.parseInt(currentPageStr);
} else {
currentPage = 1;//当前页码,如果不传,默认为第一页
}
if (pageSizeStr != null && pageSizeStr.length() > 0) {
pageSize = Integer.parseInt(pageSizeStr);
} else {
pageSize = 5;//每页显示条数,如果不传,默认每页显示5条记录
}
if (cidStr != null && cidStr.length() > 0 && !"null".equals(cidStr)) {
cid = Integer.parseInt(cidStr);
}
if (rname != null) {
rname = new String(rname.getBytes("iso-8859-1"), "utf-8");
}
// System.out.println(cid+"");
//3.调用service查询PageBean对象
PageBean<Route> pb = routeService.pageQuery(cid, currentPage, pageSize, rname);
//4.将PageBean对象序列化为json,返回
writeValue(response, pb);
}
/**
* 根据id查询一个旅游线路的详细信息
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收id
int rid = Integer.parseInt(request.getParameter("rid"));
//2.调用service查询route对象
Route route = routeService.findOne(rid);
//3.转成json写回客户端
writeValue(response, route);
}
/**
* 判断当前登录用户是否收藏过该线路
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void isFavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取线路id
String rid = request.getParameter("rid");
//获取用户id
User user = (User) request.getSession().getAttribute("user");
int uid;
if (user == null) {//用户未登录
uid = 0;//数据库中查不到
} else {//用户已登录
uid = user.getUid();
}
// System.out.println(uid);
//调用FavoriteService查询是否收藏
boolean flag = favoriteService.isFavorite(rid, uid);
//写回客户端
writeValue(response, flag);
}
/**
* 添加收藏
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void addFavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String rid = request.getParameter("rid");
User user = (User) request.getSession().getAttribute("user");
int uid;
if (user == null) {//用户未登录
return;//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
} else {//用户已登录
uid = user.getUid();
}
favoriteService.add(rid, uid);
}
}
| 32.646154 | 124 | 0.624175 |
f9a7c5e2a25ea0de4f172880c9274d26fd33ee3c | 340 | package net.serenitybdd.screenplay.amazon.pages;
import net.serenitybdd.core.pages.PageObject;
public class HomePageLeftNavigation extends PageObject {
public static String optBooklang = "//li[@aria-label='%s']//input";
public static String booklang(String booklang) {
return String.format(optBooklang, booklang);
}
}
| 30.909091 | 71 | 0.747059 |
9e27bb86e0c03cd41dd876735f75924d20e313d4 | 700 | public class PlayerHealth {
public static void main(String args[]) throws Exception {
PlayerHealth playerHealth = new PlayerHealth();
playerHealth.Health();
}
public void Health()
{
boolean player = true;
boolean enemy = false;
int playerHealth = 100;
if (enemy != player)
{
System.out.println("Enemy attack player");
playerHealth = 0; // Update player health
if (playerHealth <= 0)
{
System.out.println("Player is dead");
}
}
else
{
System.out.println("Enemy is not attack player(Lazy)");
}
}
}
| 21.875 | 67 | 0.512857 |
d856bc40236483ccb6710c067b1ca7fadbfeec0b | 2,466 | /**
* The MIT License
* Copyright (c) 2016 Population Register Centre
*
* 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 fi.vm.kapa.rova.external.model;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import fi.vm.kapa.rova.engine.model.ypa.IssueRoleType;
import fi.vm.kapa.rova.engine.model.ypa.ResultRoleType;
import java.io.IOException;
import static fi.vm.kapa.rova.external.model.AuthorizationType.*;
public class ResultTypeDeserializer extends JsonDeserializer<IResultType> {
@Override
public IResultType deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException {
ObjectCodec oc = jp.getCodec();
JsonNode rootNode = oc.readTree(jp);
IResultType result = null;
String nodeAsText = rootNode.asText();
if (nodeAsText.startsWith("http")) {
result = new IssueRoleType(nodeAsText);
} else if (nodeAsText.equals(ALLOWED.toString()) || nodeAsText.equals(DISALLOWED.toString())
|| nodeAsText.equals(UNKNOWN.toString())) {
result = AuthorizationType.valueOf(nodeAsText);
} else {
result = ResultRoleType.valueOf(nodeAsText);
}
return result;
}
}
| 40.42623 | 100 | 0.735604 |
1476b304f091e085a3a63b965f781486a1b6cc01 | 5,488 | /*
* Jexer - Java Text User Interface
*
* The MIT License (MIT)
*
* Copyright (C) 2021 Autumn Lamonte
*
* 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.
*
* @author Autumn Lamonte [AutumnWalksTheLake@gmail.com] ⚧ Trans Liberation Now
* @version 1
*/
package jexer.help;
import java.util.List;
import jexer.TWidget;
/**
* TParagraph contains a reflowable collection of TWords, some of which are
* clickable links.
*/
public class TParagraph extends TWidget {
// ------------------------------------------------------------------------
// Constants --------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Variables --------------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Topic text and links converted to words.
*/
private List<TWord> words;
/**
* If true, add one row to height as a paragraph separator. Note package
* private access.
*/
boolean separator = true;
// ------------------------------------------------------------------------
// Constructors -----------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Public constructor.
*
* @param parent parent widget
* @param words the pieces of the paragraph to display
*/
public TParagraph(final THelpText parent, final List<TWord> words) {
// Set parent and window
super(parent, 0, 0, parent.getWidth() - 1, 1);
this.words = words;
for (TWord word: words) {
word.setParent(this, false);
}
reflowData();
}
// ------------------------------------------------------------------------
// TWidget ----------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// TParagraph -------------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Reposition the words in this paragraph to reflect the new width, and
* set the paragraph height.
*/
public void reflowData() {
int x = 0;
int y = 0;
for (TWord word: words) {
if (x + word.getWidth() >= getWidth()) {
x = 0;
y++;
}
word.setX(x);
word.setY(y);
x += word.getWidth() + 1;
}
if (separator) {
setHeight(y + 2);
} else {
setHeight(y + 1);
}
}
/**
* Try to select a previous link.
*
* @return true if there was a previous link in this paragraph to select
*/
public boolean up() {
if (words.size() == 0) {
return false;
}
if (getActiveChild() == this) {
// No selectable links
return false;
}
TWord firstWord = null;
TWord lastWord = null;
for (TWord word: words) {
if (word.isEnabled()) {
if (firstWord == null) {
firstWord = word;
}
lastWord = word;
}
}
if (getActiveChild() == firstWord) {
return false;
}
switchWidget(false);
return true;
}
/**
* Try to select a next link.
*
* @return true if there was a next link in this paragraph to select
*/
public boolean down() {
if (words.size() == 0) {
return false;
}
if (getActiveChild() == this) {
// No selectable links
return false;
}
TWord firstWord = null;
TWord lastWord = null;
for (TWord word: words) {
if (word.isEnabled()) {
if (firstWord == null) {
firstWord = word;
}
lastWord = word;
}
}
if (getActiveChild() == lastWord) {
return false;
}
switchWidget(true);
return true;
}
}
| 31.181818 | 79 | 0.445882 |
736cb4c4bb9e80a3efa4c323da919d02a7c2cfc5 | 2,746 | package org.smartframework.cloud.examples.basic.auth.controller.oms;
import org.smartframework.cloud.api.core.annotation.RequireDataSecurity;
import org.smartframework.cloud.api.core.annotation.RequireRepeatSubmitCheck;
import org.smartframework.cloud.api.core.annotation.RequireTimestamp;
import org.smartframework.cloud.api.core.annotation.auth.RequirePermissions;
import org.smartframework.cloud.api.core.annotation.auth.RequireRoles;
import org.smartframework.cloud.api.core.annotation.enums.Role;
import org.smartframework.cloud.common.pojo.Response;
import org.smartframework.cloud.examples.basic.auth.service.oms.UserRoleOmsService;
import org.smartframework.cloud.examples.basic.rpc.auth.request.oms.user.role.UserRoleCreateReqVO;
import org.smartframework.cloud.examples.basic.rpc.auth.request.oms.user.role.UserRoleUpdateReqVO;
import org.smartframework.cloud.examples.basic.rpc.auth.response.oms.user.role.UserRoleRespVO;
import org.smartframework.cloud.starter.core.business.util.RespUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* 用户角色信息
*
* @author collin
* @date 2021-07-04
* @status done
*/
@RestController
@RequestMapping("auth/oms/user/role")
@Validated
public class UserRoleOmsController {
@Autowired
private UserRoleOmsService userRoleOmsService;
/**
* 添加用户角色
*
* @param req
* @return
*/
@PostMapping("create")
@RequireRoles(Role.ADMIN)
@RequirePermissions("auth:user:role:create")
@RequireDataSecurity
@RequireRepeatSubmitCheck
@RequireTimestamp
public Response<Boolean> create(@RequestBody @Valid UserRoleCreateReqVO req) {
return RespUtil.success(userRoleOmsService.create(req));
}
/**
* 修改用户角色信息
*
* @param req
* @return
*/
@PostMapping("update")
@RequireRoles(Role.ADMIN)
@RequirePermissions("auth:user:role:update")
@RequireDataSecurity
@RequireTimestamp
public Response<Boolean> update(@RequestBody @Valid UserRoleUpdateReqVO req) {
return RespUtil.success(userRoleOmsService.update(req));
}
/**
* 查询用户所拥有的角色权限
*
* @param uid
* @return
*/
@GetMapping("listRole")
@RequireRoles(Role.ADMIN)
@RequirePermissions("auth:user:role:listRole")
@RequireTimestamp
public Response<List<UserRoleRespVO>> listRole(@NotNull Long uid) {
return RespUtil.success(userRoleOmsService.listRole(uid));
}
} | 33.084337 | 99 | 0.730153 |
4a6d8ff8f39d5b64b020c04f08ae096843dad4d4 | 1,069 | package com.dcits.dcwlt.common.pay.enums;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* 业务拒绝码
*
*
* @date 2021/1/3
*/
public enum RejectCdEnum {
PR02("PR02","处理中"),
PR03("PR03","推定成功"),
PR04("PR04","推定失败"),
R004("R004", "请求非法"),
R005("R005", "请求报文格式有误"),
R006("R006", "请求报文必填参数缺失"),
R007("R007", "请求报文参数有误"),
R008("R008", "请求报文字段长度超限"),
R999("R999","机构自定义原因失败说明"),
SUCCESS("000000","交易成功")
;
private static final Set<String> enumSet = new HashSet<>(4);
static {
Arrays.asList(ChangeCdEnum.values()).forEach(e -> enumSet.add(e.getCode()));
}
public static boolean hasEnum(String code){
return enumSet.contains(code);
}
private String code;
private String desc;
RejectCdEnum(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
| 19.796296 | 85 | 0.55753 |
87303d8c9f5f1358de3d49415a8787ebb8016489 | 1,677 | package factionmod.manager.instanciation;
import factionmod.manager.IChunkManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraftforge.common.util.Constants.NBT;
import net.minecraftforge.common.util.INBTSerializable;
/**
* Used to instanciate an {@link IChunkManager} from the name of the
* {@link Zone} an its arguments.
*
* @author BrokenSwing
*
*/
public class ZoneInstance implements INBTSerializable<NBTTagCompound> {
private String zoneName;
private String[] args;
public ZoneInstance(final String name, final String[] args) {
this.zoneName = name;
this.args = args;
}
public ZoneInstance(final NBTTagCompound nbt) {
this.deserializeNBT(nbt);
}
public String getZoneName() {
return zoneName;
}
public String[] getArgs() {
return args;
}
@Override
public NBTTagCompound serializeNBT() {
final NBTTagCompound nbt = new NBTTagCompound();
nbt.setString("name", this.zoneName);
final NBTTagList argsList = new NBTTagList();
for (final String arg : this.args)
argsList.appendTag(new NBTTagString(arg));
nbt.setTag("args", argsList);
return nbt;
}
@Override
public void deserializeNBT(final NBTTagCompound nbt) {
this.zoneName = nbt.getString("name");
final NBTTagList argsList = nbt.getTagList("args", NBT.TAG_STRING);
this.args = new String[argsList.tagCount()];
for (int i = 0; i < argsList.tagCount(); i++)
this.args[i] = argsList.getStringTagAt(i);
}
}
| 27.048387 | 75 | 0.667859 |
5a337b50872f2da10dffe565c78f1673178c8da6 | 11,251 | /*
* Copyright 2014 IBM Corp. 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.ibm.bluelist;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.directions.sample.R;
import com.ibm.mobile.services.data.IBMDataException;
import com.ibm.mobile.services.data.IBMDataObject;
import com.ibm.mobile.services.data.IBMQuery;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import bolts.Continuation;
import bolts.Task;
public class MainActivity extends Activity implements OnEditorActionListener{
List<Item> itemList;
BlueListApplication blApplication;
ArrayAdapter<Item> lvArrayAdapter;
ActionMode mActionMode = null;
int listItemPosition;
public static final String CLASS_NAME="MainActivity";
@Override
/**
* onCreate called when main activity is created.
*
* Sets up the itemList, application, and sets listeners.
*
* @param savedInstanceState
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluemix_activity_main);
/* Use application class to maintain global state. */
blApplication = (BlueListApplication) getApplication();
itemList = blApplication.getItemList();
/* Set up the array adapter for items list view. */
ListView itemsLV = (ListView)findViewById(R.id.itemsList);
lvArrayAdapter = new ArrayAdapter<Item>(this, R.layout.list_item_1, itemList);
itemsLV.setAdapter(lvArrayAdapter);
/* Refresh the list. */
listItems();
/* Set long click listener. */
itemsLV.setOnItemLongClickListener(new OnItemLongClickListener() {
/* Called when the user long clicks on the textview in the list. */
public boolean onItemLongClick(AdapterView<?> adapter, View view, int position,
long rowId) {
listItemPosition = position;
if (mActionMode != null) {
return false;
}
/* Start the contextual action bar using the ActionMode.Callback. */
mActionMode = MainActivity.this.startActionMode(mActionModeCallback);
return true;
}
});
EditText pass = (EditText) findViewById(R.id.edt_pass);
EditText itemToAdd = (EditText) findViewById(R.id.itemToAdd);
/* Set key listener for edittext (done key to accept item to list). */
itemToAdd.setOnEditorActionListener(this);
pass.setOnEditorActionListener(this);
itemToAdd.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
createItem(v);
return true;
}
return false;
}
});
/* Set key listener for edittext (done key to accept item to list). */
pass.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId==EditorInfo.IME_ACTION_DONE){
createItem(v);
return true;
}
return false;
}
});
}
/**
* Removes text on click of x button.
*
* @param v the edittext view.
*/
public void clearText(View v) {
EditText itemToAdd = (EditText) findViewById(R.id.itemToAdd);
EditText pass = (EditText) findViewById(R.id.edt_pass);
itemToAdd.setText("");
pass.setText("");
}
/**
* Refreshes itemList from data service.
*
* An IBMQuery is used to find all the list items.
*/
public void listItems() {
try {
IBMQuery<Item> query = IBMQuery.queryForClass(Item.class);
// Query all the Item objects from the server.
query.find().continueWith(new Continuation<List<Item>, Void>() {
@Override
public Void then(Task<List<Item>> task) throws Exception {
final List<Item> objects = task.getResult();
// Log if the find was cancelled.
if (task.isCancelled()){
Log.e(CLASS_NAME, "Exception : Task " + task.toString() + " was cancelled.");
}
// Log error message, if the find task fails.
else if (task.isFaulted()) {
Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
}
// If the result succeeds, load the list.
else {
// Clear local itemList.
// We'll be reordering and repopulating from DataService.
itemList.clear();
for(IBMDataObject item:objects) {
itemList.add((Item) item);
}
sortItems(itemList);
lvArrayAdapter.notifyDataSetChanged();
}
return null;
}
},Task.UI_THREAD_EXECUTOR);
} catch (IBMDataException error) {
Log.e(CLASS_NAME, "Exception : " + error.getMessage());
}
}
/**
* On return from other activity, check result code to determine behavior.
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (resultCode)
{
/* If an edit has been made, notify that the data set has changed. */
case BlueListApplication.EDIT_ACTIVITY_RC:
sortItems(itemList);
lvArrayAdapter.notifyDataSetChanged();
break;
}
}
/**
* Called on done and will add item to list.
*
* @param v edittext View to get item from.
* @throws IBMDataException
*/
public void createItem(View v) {
EditText itemToAdd = (EditText) findViewById(R.id.itemToAdd);
String toAdd = itemToAdd.getText().toString();
EditText pass = (EditText) findViewById(R.id.edt_pass);
String topass = pass.getText().toString();
Item item = new Item();
if (!toAdd.equals("")&&!topass.equals("")) {
item.setName(toAdd);
item.setPass(topass);
// Use the IBMDataObject to create and persist the Item object.
item.save().continueWith(new Continuation<IBMDataObject, Void>() {
@Override
public Void then(Task<IBMDataObject> task) throws Exception {
// Log if the save was cancelled.
if (task.isCancelled()) {
Log.e(CLASS_NAME, "Exception : Task " + task.toString() + " was cancelled.");
}
// Log error message, if the save task fails.
else if (task.isFaulted()) {
Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
}
// If the result succeeds, load the list.
else {
listItems();
}
return null;
}
});
// Set text field back to empty after item is added.
itemToAdd.setText("");
pass.setText("");
}
}
/**
* Will delete an item from the list.
*
* @param //Item item to be deleted
*/
public void deleteItem(Item item) {
itemList.remove(listItemPosition);
// This will attempt to delete the item on the server.
item.delete().continueWith(new Continuation<IBMDataObject, Void>() {
@Override
public Void then(Task<IBMDataObject> task) throws Exception {
// Log if the delete was cancelled.
if (task.isCancelled()) {
Log.e(CLASS_NAME, "Exception : Task " + task.toString() + " was cancelled.");
}
// Log error message, if the delete task fails.
else if (task.isFaulted()) {
Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
}
// If the result succeeds, reload the list.
else {
lvArrayAdapter.notifyDataSetChanged();
}
return null;
}
}, Task.UI_THREAD_EXECUTOR);
lvArrayAdapter.notifyDataSetChanged();
}
/**
* Will call new activity for editing item on list.
* @parm String name - name of the item.
*/
public void updateItem(String name) {
Intent editIntent = new Intent(getBaseContext(), EditActivity.class);
editIntent.putExtra("ItemText", name);
editIntent.putExtra("ItemLocation", listItemPosition);
startActivityForResult(editIntent, BlueListApplication.EDIT_ACTIVITY_RC);
}
/**
* Sort a list of Items.
* @param //List<Item> theList
*/
private void sortItems(List<Item> theList) {
// Sort collection by case insensitive alphabetical order.
Collections.sort(theList, new Comparator<Item>() {
public int compare(Item lhs,
Item rhs) {
String lhsName = lhs.getName()+lhs.getPass();
String rhsName = rhs.getName()+lhs.getPass();
return lhsName.compareToIgnoreCase(rhsName);
}
});
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
/* Inflate a menu resource with context menu items. */
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.editaction, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
/**
* Called when user clicks on contextual action bar menu item.
*
* Determined which item was clicked, and then determine behavior appropriately.
*
* @param /ActionMode mode and MenuItem item clicked
*/
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Item lItem = itemList.get(listItemPosition);
/* Switch dependent on which action item was clicked. */
switch (item.getItemId()) {
/* On edit, get all info needed & send to new, edit activity. */
case R.id.action_edit:
updateItem(lItem.getName());
updateItem(lItem.getPass());
mode.finish(); /* Action picked, so close the CAB. */
return true;
/* On delete, remove list item & update. */
case R.id.action_delete:
deleteItem(lItem);
mode.finish(); /* Action picked, so close the CAB. */
default:
return false;
}
}
/* Called on exit of action mode. */
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (v.getId()==R.id.edt_pass ||v.getId()==R.id.itemToAdd)
if(actionId==EditorInfo.IME_ACTION_DONE){
createItem(v);
return true;
}
return false;
}
@Override
protected void onResume() {
super.onResume();
finish();
}
}
| 30.490515 | 101 | 0.668207 |
8a965d206a6c67a1f8519ed2698b455a6a691fb2 | 9,790 | /*
* Copyright 2016 Fendler Consulting cc.
*
* 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.jensfendler.ninjacamunda;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Provider;
import ninja.postoffice.PostofficeConstant;
import ninja.utils.NinjaProperties;
/**
* Default implementation of a {@link Provider} for the injectable
* {@link Camunda} interface.
*
* This class creates a Camunda {@link ProcessEngineConfiguration} which is then
* used to construct the singleton {@link ProcessEngine} instance which is kept
* within a {@link Camunda} implementation to provide access to all parts of the
* process engine.
*
* @author Jens Fendler
*
*/
public class CamundaProvider implements Provider<Camunda> {
/**
* Logger
*/
private static final Logger LOG = LoggerFactory.getLogger(NinjaCamundaModule.class);
/**
* JDBC URL to use for the process engine database (required property)
*/
private static final String PROPERTY_JDBC_URL = "camunda.jdbc.url";
/**
* JDBC user name to use when connecting to the process engine database
* (required property)
*/
private static final String PROPERTY_JDBC_USERNAME = "camunda.jdbc.username";
/**
* JDBC password to use when connecting to the process engine database
* (required property)
*/
private static final String PROPERTY_JDBC_PASSWORD = "camunda.jdbc.password";
/**
* Class name of the JDBC driver to use for connecting to the process engine
* database (required property)
*/
private static final String PROPERTY_JDBC_DRIVER = "camunda.jdbc.driver";
/**
* Boolean property, indicating if the camunda job executor should be aware
* of process deployments (default: true)
*/
private static final String PROPERTY_JOBEXECUTOR_DEPLOYMENTAWARE = "camunda.jobexecutor.deploymentAware";
/**
* Boolean property, indicating if the camunda job executor should be
* activated immediately. (default: true)
*/
private static final String PROPERTY_JOBEXECUTOR_ACTIVATE = "camunda.jobexecutor.activate";
/**
* Boolean property to control if the Camunda BPM should work with an
* in-memory database (e.g. for testing), or through the configured JDBC
* connection (default: false).
*/
private static final String PROPERTY_USE_IN_MEMORY_DB = "camunda.db.inMemory";
/**
* String property to control Camunda DB schema drop/create/update. Possible
* values are <code>"true"</true>
* ({@link ProcessEngineConfiguration#DB_SCHEMA_UPDATE_TRUE}),
* <code>"false"</true>
* ({@link ProcessEngineConfiguration#DB_SCHEMA_UPDATE_FALSE}), or
* <code>"create-drop"</true>
* ({@link ProcessEngineConfiguration#DB_SCHEMA_UPDATE_CREATE_DROP}).
*
* Default: <code>"true"</true>
*/
private static final String PROPERTY_UPDATE_SCHEMA = "camunda.db.schemaUpdate";
/**
* Boolean property to control user authorization.
*/
private static final String PROPERTY_AUTHORIZATION_ENABLED = "camunda.useAuthorization";
/**
* String property for the Sender name of outgoing emails
*
* (No default value. Camunda will not send mails unless this property is
* set.)
*/
private static final String PROPERTY_SMTP_FROM = "camunda.smtp.from";
/**
* String property for the SMTP host name (defaults to Ninja Postoffice
* configuration as per the config values defined in
* {@link PostofficeConstant}).
*/
private static final String PROPERTY_SMTP_HOST = "camunda.smtp.host";
/**
* Integer property for the SMTP port number (defaults to Ninja Postoffice
* configuration as per the config values defined in
* {@link PostofficeConstant}).
*/
private static final String PROPERTY_SMTP_PORT = "camunda.smtp.port";
/**
* String property for the SMTP username (if any) (defaults to Ninja
* Postoffice configuration as per the config values defined in
* {@link PostofficeConstant}).
*/
private static final String PROPERTY_SMTP_USERNAME = "camunda.smtp.username";
/**
* String property for the SMTP password (if any) (defaults to Ninja
* Postoffice configuration as per the config values defined in
* {@link PostofficeConstant}).
*/
private static final String PROPERTY_SMTP_PASSWORD = "camunda.smtp.password";
/**
* Boolean property to control the use of TLS when camunda sends SMTP mails
* (defaults to Ninja Postoffice configuration as per the config values
* defined in {@link PostofficeConstant}).
*
* If no default value is provided by {@link PostofficeConstant#smtpSsl},
* this defaults to false.
*/
private static final String PROPERTY_SMTP_USE_TLS = "camunda.smtp.tls";
/**
* Injected (via constructor) {@link NinjaProperties} to read module
* configuration from
*/
protected NinjaProperties ninjaProperties;
/**
* Constructor with injected {@link NinjaProperties}
*
* @param ninjaProperties
* injected {@link NinjaProperties}
*/
@Inject
public CamundaProvider(NinjaProperties ninjaProperties) {
this.ninjaProperties = ninjaProperties;
}
/**
* Provides a new {@link Camunda} instance.
*
* @see com.google.inject.Provider#get()
*/
@Override
public Camunda get() {
ProcessEngineConfiguration processEngineConfiguration = null;
// generic camunda configuration properties
boolean useInMemoryDatabase = ninjaProperties.getBooleanWithDefault(PROPERTY_USE_IN_MEMORY_DB, false);
String updateSchema = ninjaProperties.getWithDefault(PROPERTY_UPDATE_SCHEMA, ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
boolean jobExecutorDeploymentAware = ninjaProperties.getBooleanWithDefault(PROPERTY_JOBEXECUTOR_DEPLOYMENTAWARE, true);
boolean jobExecutorActivate = ninjaProperties.getBooleanWithDefault(PROPERTY_JOBEXECUTOR_ACTIVATE, true);
boolean authorizationEnabled = ninjaProperties.getBooleanWithDefault(PROPERTY_AUTHORIZATION_ENABLED, false);
// SMTP configuration (defaults to Ninja Postoffice settings)
String mailFrom = ninjaProperties.get(PROPERTY_SMTP_FROM);
String mailHost = ninjaProperties.getWithDefault(PROPERTY_SMTP_HOST, ninjaProperties.get(PostofficeConstant.smtpHost));
int mailPort = ninjaProperties.getIntegerWithDefault(PROPERTY_SMTP_PORT,
ninjaProperties.getIntegerWithDefault(PostofficeConstant.smtpPort, 25));
String mailUser = ninjaProperties.getWithDefault(PROPERTY_SMTP_USERNAME, ninjaProperties.get(PostofficeConstant.smtpUser));
String mailPass = ninjaProperties.getWithDefault(PROPERTY_SMTP_PASSWORD, ninjaProperties.get(PostofficeConstant.smtpPassword));
boolean mailUseTLS = ninjaProperties.getBooleanWithDefault(PROPERTY_SMTP_USE_TLS,
ninjaProperties.getBooleanWithDefault(PostofficeConstant.smtpSsl, false));
// create specific configurations for JDBC/in-memory scenarios
if (useInMemoryDatabase) {
LOG.debug("Preparing Camunda configuration for In-Memory database");
processEngineConfiguration = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
} else {
LOG.debug("Preparing Camunda configuration with JDBC connection to database");
String jdbcUrl = ninjaProperties.getOrDie(PROPERTY_JDBC_URL);
String jdbcUsername = ninjaProperties.getOrDie(PROPERTY_JDBC_USERNAME);
String jdbcPassword = ninjaProperties.getOrDie(PROPERTY_JDBC_PASSWORD);
String jdbcDriver = ninjaProperties.getOrDie(PROPERTY_JDBC_DRIVER);
processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration().setJdbcUrl(jdbcUrl)
.setJdbcUsername(jdbcUsername).setJdbcPassword(jdbcPassword).setJdbcDriver(jdbcDriver);
}
// setup general configuration aspects
processEngineConfiguration = processEngineConfiguration.setDatabaseSchemaUpdate(updateSchema)
.setJobExecutorDeploymentAware(jobExecutorDeploymentAware).setJobExecutorActivate(jobExecutorActivate)
.setAuthorizationEnabled(authorizationEnabled);
// only configure SMTP setup if explicitly provided
if (StringUtils.isNotBlank(mailFrom)) {
processEngineConfiguration = processEngineConfiguration.setMailServerDefaultFrom(mailFrom).setMailServerHost(mailHost)
.setMailServerPort(mailPort).setMailServerUseTLS(mailUseTLS);
// only configure SMTP user if explicitly provided
if (StringUtils.isNotBlank(mailUser)) {
LOG.debug("Camunda will use usename/password authentication for SMTP requests");
processEngineConfiguration = processEngineConfiguration.setMailServerUsername(mailUser);
// only configure SMTP password when explicitly provided
// together with user name
if (StringUtils.isNotBlank(mailPass)) {
processEngineConfiguration = processEngineConfiguration.setMailServerPassword(mailPass);
}
} else {
LOG.debug("Camunda will issue un-authenticated for SMTP requests");
}
}
// start the engine
LOG.info("Building Camunda BPMN Process Engine...");
ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine();
// wrap the ProcessEngine in a Camunda object and return it
Camunda camunda = new DefaultCamundaImpl(processEngine);
LOG.info("Camunda BPMN Process Engine ready: {}", processEngine.getName());
return camunda;
}
}
| 39.003984 | 129 | 0.774464 |
4bc5ea5613f5ee5094e7bc514119f74b5968a665 | 1,053 | package br.com.alugueAgora.domain;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import java.util.List;
/**
* The persistent class for the NEGOCIO database table.
*
*/
@Entity
@Data
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
public class Negocio implements Serializable {
private static final Long serialVersionUID = 1L;
@Id
@SequenceGenerator(name="NEGOCIO_SEQ", sequenceName="NEGOCIO_SEQ",allocationSize=1,initialValue=0)
@GeneratedValue(strategy=GenerationType.AUTO, generator="NEGOCIO_SEQ")
@Column(name="CODIGO_NEGOCIO")
private Long codigoNegocio;
@NonNull
@Column(name="DESCRICAO_NEGOCIO")
private String descricaoNegocio;
} | 24.488372 | 99 | 0.818613 |
1e6ca4158e4e2ca3f434c3b75544b1eaddff51f3 | 3,276 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|// Copyright (C) 2013 The Android Open Source Project
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Licensed under the Apache License, Version 2.0 (the "License");
end_comment
begin_comment
comment|// you may not use this file except in compliance with the License.
end_comment
begin_comment
comment|// You may obtain a copy of the License at
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// http://www.apache.org/licenses/LICENSE-2.0
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Unless required by applicable law or agreed to in writing, software
end_comment
begin_comment
comment|// distributed under the License is distributed on an "AS IS" BASIS,
end_comment
begin_comment
comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
end_comment
begin_comment
comment|// See the License for the specific language governing permissions and
end_comment
begin_comment
comment|// limitations under the License.
end_comment
begin_package
DECL|package|com.google.gerrit.server.restapi.project
package|package
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|restapi
operator|.
name|project
package|;
end_package
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|extensions
operator|.
name|api
operator|.
name|projects
operator|.
name|ProjectInput
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|extensions
operator|.
name|restapi
operator|.
name|ResourceConflictException
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|extensions
operator|.
name|restapi
operator|.
name|Response
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|extensions
operator|.
name|restapi
operator|.
name|RestModifyView
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|project
operator|.
name|ProjectResource
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|inject
operator|.
name|Singleton
import|;
end_import
begin_class
annotation|@
name|Singleton
DECL|class|PutProject
specifier|public
class|class
name|PutProject
implements|implements
name|RestModifyView
argument_list|<
name|ProjectResource
argument_list|,
name|ProjectInput
argument_list|>
block|{
annotation|@
name|Override
DECL|method|apply (ProjectResource resource, ProjectInput input)
specifier|public
name|Response
argument_list|<
name|?
argument_list|>
name|apply
parameter_list|(
name|ProjectResource
name|resource
parameter_list|,
name|ProjectInput
name|input
parameter_list|)
throws|throws
name|ResourceConflictException
block|{
throw|throw
operator|new
name|ResourceConflictException
argument_list|(
literal|"Project \""
operator|+
name|resource
operator|.
name|getName
argument_list|()
operator|+
literal|"\" already exists"
argument_list|)
throw|;
block|}
block|}
end_class
end_unit
| 14.958904 | 83 | 0.814103 |
04319b586c867e6c654f9ac9799dc17e09c9f90e | 5,307 | package com.skytala.eCommerce.domain.order.relations.returnReason;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.common.base.Splitter;
import com.skytala.eCommerce.domain.order.relations.returnReason.command.AddReturnReason;
import com.skytala.eCommerce.domain.order.relations.returnReason.command.DeleteReturnReason;
import com.skytala.eCommerce.domain.order.relations.returnReason.command.UpdateReturnReason;
import com.skytala.eCommerce.domain.order.relations.returnReason.event.ReturnReasonAdded;
import com.skytala.eCommerce.domain.order.relations.returnReason.event.ReturnReasonDeleted;
import com.skytala.eCommerce.domain.order.relations.returnReason.event.ReturnReasonFound;
import com.skytala.eCommerce.domain.order.relations.returnReason.event.ReturnReasonUpdated;
import com.skytala.eCommerce.domain.order.relations.returnReason.mapper.ReturnReasonMapper;
import com.skytala.eCommerce.domain.order.relations.returnReason.model.ReturnReason;
import com.skytala.eCommerce.domain.order.relations.returnReason.query.FindReturnReasonsBy;
import com.skytala.eCommerce.framework.exceptions.RecordNotFoundException;
import com.skytala.eCommerce.framework.pubsub.Scheduler;
import static com.skytala.eCommerce.framework.pubsub.ResponseUtil.*;
@RestController
@RequestMapping("/order/returnReasons")
public class ReturnReasonController {
private static Map<String, RequestMethod> validRequests = new HashMap<>();
public ReturnReasonController() {
validRequests.put("find", RequestMethod.GET);
validRequests.put("add", RequestMethod.POST);
validRequests.put("update", RequestMethod.PUT);
validRequests.put("removeById", RequestMethod.DELETE);
}
/**
*
* @param allRequestParams
* all params by which you want to find a ReturnReason
* @return a List with the ReturnReasons
* @throws Exception
*/
@GetMapping("/find")
public ResponseEntity<List<ReturnReason>> findReturnReasonsBy(@RequestParam(required = false) Map<String, String> allRequestParams) throws Exception {
FindReturnReasonsBy query = new FindReturnReasonsBy(allRequestParams);
if (allRequestParams == null) {
query.setFilter(new HashMap<>());
}
List<ReturnReason> returnReasons =((ReturnReasonFound) Scheduler.execute(query).data()).getReturnReasons();
return ResponseEntity.ok().body(returnReasons);
}
/**
* creates a new ReturnReason entry in the ofbiz database
*
* @param returnReasonToBeAdded
* the ReturnReason thats to be added
* @return true on success; false on fail
*/
@RequestMapping(method = RequestMethod.POST, value = "/add", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<ReturnReason> createReturnReason(@RequestBody ReturnReason returnReasonToBeAdded) throws Exception {
AddReturnReason command = new AddReturnReason(returnReasonToBeAdded);
ReturnReason returnReason = ((ReturnReasonAdded) Scheduler.execute(command).data()).getAddedReturnReason();
if (returnReason != null)
return successful(returnReason);
else
return conflict(null);
}
/**
* Updates the ReturnReason with the specific Id
*
* @param returnReasonToBeUpdated
* the ReturnReason thats to be updated
* @return true on success, false on fail
* @throws Exception
*/
@RequestMapping(method = RequestMethod.PUT, value = "/{returnReasonId}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> updateReturnReason(@RequestBody ReturnReason returnReasonToBeUpdated,
@PathVariable String returnReasonId) throws Exception {
returnReasonToBeUpdated.setReturnReasonId(returnReasonId);
UpdateReturnReason command = new UpdateReturnReason(returnReasonToBeUpdated);
try {
if(((ReturnReasonUpdated) Scheduler.execute(command).data()).isSuccess())
return noContent();
} catch (RecordNotFoundException e) {
return notFound();
}
return conflict();
}
@GetMapping("/{returnReasonId}")
public ResponseEntity<ReturnReason> findById(@PathVariable String returnReasonId) throws Exception {
HashMap<String, String> requestParams = new HashMap<String, String>();
requestParams.put("returnReasonId", returnReasonId);
try {
List<ReturnReason> foundReturnReason = findReturnReasonsBy(requestParams).getBody();
if(foundReturnReason.size()==1){ return successful(foundReturnReason.get(0));
}else{
return notFound();
}
} catch (RecordNotFoundException e) {
return notFound();
}
}
@DeleteMapping("/{returnReasonId}")
public ResponseEntity<String> deleteReturnReasonByIdUpdated(@PathVariable String returnReasonId) throws Exception {
DeleteReturnReason command = new DeleteReturnReason(returnReasonId);
try {
if (((ReturnReasonDeleted) Scheduler.execute(command).data()).isSuccess())
return noContent();
} catch (RecordNotFoundException e) {
return notFound();
}
return conflict();
}
}
| 35.61745 | 151 | 0.781044 |
6e170b03afa749d779e65a0333d3529d8c45867c | 3,908 | /**
* Leetcode - Algorithm - SingleNumberThree
*/
package com.ciaoshen.leetcode;
import java.util.*;
import com.ciaoshen.leetcode.myUtils.*;
/**
* Each problem is initialized with 3 solutions.
* You can expand more solutions.
* Before using your new solutions, don't forget to register them to the solution registry.
*/
class SingleNumberThree implements Problem {
private Map<Integer,Solution> solutions = new HashMap<>(); // solutions registry
// register solutions HERE...
private SingleNumberThree() {
register(new Solution1());
register(new Solution2());
register(new Solution3());
}
private abstract class Solution {
private int id = 0;
abstract public int[] singleNumber(int[] nums);
}
private class Solution1 extends Solution {
{ super.id = 1; }
public int[] singleNumber(int[] nums) {
Set<Integer> dic = new HashSet<>();
for (int num : nums) {
if (!dic.add(num)) { dic.remove(num); }
}
int[] result = new int[2];
if (dic.size() != 2) { return result; }
Iterator<Integer> ite = dic.iterator();
result[0] = ite.next();
result[1] = ite.next();
return result;
}
}
private class Solution2 extends Solution {
{ super.id = 2; }
public int[] singleNumber(int[] nums) {
// 用XOR让成对的数字互相抵消,得到两个目标数字的XOR混合后的结果。
int mix = 0;
for (int num : nums) { mix ^= num; }
// 获得两目标数XOR混合后最低的1位。
// 假设 a = 1010 0101, b = 1001 0101, 混合后 a ^ b = 0011 0000, 这步得到的就是 0001 0000
// 之所以能这么做,因为int是用2的补码形式编码
mix &= -mix;
// 把所有的数分成两组:第一组,两个目标数不同的那一位是1;第二组,两个目标数不同的那一位是0.
// 然后把两组数分别做XOR混合,最后得到的就是两个目标数。
// 因为两个目标数被分在了不同的组,和他们分在一组的所有其他数都是成对的,会被XOR混合抵消。
int[] result = new int[2];
for (int num : nums) {
if ((num & mix) == mix) { // 两个目标数不同的那一位是1
result[0] ^= num;
} else { // 两个目标数不同的那一位是0
result[1] ^= num;
}
}
return result;
}
}
private class Solution3 extends Solution {
{ super.id = 3; }
public int[] singleNumber(int[] nums) {
return null;
}
}
// you can expand more solutions HERE if you want...
/**
* register a solution in the solution registry
* return false if this type of solution already exist in the registry.
*/
private boolean register(Solution s) {
return (solutions.put(s.id,s) == null)? true : false;
}
/**
* chose one of the solution to test
* return null if solution id does not exist
*/
private Solution solution(int id) {
return solutions.get(id);
}
private static class Test {
private SingleNumberThree problem = new SingleNumberThree();
private Solution solution = null;
private void call(int[] nums, String answer) {
System.out.println("In array: " + Arrays.toString(nums) + "\n");
System.out.println(Arrays.toString(solution.singleNumber(nums)) + " are the single numbers. [answer:" + answer + "]");
}
// public API of Test interface
public void test(int i) {
solution = problem.solution(i);
if (solution == null) { System.out.println("Sorry, [id:" + i + "] doesn't exist!"); return; }
System.out.println("\nCall Solution" + solution.id);
int[] nums1 = new int[]{1, 2, 1, 3, 2, 5};
call(nums1,"[3,5]");
// call();
// call();
}
}
public static void main(String[] args) {
Test test = new Test();
test.test(1);
test.test(2);
// test.test(3);
}
}
| 32.297521 | 134 | 0.541453 |
989c02b1d1368f3b82dbe7e7d7f88c128e256d22 | 1,674 | package entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.utils.XmlReader.Element;
import misc.EntityBodyDef;
import core.Room;
public class TransportEntity extends RectangleEntity {
public static final String TYPE = "transport";
protected Vector2 transportPos;
protected TransportEntity(Room room, String textureKey, EntityBodyDef bodyDef, Vector2 transportPos) {
super(room, textureKey, bodyDef);
this.transportPos = transportPos;
}
public static Entity build(String id, Room room, Vector2 pos, Element elem) {
Element custom = elem.getChildByName("custom");
int transportRow = custom.getInt("transport_row");
int transportCol = custom.getInt("transport_col");
Vector2 transportPos = Room.getWorldPosition(room, transportRow, transportCol);
Vector2 size = new Vector2(Room.SQUARE_SIZE, Room.SQUARE_SIZE);
EntityBodyDef bodyDef = new EntityBodyDef(pos, size, BodyType.StaticBody);
TransportEntity entity = new TransportEntity(room, "block", bodyDef, transportPos);
entity.setId(id);
entity.setBodyData();
return entity;
}
@Override
public String getType() {
return TYPE;
}
@Override
public void onBeginContact(final Entity entity) {
super.onBeginContact(entity);
if(isPlayer(entity)) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
SOUNDS.playSound("transport");
entity.setLinearVelocity(0, 0.01f);
entity.setPosition(transportPos.x, transportPos.y);
}
});
}
}
@Override
protected boolean hasRandomColor() {
return true;
}
}
| 26.15625 | 103 | 0.734767 |
866a2b313f456c29026a712ffb0fb4da617ec603 | 4,937 | /*-
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ============LICENSE_END=========================================================
*/
package org.onap.appc.lockmanager.impl.sql.optimistic;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.onap.appc.lockmanager.impl.sql.Synchronizer;
import org.onap.appc.lockmanager.impl.sql.SynchronizerReceiver;
import org.onap.appc.lockmanager.impl.sql.optimistic.LockRecord;
import org.onap.appc.lockmanager.impl.sql.optimistic.MySqlLockManager;
class MySqlLockManagerMock extends MySqlLockManager implements SynchronizerReceiver {
private final ConcurrentMap<String, LockRecord> locks = new ConcurrentHashMap<>();
private boolean useReal;
private Synchronizer synchronizer;
MySqlLockManagerMock(boolean useReal) {
this.useReal = useReal;
}
@Override
public void setSynchronizer(Synchronizer synchronizer) {
this.synchronizer = synchronizer;
}
@Override
protected Connection openDbConnection() {
if(useReal) {
return super.openDbConnection();
}
return null;
}
@Override
protected void closeDbConnection(Connection connection) {
if(useReal) {
super.closeDbConnection(connection);
}
}
@Override
protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException {
LockRecord res;
if(useReal) {
res = super.loadLockRecord(connection, resource);
} else {
res = locks.get(resource);
}
if(synchronizer != null) {
synchronizer.postLoadLockRecord(resource, (res == null) ? null : res.getOwner());
}
return res;
}
@Override
protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException {
if(synchronizer != null) {
synchronizer.preAddLockRecord(resource, owner);
}
try {
if(useReal) {
super.addLockRecord(connection, resource, owner, timeout);
return;
}
LockRecord lockRecord = new LockRecord(resource);
lockRecord.setOwner(owner);
lockRecord.setUpdated(System.currentTimeMillis());
lockRecord.setTimeout(timeout);
lockRecord.setVer(1);
LockRecord prevLockRecord = locks.putIfAbsent(resource, lockRecord);
if(prevLockRecord != null) {
// simulate unique constraint violation
throw new SQLException("Duplicate PK exception", "23000", 1062);
}
} finally {
if(synchronizer != null) {
synchronizer.postAddLockRecord(resource, owner);
}
}
}
@Override
protected boolean updateLockRecord(Connection connection, String resource, String owner, long timeout, long ver) throws SQLException {
if(synchronizer != null) {
synchronizer.preUpdateLockRecord(resource, owner);
}
try {
if(useReal) {
return super.updateLockRecord(connection, resource, owner, timeout, ver);
}
LockRecord lockRecord = loadLockRecord(connection, resource);
synchronized(lockRecord) {
// should be atomic operation
if(ver != lockRecord.getVer()) {
return false;
}
lockRecord.setOwner(owner);
lockRecord.setUpdated(System.currentTimeMillis());
lockRecord.setTimeout(timeout);
lockRecord.setVer(ver + 1);
}
return true;
} finally {
if(synchronizer != null) {
synchronizer.postUpdateLockRecord(resource, owner);
}
}
}
}
| 36.57037 | 138 | 0.585376 |
72449e50542bf8de666826ff70f749787b98f75a | 2,949 | package com.airplanegaming.michaelcraft.entity;
import com.airplanegaming.michaelcraft.MiChaelCraft;
import com.airplanegaming.michaelcraft.ModRegistry;
import net.minecraft.block.BlockState;
import net.minecraft.entity.EntityDimensions;
import net.minecraft.entity.EntityPose;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.passive.CowEntity;
import net.minecraft.entity.passive.PassiveEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundEvent;
import net.minecraft.text.LiteralText;
import net.minecraft.util.TypeFilter;
import net.minecraft.util.Util;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import org.apache.logging.log4j.Level;
import org.jetbrains.annotations.Nullable;
public class Borg extends CowEntity {
public Borg(EntityType<? extends CowEntity> entityType, World world) {
super(entityType, world);
}
private final short SONG_LENGTH = 20 * 125; // song is 2:05 -> 125 seconds; 20 ticks in a second
private short singingTicks = SONG_LENGTH;
@Override
public void baseTick() {
// If Toby and Borg are close, it plays funne banana song
if (!this.world.isClient()) {
Vec3d pos = this.getPos();
var box = new Box(pos.add(10, 10, 10), pos.subtract(10, 10, 10));
var tobys = this.world.getEntitiesByType(TypeFilter.instanceOf(Toby.class), box, toby -> true);
if (!tobys.isEmpty()) {
if (singingTicks == SONG_LENGTH) {
MiChaelCraft.log(Level.INFO, "DAYLIGHT COME AND ME WAN GO HOME");
this.playSound(ModRegistry.BANANA_SOUND, 1f, 1f);
singingTicks = 0;
} else {
singingTicks++;
}
}
}
super.baseTick();
}
@Nullable
@Override
public CowEntity createChild(ServerWorld world, PassiveEntity entity) {
if (!world.isClient()) {
var player = world.getClosestPlayer(entity, 10);
if (player != null) player.sendSystemMessage(new LiteralText("I play league"), Util.NIL_UUID);
}
return null;
}
@Override
protected float getActiveEyeHeight(EntityPose pose, EntityDimensions dimensions) {
return 2.5f;
}
@Override
public SoundEvent getAmbientSound() {
return ModRegistry.BORG_AMBIENT_SOUND;
}
@Override
public SoundEvent getHurtSound(DamageSource source) {
return ModRegistry.BORG_HURT_SOUND;
}
@Override
public SoundEvent getDeathSound() {
return ModRegistry.BORG_DEATH_SOUND;
}
@Override
public void playStepSound(BlockPos pos, BlockState state) {
this.playSound(ModRegistry.BORG_STEP_SOUND, 0.15F, 1.0F);
}
}
| 33.134831 | 107 | 0.675822 |
092aa9e6231028d848dd676cc54ee933c5e3a95f | 2,819 | package calculatorlock.calculatorvault.calculatorhide.calculatorvaultlocker.gallerylock.securitylocks;
import android.content.Context;
import calculatorlock.calculatorvault.calculatorhide.calculatorvaultlocker.gallerylock.R;
import java.util.ArrayList;
public class SecurityLocksActivityMethods {
String LoginOption = "";
public ArrayList<SecurityLocksEnt> GetSecurityCredentialsDetail(Context context) {
this.LoginOption = SecurityLocksSharedPreferences.GetObject(context).GetLoginType();
ArrayList<SecurityLocksEnt> arrayList = new ArrayList<>();
SecurityLocksEnt securityLocksEnt = new SecurityLocksEnt();
securityLocksEnt.SetLoginOption(R.string.lblsetting_SecurityCredentials_Cal_Pin);
if (SecurityLocksCommon.LoginOptions.Calculator.toString().equals(this.LoginOption)) {
securityLocksEnt.SetisCheck(true);
securityLocksEnt.SetDrawable(R.drawable.calculator_icon);
} else {
securityLocksEnt.SetisCheck(false);
securityLocksEnt.SetDrawable(R.drawable.calculator_icon);
}
arrayList.add(securityLocksEnt);
SecurityLocksEnt securityLocksEnt2 = new SecurityLocksEnt();
securityLocksEnt2.SetLoginOption(R.string.lblsetting_SecurityCredentials_Pin);
if (SecurityLocksCommon.LoginOptions.Pin.toString().equals(this.LoginOption)) {
securityLocksEnt2.SetisCheck(true);
securityLocksEnt2.SetDrawable(R.drawable.pin_icon);
} else {
securityLocksEnt2.SetisCheck(false);
securityLocksEnt2.SetDrawable(R.drawable.pin_icon);
}
arrayList.add(securityLocksEnt2);
SecurityLocksEnt securityLocksEnt3 = new SecurityLocksEnt();
securityLocksEnt3.SetLoginOption(R.string.lblsetting_SecurityCredentials_Pattern);
if (SecurityLocksCommon.LoginOptions.Pattern.toString().equals(this.LoginOption)) {
securityLocksEnt3.SetisCheck(true);
securityLocksEnt3.SetDrawable(R.drawable.pattern_icon);
} else {
securityLocksEnt3.SetisCheck(false);
securityLocksEnt3.SetDrawable(R.drawable.pattern_icon);
}
arrayList.add(securityLocksEnt3);
SecurityLocksEnt securityLocksEnt4 = new SecurityLocksEnt();
securityLocksEnt4.SetLoginOption(R.string.lblsetting_SecurityCredentials_Password);
if (SecurityLocksCommon.LoginOptions.Password.toString().equals(this.LoginOption)) {
securityLocksEnt4.SetisCheck(true);
securityLocksEnt4.SetDrawable(R.drawable.password_icon);
} else {
securityLocksEnt4.SetisCheck(false);
securityLocksEnt4.SetDrawable(R.drawable.password_icon);
}
arrayList.add(securityLocksEnt4);
return arrayList;
}
}
| 47.779661 | 102 | 0.72508 |
4c5080835aea2519b7d5bcd8ac29bf27133f1032 | 13,645 | package com.callfire.api.client.api.contacts;
import com.callfire.api.client.JsonConverter;
import com.callfire.api.client.api.AbstractApiTest;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.ResourceId;
import com.callfire.api.client.api.common.model.request.GetByIdRequest;
import com.callfire.api.client.api.contacts.model.Contact;
import com.callfire.api.client.api.contacts.model.ContactList;
import com.callfire.api.client.api.contacts.model.request.AddContactListItemsRequest;
import com.callfire.api.client.api.contacts.model.request.CreateContactListRequest;
import com.callfire.api.client.api.contacts.model.request.FindContactListsRequest;
import com.callfire.api.client.api.contacts.model.request.UpdateContactListRequest;
import org.apache.http.client.methods.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockitoAnnotations;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class ContactListsApiTest extends AbstractApiTest {
protected static final String RESPONSES_PATH = "/contacts/contactsApi/response/";
protected static final String REQUESTS_PATH = "/contacts/contactsApi/request/";
protected static final String EMPTY_LIST_ID_MSG = "listId cannot be null";
protected static final String EMPTY_CONTACT_ID_MSG = "contactId cannot be null";
protected static final String EMPTY_REQ_CONTACT_LIST_ID_MSG = "request.contactListId cannot be null";
protected static final String EMPTY_CONTACT_LIST_ID_MSG = "contactListId cannot be null";
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
client.getRestApiClient().setHttpClient(mockHttpClient);
}
@Test
public void testDynamicPropertiesSerializationStringNumbers() throws Exception {
// contactNumbers
CreateContactListRequest requestString = CreateContactListRequest.<String>create()
.name("listFromNumbers")
.contacts(asList("12345678881", "12345678882"))
.build();
JsonConverter jsonConverter = new JsonConverter();
String serialized = jsonConverter.serialize(requestString);
System.out.println("contactNumbers: " + serialized);
assertThat(serialized, containsString("\"contactNumbers\":"));
}
@Test
public void testDynamicPropertiesSerializationContactIds() throws Exception {
JsonConverter jsonConverter = new JsonConverter();
// contactIds
CreateContactListRequest requestLong = CreateContactListRequest.<Long>create()
.name("listFromIds")
.contacts(asList(1L, 2L))
.build();
String serialized = jsonConverter.serialize(requestLong);
System.out.println("contactIds: " + serialized);
assertThat(serialized, containsString("\"contactIds\":"));
assertThat(serialized, containsString("\"listFromIds\""));
}
@Test
public void testDynamicPropertiesSerializationContactPojos() throws Exception {
JsonConverter jsonConverter = new JsonConverter();
Contact c1 = new Contact();
c1.setFirstName("name1");
Contact c2 = new Contact();
c2.setFirstName("name2");
// contacts
CreateContactListRequest requestObjects = CreateContactListRequest.<Contact>create()
.name("listFromContacts")
.contacts(asList(c1, c2))
.build();
String serialized = jsonConverter.serialize(requestObjects);
System.out.println("contacts: " + serialized);
assertThat(serialized, containsString("\"contacts\":"));
assertThat(serialized, containsString("\"listFromContacts\""));
}
@Test
public void testDynamicPropertiesSerializationWithOtherProps() throws Exception {
AddContactListItemsRequest requestObjects = AddContactListItemsRequest.<Long>create()
.contactNumbersField("field")
.contactListId(5L)
.contacts(asList(1L, 2L))
.build();
JsonConverter jsonConverter = new JsonConverter();
String serialized = jsonConverter.serialize(requestObjects);
System.out.println("contactIds: " + serialized);
assertThat(serialized, containsString("\"contactIds\":"));
assertThat(serialized, containsString("\"contactNumbersField\":\"field\""));
assertThat(serialized, not(containsString("\"contactListId\":")));
}
@Test
public void testFind() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "findContactLists.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
FindContactListsRequest request = FindContactListsRequest.create()
.limit(1L)
.offset(5L)
.name("test")
.fields(FIELDS)
.build();
Page<ContactList> contactLists = client.contactListsApi().find(request);
assertThat(jsonConverter.serialize(contactLists), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("limit=1"));
assertThat(arg.getURI().toString(), containsString("offset=5"));
assertThat(arg.getURI().toString(), containsString("name=test"));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
}
@Test
public void testCreate() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "createContactList.json");
mockHttpResponse(expectedJson);
Contact c1 = new Contact();
c1.setHomePhone("123456");
Contact c2 = new Contact();
c2.setHomePhone("123457");
CreateContactListRequest request = CreateContactListRequest.<Contact>create()
.name("listFromContacts")
.contacts(asList(c1, c2))
.build();
ResourceId resourceId = client.contactListsApi().create(request);
assertThat(jsonConverter.serialize(resourceId), equalToIgnoringWhiteSpace(expectedJson));
}
@Test
public void testCreateFromCsv() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "createContactList.json");
mockHttpResponse(expectedJson);
File file = new File(REQUESTS_PATH + "createContactsList.csv");
ResourceId resourceId = client.contactListsApi().createFromCsv("testFile", file);
assertThat(jsonConverter.serialize(resourceId), equalToIgnoringWhiteSpace(expectedJson));
}
@Test
public void testGetByNullId() throws Exception {
ex.expectMessage(EMPTY_ID_MSG);
ex.expect(NullPointerException.class);
client.contactListsApi().get(null);
}
@Test
public void testGetById() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "getContactList.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
ContactList contactList = client.contactListsApi().get(TEST_ID, FIELDS);
assertThat(jsonConverter.serialize(contactList), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
}
@Test
public void testUpdateByNullId() throws Exception {
ex.expectMessage(EMPTY_REQUEST_ID_MSG);
ex.expect(NullPointerException.class);
client.contactListsApi().update(UpdateContactListRequest.create().id(null).build());
}
@Test
public void testUpdateById() throws Exception {
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
String requestJson = getJsonPayload(BASE_PATH + REQUESTS_PATH + "updateContactList.json");
client.contactListsApi().update(UpdateContactListRequest.create().id(TEST_ID).name("test").build());
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPut.METHOD_NAME, arg.getMethod());
assertThat(arg.getURI().toString(), containsString("/" + TEST_ID));
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(requestJson));
}
@Test
public void testDeleteByNullId() throws Exception {
ex.expectMessage(EMPTY_ID_MSG);
ex.expect(NullPointerException.class);
client.contactListsApi().delete(null);
}
@Test
public void testDelete() throws Exception {
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
client.contactListsApi().delete(TEST_ID);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpDelete.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("/" + TEST_ID));
}
@Test
public void testGetContactsForContactListByNullId() throws Exception {
ex.expectMessage(EMPTY_ID_MSG);
ex.expect(NullPointerException.class);
client.contactListsApi().getListItems(GetByIdRequest.create().build());
}
@Test
public void testGetContactsForContactList() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "findContacts.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
GetByIdRequest request = GetByIdRequest.create()
.id(TEST_ID)
.limit(1L)
.offset(5L)
.fields(FIELDS)
.build();
Page<Contact> contactsList = client.contactListsApi().getListItems(request);
assertThat(jsonConverter.serialize(contactsList), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("limit=1"));
assertThat(arg.getURI().toString(), containsString("offset=5"));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
}
@Test
public void testAddContactsToContactListByNullId() throws Exception {
ex.expectMessage(EMPTY_REQ_CONTACT_LIST_ID_MSG);
ex.expect(NullPointerException.class);
client.contactListsApi().addListItems(AddContactListItemsRequest.create().build());
}
@Test
public void testAddContactsToContactListById() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "addContactsToContactList.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
Contact c1 = new Contact();
c1.setHomePhone("123456");
Contact c2 = new Contact();
c2.setHomePhone("123457");
AddContactListItemsRequest request = AddContactListItemsRequest.<Contact>create()
.contactNumbersField("homePhone")
.contactListId(TEST_ID)
.contacts(asList(c1, c2))
.build();
client.contactListsApi().addListItems(request);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPost.METHOD_NAME, arg.getMethod());
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(expectedJson));
assertThat(arg.getURI().toString(), containsString("/" + TEST_ID));
}
@Test
public void testDeleteContactFromContactListByNullContactListId() throws Exception {
ex.expectMessage(EMPTY_LIST_ID_MSG);
ex.expect(NullPointerException.class);
client.contactListsApi().removeListItem(null, TEST_ID);
}
@Test
public void testDeleteContactFromContactListByNullContactId() throws Exception {
ex.expectMessage(EMPTY_CONTACT_ID_MSG);
ex.expect(NullPointerException.class);
client.contactListsApi().removeListItem(TEST_ID, null);
}
@Test
public void testDeleteContactFromContactList() throws Exception {
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
client.contactListsApi().removeListItem(TEST_ID, 123456L);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpDelete.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("/" + TEST_ID));
assertThat(arg.getURI().toString(), containsString("/123456"));
}
@Test
public void testDeleteContactsFromContactListByNullContactListId() throws Exception {
ex.expectMessage(EMPTY_CONTACT_LIST_ID_MSG);
ex.expect(NullPointerException.class);
client.contactListsApi().removeListItems(null, new ArrayList<Long>());
}
@Test
public void testDeleteContactsFromContactList() throws Exception {
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
client.contactListsApi().removeListItems(TEST_ID, Arrays.asList(123456L));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpDelete.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("/" + TEST_ID));
assertThat(arg.getURI().toString(), containsString("contactId=123456"));
}
}
| 42.640625 | 108 | 0.70011 |
d1d500469a713d62f538ce78fb32a113f159bf65 | 998 | package uk.gov.companieshouse.web.lfp.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Healthcheck controller returns a 200 response if the service is running.
* <p>The ResponseEntity accepts a wildcard and thus a more verbose healthcheck can be written
* to query the status of mongo/kafka/disk space etc. The results can be marshalled into
* an object and passed to the ResponseEntity constructor along with the HttpStatus.
* <br>This will ultimately act as a more lightweight spring actuator.
*/
@Controller
public class HealthcheckController {
@RequestMapping(value = "/late-filing-penalty/healthcheck", method = RequestMethod.GET)
public ResponseEntity<?> performHealthCheck() {
return new ResponseEntity<>(HttpStatus.OK);
}
}
| 39.92 | 94 | 0.790581 |
b07f5e45d8cd6bfacbecea8b1819e17e7a72cf10 | 6,514 | /*
* Copyright (c) 2015, SRI International
* All rights reserved.
* Licensed under the The BSD 3-Clause License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the aic-praise nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sri.ai.praise.core.inference.byinputrepresentation.classbased.hogm.solver;
import static com.sri.ai.util.Util.arrayList;
import static com.sri.ai.util.Util.list;
import static com.sri.ai.util.explanation.logging.api.ThreadExplanationLogger.RESULT;
import static com.sri.ai.util.explanation.logging.api.ThreadExplanationLogger.code;
import static com.sri.ai.util.explanation.logging.api.ThreadExplanationLogger.explanationBlock;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.common.annotations.Beta;
import com.sri.ai.expresso.api.Expression;
import com.sri.ai.praise.core.inference.byinputrepresentation.classbased.expressionbased.api.ExpressionBasedSolver;
import com.sri.ai.praise.core.inference.byinputrepresentation.classbased.expressionbased.core.byalgorithm.exactbp.ExactBPExpressionBasedSolver;
import com.sri.ai.praise.core.inference.byinputrepresentation.classbased.hogm.answer.HOGMAnswerSimplifier;
import com.sri.ai.praise.core.inference.byinputrepresentation.classbased.hogm.parsing.HOGMModelParsing;
import com.sri.ai.praise.core.inference.byinputrepresentation.classbased.hogm.parsing.HOGMProblemError;
import com.sri.ai.praise.core.representation.classbased.expressionbased.api.ExpressionBasedModel;
import com.sri.ai.praise.core.representation.classbased.hogm.HOGModel;
import com.sri.ai.praise.core.representation.classbased.hogm.components.HOGMExpressionBasedModel;
import com.sri.ai.praise.other.integration.proceduralattachment.api.ProceduralAttachments;
import com.sri.ai.praise.other.integration.proceduralattachment.api.Procedure;
import com.sri.ai.praise.other.integration.proceduralattachment.core.DefaultProceduralAttachments;
@Beta
public class HOGMMultiQueryProblemSolver {
public static Class<? extends ExpressionBasedSolver> defaultSolverClass = ExactBPExpressionBasedSolver.class;
private String modelString;
private List<String> queries;
private HOGModel hogmModel = null;
private ExpressionBasedModel expressionBasedModel;
private Class<? extends ExpressionBasedSolver> solverClass;
private HOGMSingleQueryProblemSolver problemSolver;
private List<HOGMProblemError> modelErrors = new ArrayList<>();
private List<HOGMProblemResult> results = null;
private ProceduralAttachments proceduralAttachments = new DefaultProceduralAttachments();
public HOGMMultiQueryProblemSolver(String model, String query) {
this(model, list(query), defaultSolverClass);
}
public HOGMMultiQueryProblemSolver(String model, List<String> queries) {
this(model, queries, defaultSolverClass);
}
public HOGMMultiQueryProblemSolver(String model, String query, Class<? extends ExpressionBasedSolver> solverClass) {
this(model, list(query), solverClass);
}
public HOGMMultiQueryProblemSolver(String modelString, List<String> queries, Class<? extends ExpressionBasedSolver> solverClass) {
this.modelString = modelString;
this.queries = queries;
this.solverClass = solverClass;
}
public void setProceduralAttachments(ProceduralAttachments proceduralAttachments) {
this.proceduralAttachments = proceduralAttachments;
}
public Map<String, Procedure> getProceduralAttachments() {
return this.proceduralAttachments;
}
public List<HOGMProblemResult> getResults() {
if (results == null) {
results = arrayList();
initializeModel(modelString);
processAllQueries(queries);
}
return results;
}
private void initializeModel(String modelString) {
HOGMModelParsing parsingWithErrorCollecting = new HOGMModelParsing(modelString, modelErrors);
this.hogmModel = parsingWithErrorCollecting.getModel();
this.expressionBasedModel = hogmModel == null? null : new HOGMExpressionBasedModel(hogmModel);
if (this.expressionBasedModel != null) {
this.expressionBasedModel.setProceduralAttachments(proceduralAttachments);
}
}
private void processAllQueries(List<String> queries) {
for (String query : queries) {
solveProblemWithQuery(query);
}
}
private void solveProblemWithQuery(String query) {
explanationBlock("Solving query ", query, code(() -> {
HOGMSingleQueryProblemSolver problemSolver = new HOGMSingleQueryProblemSolver(query, solverClass, hogmModel, expressionBasedModel, modelErrors);
List<HOGMProblemResult> queryResult = problemSolver.getResults();
results.addAll(queryResult);
return queryResult; }), "Query result is ", RESULT);
}
public void interrupt() {
if (problemSolver != null) {
problemSolver.interrupt();
}
}
public Expression simplifyAnswer(Expression answer, Expression forQuery) {
Expression result = HOGMAnswerSimplifier.simplifyAnswer(answer, forQuery, expressionBasedModel.getContext());
return result;
}
}
| 43.718121 | 147 | 0.796592 |
684af1ee5f89e0043e4335abf283113e7845a4ca | 120 | package com.baidu.che.codriversdk;
import java.io.Serializable;
public interface INoProguard extends Serializable {
}
| 17.142857 | 51 | 0.816667 |
08f10600f35559bc9c24a49c25f9d0137be962c4 | 2,234 | package mltk.core;
import java.util.ArrayList;
import java.util.List;
public class InstancesTestHelper {
private static InstancesTestHelper instance = null;
private Instances denseClaDataset;
private Instances denseRegDataset;
private Instances denseClaDatasetWMissing;
private Instances denseRegDatasetWMissing;
public static InstancesTestHelper getInstance() {
if (instance == null) {
instance = new InstancesTestHelper();
}
return instance;
}
public Instances getDenseClassificationDataset() {
return denseClaDataset;
}
public Instances getDenseRegressionDataset() {
return denseRegDataset;
}
public Instances getDenseClassificationDatasetWMissing() {
return denseClaDatasetWMissing;
}
public Instances getDenseRegressionDatasetWMissing() {
return denseRegDatasetWMissing;
}
private InstancesTestHelper() {
List<Attribute> attributes = new ArrayList<>();
NumericalAttribute f1 = new NumericalAttribute("f1", 0);
NominalAttribute f2 = new NominalAttribute("f2", new String[] {"a", "b", "c"}, 1);
BinnedAttribute f3 = new BinnedAttribute("f3", 256, 2);
Bins bins = new Bins(new double[] {1, 5, 6}, new double[] {0.5, 2.5, 3});
BinnedAttribute f4 = new BinnedAttribute("f4", bins, 3);
attributes.add(f1);
attributes.add(f2);
attributes.add(f3);
attributes.add(f4);
Attribute claTarget = new NominalAttribute("target", new String[] {"0", "1"});
Attribute regTarget = new NumericalAttribute("target");
denseClaDataset = new Instances(attributes, claTarget);
for (int i = 0; i < 1000; i++) {
double[] v = new double[4];
v[0] = i * 0.1;
v[1] = i % f2.getCardinality();
v[2] = (i + 1000) % f3.getNumBins();
v[3] = i % f3.getNumBins();
double target = (i % 10) < 8 ? 0 : 1;
Instance instance = new Instance(v, target);
denseClaDataset.add(instance);
}
denseRegDataset = denseClaDataset.copy();
denseRegDataset.setTargetAttribute(regTarget);
denseClaDatasetWMissing = denseClaDataset.copy();
for (int i = 0; i < 10; i++) {
denseClaDatasetWMissing.get(i).setValue(0, Double.NaN);
}
denseRegDatasetWMissing = denseClaDatasetWMissing.copy();
denseRegDatasetWMissing.setTargetAttribute(regTarget);
}
}
| 28.278481 | 84 | 0.708147 |
070e039c0479946d045c53e5a5f0587837314d0f | 3,731 | package io.kettil;
import com.google.rpc.Status;
import io.envoyproxy.envoy.service.auth.v3.AuthorizationGrpc.AuthorizationImplBase;
import io.envoyproxy.envoy.service.auth.v3.CheckRequest;
import io.envoyproxy.envoy.service.auth.v3.CheckResponse;
import io.envoyproxy.envoy.service.auth.v3.OkHttpResponse;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
@Slf4j
@Service
public class TestEnvoyExtAuthzService implements Closeable {
private static final Integer GRANTED = 0;
private static final Integer DENIED = 7;
private final int gRpcPort;
private Server server;
public TestEnvoyExtAuthzService(@Value("${grpc.port}") int gRpcPort) {
this.gRpcPort = gRpcPort;
}
@PostConstruct
public void start() throws IOException {
server = ServerBuilder.forPort(gRpcPort)
.addService(newCheckRequestHandler())
.build();
server.start();
log.info("gRPC listen port: {}", server.getPort());
}
@Override
public void close() {
if (server != null)
server.shutdown();
}
private io.grpc.BindableService newCheckRequestHandler() {
return new AuthorizationImplBase() {
@SneakyThrows
@Override
public void check(CheckRequest request, StreamObserver<CheckResponse> responseObserver) {
log.info("v3.CheckRequest: {}", request);
String objectNamespace = request.getAttributes().getContextExtensionsOrThrow("namespace_object");
String serviceNamespace = request.getAttributes().getContextExtensionsOrThrow("namespace_service");
String servicePath = request.getAttributes().getContextExtensionsOrThrow("service_path");
String relation = request.getAttributes().getContextExtensionsOrThrow("relation");
String objectIdPtr = request.getAttributes().getContextExtensionsMap().get("objectid_ptr");
String authzResult = request.getAttributes().getContextExtensionsMap().get("authz_result");
Map<String, String> headers = request.getAttributes().getRequest().getHttp().getHeadersMap();
String authorization = headers.get("authorization");
String method = request.getAttributes().getRequest().getHttp().getMethod();
String path = request.getAttributes().getRequest().getHttp().getPath();
int code = GRANTED;
switch (authzResult) {
case "allow":
code = GRANTED;
break;
case "deny":
code = DENIED;
break;
}
switch (path) {
case "/allow":
code = GRANTED;
break;
case "/deny":
code = DENIED;
break;
}
log.info("v3.CheckRequest result: {}", code == GRANTED ? "GRANTED" : "DENIED");
responseObserver.onNext(CheckResponse.newBuilder()
.setStatus(Status.newBuilder().setCode(code).build())
.setOkResponse(OkHttpResponse.newBuilder().build())
.build());
responseObserver.onCompleted();
}
};
}
}
| 35.198113 | 115 | 0.60922 |
1aace589ff5c3aa4df2d5d98db1f04fe5114ce6a | 902 | package de.polocloud.api.network.packet.player;
import de.polocloud.network.packet.Packet;
import de.polocloud.network.packet.NetworkBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
@AllArgsConstructor
@Getter
@NoArgsConstructor
public class CloudPlayerLoginPacket implements Packet {
private String username;
private UUID uuid;
private String proxyServer;
@Override
public void read(@NotNull NetworkBuf byteBuf) {
this.username = byteBuf.readString();
this.uuid = byteBuf.readUUID();
this.proxyServer = byteBuf.readString();
}
@Override
public void write(@NotNull NetworkBuf byteBuf) {
byteBuf
.writeString(this.username)
.writeUUID(this.uuid)
.writeString(this.proxyServer);
}
}
| 24.378378 | 55 | 0.717295 |
7fc177088cd48c6dd5603808ee8f1d2728ff25fb | 407 | package cn.bootx.common.sequence.range.jdbc;
import cn.bootx.common.mybatisplus.impl.BaseManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
/**
* 队列区间
* @author xxm
* @date 2021/12/14
*/
@Slf4j
@Repository
@RequiredArgsConstructor
public class SequenceRangeManager extends BaseManager<SequenceRangeMapper,SequenceRange> {
}
| 22.611111 | 90 | 0.818182 |
f7dd76a218747481add7296ec972c83a4683bcb0 | 24,337 | package android.support.v7.widget;
import android.content.Context;
import android.graphics.Rect;
import android.os.Parcelable;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionItemInfoCompat;
import android.support.v4.view.accessibility.AccessibilityRecordCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.accessibility.AccessibilityEvent;
import java.util.ArrayList;
import java.util.BitSet;
public final class StaggeredGridLayoutManager extends ao
{
Z a;
private Z d;
private int e;
private F f;
private boolean g;
private boolean h;
private int i;
private int j;
private boolean k;
private boolean l;
private StaggeredGridLayoutManager.SavedState m;
private int n;
private int o;
private int p;
private final Rect q;
private final av r;
private boolean s;
private final Runnable t;
private static int a(int paramInt1, int paramInt2, int paramInt3)
{
if ((paramInt2 == 0) && (paramInt3 == 0));
int i1;
do
{
return paramInt1;
i1 = View.MeasureSpec.getMode(paramInt1);
}
while ((i1 != -2147483648) && (i1 != 1073741824));
return View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(paramInt1) - paramInt2 - paramInt3, i1);
}
private int a(ar paramar, F paramF, aw paramaw)
{
null.set(0, 0, true);
int i1;
int i2;
label47: int i3;
label50: int i4;
label71: View localView;
aO localaO1;
int i8;
label139: int i19;
label155: label180: label187: label207: int i9;
int i11;
label229: Rect localRect;
label257: int i14;
int i13;
label369: int i18;
if (paramF.d == 1)
{
i1 = paramF.f + paramF.a;
if (!this.h)
break label627;
i2 = this.a.d();
i3 = 0;
if ((paramF.b < 0) || (paramF.b >= paramaw.d()))
break label639;
i4 = 1;
if ((i4 == 0) || (null.isEmpty()))
break label861;
localView = paramar.b(paramF.b);
paramF.b += paramF.c;
localaO1 = (aO)localView.getLayoutParams();
int i7 = localaO1.a.c();
if (null.c(i7) != -1)
break label645;
i8 = 1;
if (i8 == 0)
break label668;
if (paramF.d != -1)
break label651;
i19 = 1;
if ((i19 != this.h) && (paramF.d != 1))
break label657;
this.a.c();
null.a(i7, null);
localaO1.e = null;
if (paramF.d != 1)
break label671;
a(localView);
i9 = localaO1.width;
int i10 = this.o;
if (i9 >= 0)
break label681;
i11 = i10;
int i12 = this.p;
localRect = this.q;
if (this.c != null)
break label693;
localRect.set(0, 0, 0, 0);
aO localaO2 = (aO)localView.getLayoutParams();
localView.measure(a(i11, localaO2.leftMargin + this.q.left, localaO2.rightMargin + this.q.right), a(i12, localaO2.topMargin + this.q.top, localaO2.bottomMargin + this.q.bottom));
if (paramF.d != 1)
break label710;
i14 = null.b(i2);
i13 = i14 + this.a.c(localView);
if (i8 != 0);
if (paramF.d != 1)
break label735;
aR localaR2 = localaO1.e;
aO localaO5 = (aO)localView.getLayoutParams();
localaO5.e = localaR2;
null.add(localView);
localaR2.b = -2147483648;
if (null.size() == 1)
localaR2.a = -2147483648;
if ((localaO5.a.m()) || (localaO5.a.k()))
localaR2.c += localaR2.e.a.c(localView);
label476: int i15 = null.d * this.e + this.d.c();
int i16 = i15 + this.d.c(localView);
aO localaO4 = (aO)localView.getLayoutParams();
a(localView, i14 + localaO4.leftMargin, i15 + localaO4.topMargin, i13 - localaO4.rightMargin, i16 - localaO4.bottomMargin);
int i17 = this.f.d;
i18 = null.c;
if (i17 != -1)
break label837;
if (i18 + null.a() <= i1)
null.set(null.d, false);
}
while (true)
{
a(paramar, this.f);
i3 = 1;
break label50;
i1 = paramF.e - paramF.a;
break;
label627: i2 = this.a.c();
break label47;
label639: i4 = 0;
break label71;
label645: i8 = 0;
break label139;
label651: i19 = 0;
break label155;
label657: this.a.d();
break label180;
label668: break label187;
label671: b(localView, 0);
break label207;
label681: i11 = View.MeasureSpec.makeMeasureSpec(i9, 1073741824);
break label229;
label693: localRect.set(this.c.c(localView));
break label257;
label710: i13 = null.a(i2);
i14 = i13 - this.a.c(localView);
break label369;
label735: aR localaR1 = localaO1.e;
aO localaO3 = (aO)localView.getLayoutParams();
localaO3.e = localaR1;
null.add(0, localView);
localaR1.a = -2147483648;
if (null.size() == 1)
localaR1.b = -2147483648;
if ((!localaO3.a.m()) && (!localaO3.a.k()))
break label476;
localaR1.c += localaR1.e.a.c(localView);
break label476;
label837: if (null.b() - i18 < i1)
continue;
null.set(null.d, false);
}
label861: if (i3 == 0)
a(paramar, this.f);
int i6;
if (this.f.d == -1)
i6 = null.a(this.a.c());
for (int i5 = this.a.c() - i6; i5 > 0; i5 = null.b(this.a.d()) - this.a.d())
return Math.min(paramF.a, i5);
return 0;
}
private View a(boolean paramBoolean1, boolean paramBoolean2)
{
e();
int i1 = this.a.c();
int i2 = this.a.d();
int i3 = h();
Object localObject1 = null;
int i4 = 0;
Object localObject2;
if (i4 < i3)
{
localObject2 = b(i4);
int i5 = this.a.a((View)localObject2);
if ((this.a.b((View)localObject2) <= i1) || (i5 >= i2))
break label110;
if ((i5 >= i1) || (!paramBoolean1))
return localObject2;
if (localObject1 != null)
break label110;
}
while (true)
{
i4++;
localObject1 = localObject2;
break;
return localObject1;
label110: localObject2 = localObject1;
}
}
private void a(int paramInt, aw paramaw)
{
this.f.a = 0;
this.f.b = paramInt;
if ((this.c != null) && (RecyclerView.t(this.c)));
for (int i1 = 1; i1 != 0; i1 = 0)
{
this.f.e = (this.a.c() - 0);
this.f.f = (0 + this.a.d());
return;
}
this.f.f = (0 + this.a.e());
this.f.e = (-0);
}
private void a(ar paramar, int paramInt)
{
while (true)
{
View localView1;
aO localaO1;
if (h() > 0)
{
localView1 = b(0);
if (this.a.b(localView1) <= paramInt)
{
localaO1 = (aO)localView1.getLayoutParams();
if (null.size() != 1)
break label49;
}
}
return;
label49: aR localaR = localaO1.e;
View localView2 = (View)null.remove(0);
aO localaO2 = (aO)localView2.getLayoutParams();
localaO2.e = null;
if (null.size() == 0)
localaR.b = -2147483648;
if ((localaO2.a.m()) || (localaO2.a.k()))
localaR.c -= localaR.e.a.c(localView2);
localaR.a = -2147483648;
a(localView1, paramar);
}
}
private void a(ar paramar, F paramF)
{
if (paramF.a == 0)
{
if (paramF.d == -1)
{
b(paramar, paramF.f);
return;
}
a(paramar, paramF.e);
return;
}
if (paramF.d == -1)
{
int i3 = paramF.e - null.a(paramF.e);
if (i3 < 0);
for (int i4 = paramF.f; ; i4 = paramF.f - Math.min(i3, paramF.a))
{
b(paramar, i4);
return;
}
}
int i1 = null.b(paramF.f) - paramF.f;
if (i1 < 0);
for (int i2 = paramF.e; ; i2 = paramF.e + Math.min(i1, paramF.a))
{
a(paramar, i2);
return;
}
}
private void a(ar paramar, aw paramaw, boolean paramBoolean)
{
int i1 = null.b(this.a.d());
int i2 = this.a.d() - i1;
if (i2 > 0)
{
int i3 = i2 - -d(-i2, paramar, paramaw);
if ((paramBoolean) && (i3 > 0))
this.a.a(i3);
}
}
private View b(boolean paramBoolean1, boolean paramBoolean2)
{
e();
int i1 = this.a.c();
int i2 = this.a.d();
Object localObject1 = null;
int i3 = -1 + h();
Object localObject2;
if (i3 >= 0)
{
localObject2 = b(i3);
int i4 = this.a.a((View)localObject2);
int i5 = this.a.b((View)localObject2);
if ((i5 <= i1) || (i4 >= i2))
break label112;
if ((i5 <= i2) || (!paramBoolean1))
return localObject2;
if (localObject1 != null)
break label112;
}
while (true)
{
i3--;
localObject1 = localObject2;
break;
return localObject1;
label112: localObject2 = localObject1;
}
}
private void b(int paramInt1, int paramInt2, int paramInt3)
{
int i1;
int i2;
int i3;
if (this.h)
{
i1 = s();
if (paramInt3 != 3)
break label96;
if (paramInt1 >= paramInt2)
break label85;
i2 = paramInt2 + 1;
i3 = paramInt1;
label31: null.b(i3);
switch (paramInt3)
{
case 2:
default:
label68: if (i2 > i1)
break;
case 0:
case 1:
case 3:
}
}
while (true)
{
return;
i1 = t();
break;
label85: i2 = paramInt1 + 1;
i3 = paramInt2;
break label31;
label96: i2 = paramInt1 + paramInt2;
i3 = paramInt1;
break label31;
null.b(paramInt1, paramInt2);
break label68;
null.a(paramInt1, paramInt2);
break label68;
null.a(paramInt1, 1);
null.b(paramInt2, 1);
break label68;
if (this.h);
for (int i4 = t(); i3 <= i4; i4 = s())
{
g();
return;
}
}
}
private void b(ar paramar, int paramInt)
{
for (int i1 = -1 + h(); ; i1--)
{
View localView1;
aO localaO1;
if (i1 >= 0)
{
localView1 = b(i1);
if (this.a.a(localView1) >= paramInt)
{
localaO1 = (aO)localView1.getLayoutParams();
if (null.size() != 1)
break label56;
}
}
return;
label56: aR localaR = localaO1.e;
int i2 = null.size();
View localView2 = (View)null.remove(i2 - 1);
aO localaO2 = (aO)localView2.getLayoutParams();
localaO2.e = null;
if ((localaO2.a.m()) || (localaO2.a.k()))
localaR.c -= localaR.e.a.c(localView2);
if (i2 == 1)
localaR.a = -2147483648;
localaR.b = -2147483648;
a(localView1, paramar);
}
}
private void b(ar paramar, aw paramaw, boolean paramBoolean)
{
int i1 = null.a(this.a.c()) - this.a.c();
if (i1 > 0)
{
int i2 = i1 - d(i1, paramar, paramaw);
if ((paramBoolean) && (i2 > 0))
this.a.a(-i2);
}
}
private int d(int paramInt, ar paramar, aw paramaw)
{
e();
int i1;
int i2;
int i4;
if (paramInt > 0)
{
i1 = 1;
i2 = s();
a(i2, paramaw);
f(i1);
this.f.b = (i2 + this.f.c);
int i3 = Math.abs(paramInt);
this.f.a = i3;
i4 = a(paramar, this.f, paramaw);
if (i3 >= i4)
break label112;
}
while (true)
{
this.a.a(-paramInt);
this.k = this.h;
return paramInt;
i1 = -1;
i2 = t();
break;
label112: if (paramInt < 0)
{
paramInt = -i4;
continue;
}
paramInt = i4;
}
}
private void e()
{
if (this.a == null)
{
this.a = Z.a(this, 0);
this.d = Z.a(this, 1);
this.f = new F();
}
}
private void f(int paramInt)
{
int i1 = 1;
this.f.d = paramInt;
F localF = this.f;
int i2 = this.h;
if (paramInt == -1)
{
int i3 = i1;
if (i2 != i3)
break label48;
}
while (true)
{
localF.c = i1;
return;
int i4 = 0;
break;
label48: i1 = -1;
}
}
private int g(aw paramaw)
{
if (h() == 0)
return 0;
e();
return a.a(paramaw, this.a, a(true, true), b(true, true), this, false, this.h);
}
private int h(aw paramaw)
{
if (h() == 0)
return 0;
e();
return a.a(paramaw, this.a, a(true, true), b(true, true), this, false);
}
private int i(aw paramaw)
{
if (h() == 0)
return 0;
e();
return a.b(paramaw, this.a, a(true, true), b(true, true), this, false);
}
private void q()
{
boolean bool;
if (!r())
bool = this.g;
while (true)
{
this.h = bool;
return;
if (!this.g)
{
bool = true;
continue;
}
bool = false;
}
}
private boolean r()
{
return ViewCompat.getLayoutDirection(this.c) == 1;
}
private int s()
{
int i1 = h();
if (i1 == 0)
return 0;
return b(b(i1 - 1));
}
private int t()
{
if (h() == 0)
return 0;
return b(b(0));
}
public final int a(int paramInt, ar paramar, aw paramaw)
{
return d(paramInt, paramar, paramaw);
}
public final int a(aw paramaw)
{
return g(paramaw);
}
public final ap a()
{
return new aO(-2, -2);
}
public final ap a(Context paramContext, AttributeSet paramAttributeSet)
{
return new aO(paramContext, paramAttributeSet);
}
public final ap a(ViewGroup.LayoutParams paramLayoutParams)
{
if ((paramLayoutParams instanceof ViewGroup.MarginLayoutParams))
return new aO((ViewGroup.MarginLayoutParams)paramLayoutParams);
return new aO(paramLayoutParams);
}
public final void a(int paramInt1, int paramInt2)
{
b(paramInt1, paramInt2, 0);
}
public final void a(Parcelable paramParcelable)
{
if ((paramParcelable instanceof StaggeredGridLayoutManager.SavedState))
{
this.m = ((StaggeredGridLayoutManager.SavedState)paramParcelable);
g();
}
}
public final void a(RecyclerView paramRecyclerView, ar paramar)
{
Runnable localRunnable = this.t;
if (this.c != null)
this.c.removeCallbacks(localRunnable);
}
public final void a(ar paramar, aw paramaw)
{
e();
av localav = this.r;
localav.a();
label140: label173: int i1;
label191: int i7;
label217: int i5;
if (this.m != null)
if ((this.m.c <= 0) || (this.m.c == 0))
{
this.l = this.m.j;
boolean bool2 = this.m.h;
a(null);
if ((this.m != null) && (this.m.h != bool2))
this.m.h = bool2;
this.g = bool2;
g();
q();
if (this.m.a == -1)
break label566;
this.i = this.m.a;
localav.c = this.m.i;
if (this.m.e > 1)
{
null.f = this.m.f;
null.g = this.m.g;
}
if ((!paramaw.a()) && (this.i != -1))
break label592;
i1 = 0;
if (i1 == 0)
{
if (!this.k)
break label1068;
int i6 = paramaw.d();
i7 = -1 + h();
if (i7 < 0)
break label1062;
i5 = b(b(i7));
if ((i5 < 0) || (i5 >= i6))
break label1056;
label245: localav.a = i5;
localav.b = -2147483648;
}
if ((this.m == null) && ((localav.c != this.k) || (r() != this.l)))
{
null.c();
localav.d = true;
}
if ((h() > 0) && (this.m != null));
a(paramar);
this.s = false;
this.e = (this.d.f() / 0);
this.n = View.MeasureSpec.makeMeasureSpec(this.d.f(), 1073741824);
this.p = View.MeasureSpec.makeMeasureSpec(this.e, 1073741824);
this.o = View.MeasureSpec.makeMeasureSpec(0, 0);
a(localav.a, paramaw);
if (!localav.c)
break label1125;
f(-1);
a(paramar, this.f, paramaw);
f(1);
this.f.b = (localav.a + this.f.c);
a(paramar, this.f, paramaw);
label445: if (h() > 0)
{
if (!this.h)
break label1179;
a(paramar, paramaw, true);
b(paramar, paramaw, false);
}
}
while (true)
{
if (!paramaw.a())
{
this.i = -1;
this.j = -2147483648;
}
this.k = localav.c;
this.l = r();
this.m = null;
return;
StaggeredGridLayoutManager.SavedState localSavedState = this.m;
localSavedState.d = null;
localSavedState.c = 0;
localSavedState.e = 0;
localSavedState.f = null;
localSavedState.g = null;
this.m.a = this.m.b;
break;
label566: localav.c = this.h;
break label140;
q();
localav.c = this.h;
break label173;
label592: if ((this.i < 0) || (this.i >= paramaw.d()))
{
this.i = -1;
this.j = -2147483648;
i1 = 0;
break label191;
}
View localView;
label683: label746: int i14;
if ((this.m == null) || (this.m.a == -1) || (this.m.c <= 0))
{
localView = a(this.i);
if (localView != null)
{
int i11;
if (this.h)
{
i11 = s();
localav.a = i11;
if (this.j == -2147483648)
break label775;
if (!localav.c)
break label746;
}
for (localav.b = (this.a.d() - this.j - this.a.b(localView)); ; localav.b = (this.a.c() + this.j - this.a.a(localView)))
{
i1 = 1;
break;
i11 = t();
break label683;
}
label775: if (this.a.c(localView) > this.a.f())
if (localav.c)
{
i14 = this.a.d();
label810: localav.b = i14;
}
}
}
while (true)
{
i1 = 1;
break;
i14 = this.a.c();
break label810;
int i12 = this.a.a(localView) - this.a.c();
if (i12 < 0)
{
localav.b = (-i12);
continue;
}
int i13 = this.a.d() - this.a.b(localView);
if (i13 < 0)
{
localav.b = i13;
continue;
}
localav.b = -2147483648;
continue;
localav.a = this.i;
int i8;
int i10;
label950: boolean bool1;
if (this.j == -2147483648)
{
i8 = localav.a;
if (h() == 0)
if (this.h)
{
i10 = 1;
if (i10 != 1)
break label1022;
bool1 = true;
label959: localav.c = bool1;
localav.b();
}
}
while (true)
{
localav.d = true;
break;
i10 = -1;
break label950;
if (i8 < t());
for (int i9 = 1; ; i9 = 0)
{
if (i9 == this.h)
break label1016;
i10 = -1;
break;
}
label1016: i10 = 1;
break label950;
label1022: bool1 = false;
break label959;
localav.a(this.j);
}
localav.b = -2147483648;
localav.a = this.i;
}
label1056: i7--;
break label217;
label1062: i5 = 0;
break label245;
label1068: int i2 = paramaw.d();
int i3 = h();
for (int i4 = 0; ; i4++)
{
if (i4 >= i3)
break label1119;
i5 = b(b(i4));
if ((i5 >= 0) && (i5 < i2))
break;
}
label1119: i5 = 0;
break label245;
label1125: f(1);
a(paramar, this.f, paramaw);
f(-1);
this.f.b = (localav.a + this.f.c);
a(paramar, this.f, paramaw);
break label445;
label1179: b(paramar, paramaw, true);
a(paramar, paramaw, false);
}
}
public final void a(AccessibilityEvent paramAccessibilityEvent)
{
super.a(paramAccessibilityEvent);
AccessibilityRecordCompat localAccessibilityRecordCompat;
View localView1;
View localView2;
if (h() > 0)
{
localAccessibilityRecordCompat = AccessibilityEventCompat.asRecord(paramAccessibilityEvent);
localView1 = a(false, true);
localView2 = b(false, true);
if ((localView1 != null) && (localView2 != null));
}
else
{
return;
}
int i1 = b(localView1);
int i2 = b(localView2);
if (i1 < i2)
{
localAccessibilityRecordCompat.setFromIndex(i1);
localAccessibilityRecordCompat.setToIndex(i2);
return;
}
localAccessibilityRecordCompat.setFromIndex(i2);
localAccessibilityRecordCompat.setToIndex(i1);
}
public final void a(String paramString)
{
if (this.m == null)
super.a(paramString);
}
public final boolean a(ap paramap)
{
return paramap instanceof aO;
}
public final int b(int paramInt, ar paramar, aw paramaw)
{
return d(paramInt, paramar, paramaw);
}
public final int b(ar paramar, aw paramaw)
{
return 0;
}
public final int b(aw paramaw)
{
return g(paramaw);
}
public final Parcelable b()
{
if (this.m != null)
return new StaggeredGridLayoutManager.SavedState(this.m);
StaggeredGridLayoutManager.SavedState localSavedState = new StaggeredGridLayoutManager.SavedState();
localSavedState.h = this.g;
localSavedState.i = this.k;
localSavedState.j = this.l;
localSavedState.e = 0;
int i1;
View localView;
label98: int i2;
if (h() > 0)
{
e();
if (this.k)
{
i1 = s();
localSavedState.a = i1;
if (!this.h)
break label133;
localView = b(true, true);
if (localView != null)
break label143;
i2 = -1;
label105: localSavedState.b = i2;
localSavedState.c = 0;
localSavedState.d = new int[0];
}
}
while (true)
{
return localSavedState;
i1 = t();
break;
label133: localView = a(true, true);
break label98;
label143: i2 = b(localView);
break label105;
localSavedState.a = -1;
localSavedState.b = -1;
localSavedState.c = 0;
}
}
public final void b(int paramInt1, int paramInt2)
{
b(paramInt1, paramInt2, 1);
}
public final void b(View paramView, AccessibilityNodeInfoCompat paramAccessibilityNodeInfoCompat)
{
ViewGroup.LayoutParams localLayoutParams = paramView.getLayoutParams();
if (!(localLayoutParams instanceof aO))
{
super.a(paramView, paramAccessibilityNodeInfoCompat);
return;
}
aO localaO = (aO)localLayoutParams;
if (localaO.e == null);
for (int i1 = -1; ; i1 = localaO.e.d)
{
paramAccessibilityNodeInfoCompat.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(i1, 1, -1, -1, false, false));
return;
}
}
public final int c(ar paramar, aw paramaw)
{
return super.c(paramar, paramaw);
}
public final int c(aw paramaw)
{
return h(paramaw);
}
public final void c(int paramInt)
{
super.c(paramInt);
}
public final void c(int paramInt1, int paramInt2)
{
b(paramInt1, paramInt2, 2);
}
public final boolean c()
{
return true;
}
public final int d(aw paramaw)
{
return h(paramaw);
}
public final void d(int paramInt)
{
super.d(paramInt);
}
public final void d(int paramInt1, int paramInt2)
{
b(paramInt1, paramInt2, 3);
}
public final boolean d()
{
return false;
}
public final int e(aw paramaw)
{
return i(paramaw);
}
public final void e(int paramInt)
{
if (paramInt == 0)
h();
}
public final int f(aw paramaw)
{
return i(paramaw);
}
public final boolean f()
{
return this.m == null;
}
public final void p()
{
null.c();
g();
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.v7.widget.StaggeredGridLayoutManager
* JD-Core Version: 0.6.0
*/ | 23.46866 | 184 | 0.527263 |
9369c4b64b25a88cd0260e8906972e8806619304 | 8,688 | package org.cloudfoundry.vr;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;
@WebIntegrationTest(value = "server.port=9873")
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { Application.class })
public class VrCatalogTest {
ParameterizedTypeReference<Map<String, String>> mapType = new ParameterizedTypeReference<Map<String, String>>() {
};
ParameterizedTypeReference<HttpEntity<String>> stringType = new ParameterizedTypeReference<HttpEntity<String>>() {
};
private final RestTemplate restTemplate = new TestRestTemplate();
private static final String URI = "http://localhost:9873";
@Test
public void testGetToken() {
ResponseEntity<Map<String, String>> token = getToken();
assertNotNull(token);
assertEquals(HttpStatus.OK, token.getStatusCode());
assertEquals("mycompany", token.getBody().get("tenant"));
}
@Test
public void testCheckToken() {
ResponseEntity<Map<String, String>> token = getToken();
assertNotNull(token);
assertEquals(HttpStatus.NO_CONTENT, checkToken(token.getBody()
.get("id")));
assertEquals(HttpStatus.FORBIDDEN, checkToken(null));
}
@Test
public void testGetCatalog() {
ResponseEntity<String> resp = getCatalog(VrController.TOKEN);
assertNotNull(resp);
assertEquals(HttpStatus.OK, resp.getStatusCode());
String cat = resp.getBody().toString();
assertNotNull(cat);
assertEquals("nsumerEnti", cat.substring(70, 80));
}
@Test
public void testGetTemplateRequest() {
ResponseEntity<String> resp = getTemplateRequest(VrController.TOKEN,
VrController.CATALOG_ID);
assertNotNull(resp);
assertEquals(HttpStatus.OK, resp.getStatusCode());
String temp = resp.getBody().toString();
assertNotNull(temp);
assertEquals("sioningReq", temp.substring(70, 80));
}
@Test
public void testPostRequest() {
ResponseEntity<String> resp = postRequest(VrController.TOKEN,
VrController.CATALOG_ID, VrController.getJson("template.json"));
assertNotNull(resp);
assertEquals(HttpStatus.CREATED, resp.getStatusCode());
String temp = resp.getBody().toString();
assertNotNull(temp);
assertEquals("b-edd7c798", temp.substring(70, 80));
}
@Test
public void testRequestDetails() {
ResponseEntity<String> dets = getRequestDetails(VrController.TOKEN,
VrController.REQUEST_ID);
assertNotNull(dets);
assertEquals(HttpStatus.OK, dets.getStatusCode());
assertEquals("b-edd7c798", dets.getBody().substring(70, 80));
}
@Test
public void testResources() {
ResponseEntity<String> dets = getResources(VrController.TOKEN,
VrController.REQUEST_ID);
assertNotNull(dets);
assertEquals(HttpStatus.OK, dets.getStatusCode());
assertEquals("talogResou", dets.getBody().substring(70, 80));
}
@Test
public void testChild() {
ResponseEntity<String> child = getChild(VrController.TOKEN,
VrController.RESOURCE_ID);
assertNotNull(child);
assertEquals(HttpStatus.OK, child.getStatusCode());
assertEquals(" \"@type\": ", child.getBody().substring(150, 160));
}
@Test
public void testActionTemplate() {
ResponseEntity<String> temp = getActionTemplate(VrController.TOKEN,
VrController.RESOURCE_ID, VrController.ACTION_ID);
assertNotNull(temp);
assertEquals(HttpStatus.OK, temp.getStatusCode());
assertEquals("e resolved", temp.getBody().substring(50, 60));
}
// TODO string these together by processing responses
@Test
public void testUseCase() {
// get an auth token
Map<String, String> token = getToken().getBody();
assertNotNull(token);
// make sure it's valid
assertEquals(HttpStatus.NO_CONTENT, checkToken(token.get("id")));
// make sure it's still valid
assertNotNull(getCatalog(token.get("id")));
// get the catalog
assertNotNull(getCatalog(token.get("id")));
// get a template to request something from the catalog
assertNotNull(getTemplateRequest(token.get("id"),
VrController.CATALOG_ID));
// use the template to make the request
assertNotNull(postRequest(token.get("id"), VrController.CATALOG_ID,
VrController.getJson("template.json")));
// check on the request
assertNotNull(getRequestDetails(token.get("id"),
VrController.REQUEST_ID));
// see the resources created by the request
assertNotNull(getResources(token.get("id"), VrController.REQUEST_ID));
// see the details on a resource created by the request
assertNotNull(getChild(token.get("id"), VrController.RESOURCE_ID));
// get an action template
assertNotNull(getActionTemplate(token.get("id"),
VrController.RESOURCE_ID, VrController.ACTION_ID));
}
private ResponseEntity<Map<String, String>> getToken() {
Map<String, String> m = new HashMap<String, String>();
m.put("username", "csummers@example.com");
m.put("password", "mypassword");
m.put("tenant", "mycompany");
return restTemplate.exchange(URI + "/identity/api/tokens",
HttpMethod.POST, new HttpEntity<Map<String, String>>(m),
mapType);
}
private HttpStatus checkToken(String token) {
return restTemplate.exchange(URI + "/identity/api/tokens/" + token,
HttpMethod.GET, null, stringType).getStatusCode();
}
private ResponseEntity<String> getCatalog(String token) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", " Bearer " + token);
HttpEntity<String> he = new HttpEntity<String>(headers);
return restTemplate.exchange(URI
+ "/catalog-service/api/consumer/entitledCatalogItemViews",
HttpMethod.GET, he, String.class);
}
private ResponseEntity<String> getTemplateRequest(String token,
String catalogId) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", " Bearer " + token);
HttpEntity<String> he = new HttpEntity<String>(headers);
return restTemplate.exchange(URI
+ "/service/api/consumer/entitledCatalogItems/" + catalogId
+ "/requests/template", HttpMethod.GET, he, String.class);
}
private ResponseEntity<String> postRequest(String token, String catalogId,
String body) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", " Bearer " + token);
HttpEntity<String> he = new HttpEntity<String>(body, headers);
return restTemplate.exchange(URI
+ "/service/api/consumer/entitledCatalogItems/ " + catalogId
+ "/requests", HttpMethod.POST, he, String.class);
}
private ResponseEntity<String> getRequestDetails(String token,
String requestId) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", " Bearer " + token);
HttpEntity<String> he = new HttpEntity<String>(headers);
return restTemplate.exchange(URI
+ "/catalog-service/api/consumer/requests/" + requestId,
HttpMethod.GET, he, String.class);
}
private ResponseEntity<String> getResources(String token, String requestId) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", " Bearer " + token);
HttpEntity<String> he = new HttpEntity<String>(headers);
return restTemplate.exchange(URI
+ "/catalog-service/api/consumer/requests/" + requestId
+ "/resourceViews", HttpMethod.GET, he, String.class);
}
private ResponseEntity<String> getChild(String token, String resourceId) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", " Bearer " + token);
HttpEntity<String> he = new HttpEntity<String>(headers);
return restTemplate.exchange(URI
+ "/catalogservice/api/consumer/resourceViews/" + resourceId,
HttpMethod.GET, he, String.class);
}
private ResponseEntity<String> getActionTemplate(String token,
String resourceId, String actionId) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", " Bearer " + token);
HttpEntity<String> he = new HttpEntity<String>(headers);
return restTemplate.exchange(URI
+ "/catalog-service/api/consumer/resources/" + resourceId
+ "/actions/" + actionId + "/requests/template",
HttpMethod.GET, he, String.class);
}
}
| 33.9375 | 115 | 0.746202 |
ea7544f461ae2847dd563291759d250b4f1d47e9 | 144 | package com.zgkxzx.modbus4And.sero.messaging;
public interface OutgoingResponseMessage extends OutgoingMessage {
// A marker interface.
}
| 20.571429 | 66 | 0.798611 |
98d4020da2f939541d3a51bc7c496e83fd3248d1 | 3,335 | package org.dew.fhir.model;
import java.io.Serializable;
/**
*
* The detailed description of a substance, typically at a level beyond what is used for prescribing.
*
* @see <a href="https://www.hl7.org/fhir">SubstanceSpecification_Relationship</a>
*/
public
class SubstanceSpecificationRelationship extends BackboneElement implements Serializable
{
private static final long serialVersionUID = 1L;
protected Ratio amountRatio;
protected CodeableConcept amountType;
protected CodeableConcept substanceCodeableConcept;
protected Reference<Resource>[] source;
protected Ratio amountRatioLowLimit;
protected Boolean isDefining;
protected Quantity amountQuantity;
protected String amountString;
protected Range amountRange;
protected CodeableConcept relationship;
protected Reference<Resource> substanceReference;
public SubstanceSpecificationRelationship()
{
}
public Ratio getAmountRatio() {
return amountRatio;
}
public void setAmountRatio(Ratio amountRatio) {
this.amountRatio = amountRatio;
}
public CodeableConcept getAmountType() {
return amountType;
}
public void setAmountType(CodeableConcept amountType) {
this.amountType = amountType;
}
public CodeableConcept getSubstanceCodeableConcept() {
return substanceCodeableConcept;
}
public void setSubstanceCodeableConcept(CodeableConcept substanceCodeableConcept) {
this.substanceCodeableConcept = substanceCodeableConcept;
}
public Reference<Resource>[] getSource() {
return source;
}
public void setSource(Reference<Resource>[] source) {
this.source = source;
}
public Ratio getAmountRatioLowLimit() {
return amountRatioLowLimit;
}
public void setAmountRatioLowLimit(Ratio amountRatioLowLimit) {
this.amountRatioLowLimit = amountRatioLowLimit;
}
public Boolean getIsDefining() {
return isDefining;
}
public void setIsDefining(Boolean isDefining) {
this.isDefining = isDefining;
}
public Quantity getAmountQuantity() {
return amountQuantity;
}
public void setAmountQuantity(Quantity amountQuantity) {
this.amountQuantity = amountQuantity;
}
public String getAmountString() {
return amountString;
}
public void setAmountString(String amountString) {
this.amountString = amountString;
}
public Range getAmountRange() {
return amountRange;
}
public void setAmountRange(Range amountRange) {
this.amountRange = amountRange;
}
public CodeableConcept getRelationship() {
return relationship;
}
public void setRelationship(CodeableConcept relationship) {
this.relationship = relationship;
}
public Reference<Resource> getSubstanceReference() {
return substanceReference;
}
public void setSubstanceReference(Reference<Resource> substanceReference) {
this.substanceReference = substanceReference;
}
@Override
public boolean equals(Object object) {
if(object instanceof SubstanceSpecificationRelationship) {
return this.hashCode() == object.hashCode();
}
return false;
}
@Override
public int hashCode() {
if(id == null) return 0;
return id.hashCode();
}
@Override
public String toString() {
return "SubstanceSpecificationRelationship(" + id + ")";
}
}
| 23.992806 | 101 | 0.732534 |
c9f8b7bdbed8c41543fde43d9ddce7fba71f4ded | 773 | package org.ranji.lemon.service.authority.impl;
import java.util.List;
import org.ranji.lemon.model.authority.Resource;
import org.ranji.lemon.persist.authority.prototype.IResourceDao;
import org.ranji.lemon.persist.oauth2.prototype.IClientDao;
import org.ranji.lemon.service.authority.prototype.IResourceService;
import org.ranji.lemon.service.common.impl.GenericServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ResourceServiceImpl extends GenericServiceImpl<Resource, Integer> implements IResourceService {
@Override
public List<Integer> findROsByResourceId(int resourceId) {
return ((IResourceDao)dao).findROsByResourceId(resourceId);
}
}
| 33.608696 | 109 | 0.809832 |
c7f9e365e735816ff7078272b1a51bd93eaf5d53 | 567 | package ru.intertrust.cm.core.gui.api.server.widget;
import ru.intertrust.cm.core.business.api.dto.DomainObjectTypeAndAccessValue;
import ru.intertrust.cm.core.business.api.dto.Dto;
import ru.intertrust.cm.core.business.api.dto.StringValue;
import ru.intertrust.cm.core.gui.api.server.ComponentHandler;
/**
* @author Yaroslav Bondarchuk
* Date: 27.10.2014
* Time: 21:22
*/
public interface DomainObjectTypeExtractor extends ComponentHandler {
StringValue getType(Dto input);
DomainObjectTypeAndAccessValue getTypeAndAccess(Dto input);
}
| 33.352941 | 77 | 0.776014 |
3da705ecbc1c55834ebeb6d0dd20b50533007489 | 6,671 | package com.eclipsekingdom.fractalforest.gui.page.pop;
import com.eclipsekingdom.fractalforest.gui.PopData;
import com.eclipsekingdom.fractalforest.gui.SessionData;
import com.eclipsekingdom.fractalforest.gui.page.Icons;
import com.eclipsekingdom.fractalforest.gui.page.PageContents;
import com.eclipsekingdom.fractalforest.gui.page.PageType;
import com.eclipsekingdom.fractalforest.util.X.XMaterial;
import com.eclipsekingdom.fractalforest.worldgen.pop.TreePopulator;
import com.eclipsekingdom.fractalforest.worldgen.pop.TreeSpawner;
import com.eclipsekingdom.fractalforest.worldgen.pop.util.TreeBiome;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import static com.eclipsekingdom.fractalforest.sys.language.Message.*;
public class PopHome implements PageContents {
private Material writtenBook = XMaterial.WRITABLE_BOOK.parseMaterial();
@Override
public Inventory populate(Inventory menu, SessionData sessionData) {
PopData popData = sessionData.getPopData();
TreePopulator pop = popData.getPopulator();
LinkedHashMap<TreeBiome, List<TreeSpawner>> biomeToTreeSpawners = pop.getBiomeToTreeSpawner();
List<TreeBiome> biomes = new ArrayList<>();
for (TreeBiome biome : biomeToTreeSpawners.keySet()) {
if (biome != TreeBiome.NONE) {
biomes.add(biome);
}
}
menu.setItem(4, Icons.createIcon(Material.NAME_TAG, ChatColor.GRAY + pop.getName()));
int offset = sessionData.getPageOffsetX();
int biomesSize = biomeToTreeSpawners.size();
for (int i = 0; i < 7; i++) {
int index = i + 10;
if (biomesSize > i + offset) {
TreeBiome biome = biomes.get(i + offset);
createColumn(menu, index, biome, biomeToTreeSpawners.get(biome), sessionData.getPageOffsetY());
} else {
if (biomesSize > i - 1 + offset) {
menu.setItem(index, Icons.createIcon(writtenBook, ChatColor.GRAY + LABEL_EDIT.toString()));
} else {
menu.setItem(index, Icons.BACKGROUND_ITEM);
}
for (int j = 1; j < 4; j++) {
menu.setItem(index + (9 * j), Icons.BACKGROUND_ITEM);
}
}
}
menu.setItem(26, Icons.createIcon(Material.TRIPWIRE_HOOK, MENU_SCROLL_UP.toString()));
menu.setItem(35, Icons.createIcon(Material.STONE_BUTTON, "+" + sessionData.getPageOffsetY()));
menu.setItem(44, Icons.createIcon(Material.HOPPER, MENU_SCROLL_DOWN.toString()));
menu.setItem(48, Icons.createIcon(Material.ARROW, MENU_SCROLL_LEFT.toString()));
menu.setItem(49, Icons.createIcon(Material.STONE_BUTTON, "+" + sessionData.getPageOffsetX()));
menu.setItem(50, Icons.createIcon(Material.ARROW, MENU_SCROLL_RIGHT.toString()));
return menu;
}
private void createColumn(Inventory menu, int column, TreeBiome biome, List<TreeSpawner> treeSpawners, int offsetY) {
menu.setItem(column, biome.getItemStack());
int offset = offsetY;
int spawnersSize = treeSpawners.size();
for (int i = 0; i < 3; i++) {
int index = column + 9 + (9 * i);
if (spawnersSize > i + offset) {
TreeSpawner treeSpawner = treeSpawners.get(i + offset);
menu.setItem(index, Icons.createTreeSpawner(treeSpawner));
} else {
if (spawnersSize > i - 1 + offset) {
menu.setItem(index, Icons.createIcon(writtenBook, ChatColor.GRAY + LABEL_EDIT.toString()));
} else {
menu.setItem(index, Icons.BACKGROUND_ITEM);
}
}
}
}
@Override
public void processClick(Player player, Inventory menu, SessionData sessionData, int slot, ClickType clickType) {
PopData popData = sessionData.getPopData();
if (slot == 26) {
sessionData.scrollUp(player, this, menu);
} else if (slot == 44) {
sessionData.scrollDown(player, this, menu);
} else if (slot == 48) {
sessionData.scrollLeft(player, this, menu);
} else if (slot == 50) {
sessionData.scrollRight(player, this, menu);
} else {
ItemStack itemStack = menu.getItem(slot);
if (itemStack != null && itemStack.getType() != Icons.BACKGROUND_ITEM.getType()) {
if (itemStack.getType() == writtenBook) {
if (slot / 9 == 1) {
sessionData.transition(player, PageType.BIOME_OVERVIEW);
} else {
int top = slot % 9 + 9;
ItemStack biomeItem = menu.getItem(top);
TreeBiome biome = TreeBiome.valueOf(biomeItem.getItemMeta().getDisplayName());
popData.setCurrentBiome(biome);
sessionData.transition(player, PageType.TREE_OVERVIEW);
}
} else if (!isCorner(slot)) {
int top = slot % 9 + 9;
ItemStack biomeItem = menu.getItem(top);
if (biomeItem != null) {
TreePopulator pop = popData.getPopulator();
try {
TreeBiome biome = TreeBiome.valueOf(biomeItem.getItemMeta().getDisplayName());
List<TreeSpawner> treeSpawners = pop.getBiomeToTreeSpawner().get(biome);
ItemStack spawnStack = menu.getItem(slot);
if (spawnStack != null && spawnStack.getType() != Icons.BACKGROUND_ITEM.getType() && spawnStack.getType() != writtenBook) {
int index = (slot / 9) - 2 + sessionData.getPageOffsetY();
TreeSpawner spawner = treeSpawners.get(index);
popData.setCurrentSpawner(spawner);
popData.setCurrentBiome(biome);
sessionData.transition(player, PageType.SPAWNER);
}
} catch (Exception e) {
}
}
}
}
}
}
private boolean isCorner(int slot) {
return slot % 9 == 0 || (slot + 1) % 9 == 0;
}
}
| 45.074324 | 151 | 0.58402 |
2a0442752e7452bda0a8bf2638ffa02614cc5ad9 | 2,218 | package org.bavand.adaptors;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.bavand.R;
import org.bavand.custom.TagView;
import org.bavand.models.ShopModel;
import java.util.List;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
public class SearchAdaptor extends RecyclerView.Adapter<SearchAdaptor.ViewHolder> {
List<ShopModel> shopModels;
Context context;
public SearchAdaptor(List<ShopModel> shopModel, Context context) {
this.shopModels = shopModel;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.search_shop_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Glide.with(context).load(shopModels.get(position).getImageURL1()).dontAnimate().into(holder.imageViewShop);
holder.textViewShopTitle.setText(shopModels.get(position).getTitle());
holder.textViewShopCity.setText(shopModels.get(position).getCityID());
holder.tagViewCategory.setMono_title(shopModels.get(position).getCategoryId());
}
@Override
public int getItemCount() {
return shopModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.cardViewSearchShopList)
CardView cardViewSearchShopList;
@BindView(R.id.imageViewShop)
ImageView imageViewShop;
@BindView(R.id.textViewShopTitle)
TextView textViewShopTitle;
@BindView(R.id.textViewShopCity)
TextView textViewShopCity;
@BindView(R.id.tagViewCategory)
TagView tagViewCategory;
public ViewHolder(View v) {
super(v);
ButterKnife.bind(this, v);
}
}
}
| 28.805195 | 115 | 0.712804 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.