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
|
---|---|---|---|---|---|
21fee08bac7b4176b84885e1c6337711fe02fc86 | 242 | package leetcode.S0199;
import define.TreeNode;
import java.util.List;
/**
* 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
return null;
}
}
| 14.235294 | 55 | 0.702479 |
1a05723a761a32e4f7c5daf4f76cd61bfca083ed | 7,421 | package itests.net.osgiliath.sample.webapp.business.impl;
/*
* #%L
* net.osgiliath.hello.business.impl
* %%
* Copyright (C) 2013 Osgiliath
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.maven;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.features;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.inject.Inject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import lombok.extern.slf4j.Slf4j;
import net.osgiliath.module.exam.AbstractPaxExamKarafConfiguration;
import net.osgiliath.sample.webapp.business.spi.model.Hellos;
import net.osgiliath.sample.webapp.model.entities.HelloEntity;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Component;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.ProducerTemplate;
import org.apache.karaf.features.BootFinished;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.ops4j.pax.exam.util.Filter;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
/**
* Test a CDI web service and JMS messages.
*
* @author charliemordant
*
*/
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
@Slf4j
public class ITHelloServiceJaxRS extends AbstractPaxExamKarafConfiguration {
/**
* Boot finished event.
*/
@Inject
@Filter(timeout = 400000)
private transient BootFinished bootFinished;
/**
* OSGI Bundle context.
*/
@Inject
private transient BundleContext bundleContext;
/**
* JMS template.
*/
@Inject
@Filter(value = "(component-type=jms)")
private transient Component jmsComponent;
/**
* exported REST address.
*/
private static final String SERVICE_BASE_URL = "http://localhost:8181/cxf/helloService";
/**
* probe adding the abstract test class.
*
* @param builder
* the pax probe builder
* @return the provisionned probe.
*/
@ProbeBuilder
public TestProbeBuilder extendProbe(TestProbeBuilder builder) {
builder.addTest(AbstractPaxExamKarafConfiguration.class);
builder.setHeader(Constants.EXPORT_PACKAGE, this.getClass().getPackage().getName()
);
builder.setHeader(Constants.BUNDLE_MANIFESTVERSION, "2");
builder.setHeader(Constants.DYNAMICIMPORT_PACKAGE, "*");
return builder;
}
/**
* Cleans all data.
*/
@Before
public void cleanMessages() {
final Client client = ClientBuilder.newClient();
WebTarget target = client.target(SERVICE_BASE_URL);
target = target.path("hello");
final Invocation.Builder builder = target
.request(MediaType.APPLICATION_XML);
builder.delete();
client.close();
}
/**
* Web service call test.
*
*/
@Test
public void testSayHello() {
log.trace("************ start testSayHello **********************");
final Client client = ClientBuilder.newClient();
WebTarget target = client.target(SERVICE_BASE_URL);
target = target.path("hello");
final Invocation.Builder builder = target
.request(MediaType.APPLICATION_XML);
builder
.post(Entity.xml(HelloEntity.builder().helloMessage("John").build()));
final Invocation.Builder respbuilder = target
.request(MediaType.APPLICATION_XML);
final Hellos hellos = respbuilder.get(Hellos.class);
assertEquals(1, hellos.getHelloCollection().size());
client.close();
log.trace("************ end testSayHello **********************");
}
/**
* Test REST message error (look at the console trace).
*
*/
@Test
public void testSayHelloValidationError() {
if (log.isDebugEnabled()) {
log.trace("************ start testSayHelloValidationError *************");
log.debug("************Listing **********************");
for (final Bundle b : this.bundleContext.getBundles()) {
log.debug("bundle: " + b.getSymbolicName() + ", state: " + b.getState());
}
log.debug("********* End list ****************");
}
final Client client = ClientBuilder.newClient();
WebTarget target = client.target(SERVICE_BASE_URL);
target = target.path("hello");
final Invocation.Builder builder = target.request(MediaType.APPLICATION_XML);
builder.post(Entity.xml(HelloEntity.builder().helloMessage("J").build()));
log.trace("************ end testSayHelloValidationError ******************");
}
/**
* Test JMS call.
* @throws CamelExecutionException
* @throws IOException
*/
@Test
public void testSayHelloJMS() throws CamelExecutionException, IOException {
log.info("************ start testSayHelloJMS **********************");
if (log.isDebugEnabled()) {
log.debug("Component: " + this.jmsComponent);
log.trace("Camel context: " + this.jmsComponent.getCamelContext());
}
final ProducerTemplate template = this.jmsComponent.getCamelContext()
.createProducerTemplate();
log.trace("Producer template: " + template);
ObjectMapper mapper = new ObjectMapper();
template.sendBody("jms:queue:helloServiceQueueIn", mapper.writeValueAsString(HelloEntity.builder()
.helloMessage("Doe").build()));
final ConsumerTemplate consumer = this.jmsComponent.getCamelContext()
.createConsumerTemplate();
final Hellos hellos = mapper.readValue(consumer.receiveBody(
"jms:topic:helloServiceQueueOut", String.class), Hellos.class);
assertTrue(hellos.getHelloCollection().size() > 0);
log.info("************ end testSayHelloJMS **********************");
}
/**
* Karaf feature to test.
* @return the feature
*/
@Override
protected Option featureToTest() {
return features(
maven().groupId(System.getProperty(MODULE_GROUP_ID))
.artifactId("net.osgiliath.sample.webapp.features")
.type("xml").classifier("features").versionAsInProject(),
"net.osgiliath.sample.webapp.business.itests");
}
static {
// uncomment to enable debugging of this test class
// paxRunnerVmOption = DEBUG_VM_OPTION; //NOSONAR
}
/**
* Pax exam configuration creation.
* @return the provisionned configuration
*/
@Configuration
public Option[] config() {
return createConfig();
}
}
| 32.548246 | 102 | 0.689799 |
7ec41b31b3b29f6a260c4f57a8e1d11a9741abc7 | 4,793 | package com.sfgassistant;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.cengalabs.flatui.FlatUI;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.mxn.soul.flowingdrawer_core.FlowingView;
import com.mxn.soul.flowingdrawer_core.LeftDrawerLayout;
import com.sfgassistant.models.ModelManager;
import com.sfgassistant.utils.Constants;
import com.sfgassistant.views.MyMenu;
import com.sfgassistant.widgets.MyViewPager;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.fabric.sdk.android.Fabric;
/**
* Created by pierr on 17/09/2016.
*/
public class MainActivity extends AppCompatActivity {
@BindView(R.id.adView) AdView mAdView;
@BindView(R.id.view_pager) MyViewPager viewPager;
private boolean drawerMenu;
private LeftDrawerLayout mLeftDrawerLayout;
private Toolbar toolbar;
private ModelManager modelManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
SharedPreferences preferences = getSharedPreferences(getString(R.string.package_name), Context.MODE_PRIVATE);
drawerMenu = preferences.getBoolean(Constants.SHARED_PREFS_MENU_DRAWER, false);
FlatUI.initDefaultValues(this);
FlatUI.setDefaultTheme(R.array.button_active);
if (drawerMenu)
setContentView(R.layout.activity_main_drawer_menu);
else
setContentView(R.layout.activity_main_bottom_nav_bar);
ButterKnife.bind(this);
setupToolbar();
modelManager = new ModelManager(getAssets());
MainPagerAdapter pagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(3);
if (drawerMenu) {
setupDrawerMenu();
viewPager.setPagingEnabled(false);
}
else {
toolbar.setVisibility(View.GONE);
setupTabLayout(pagerAdapter);
viewPager.setPagingEnabled(true);
}
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
private void setupToolbar() {
toolbar = ButterKnife.findById(this, R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mLeftDrawerLayout.toggle();
}
});
}
private void setupDrawerMenu() {
mLeftDrawerLayout = ButterKnife.findById(this, R.id.drawerlayout);
FragmentManager fm = getSupportFragmentManager();
MyMenu myMenu = (MyMenu) fm.findFragmentById(R.id.container_menu);
FlowingView flowingView = ButterKnife.findById(this, R.id.sv);
if (myMenu == null)
fm.beginTransaction().add(R.id.container_menu, myMenu = new MyMenu()).commit();
mLeftDrawerLayout.setFluidView(flowingView);
mLeftDrawerLayout.setMenuFragment(myMenu);
}
private void setupTabLayout(MainPagerAdapter pagerAdapter) {
TabLayout tabLayout = ButterKnife.findById(this, R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null)
tab.setCustomView(pagerAdapter.getTabView(this, i));
}
}
@Override
public void onPause() {
if (mAdView != null)
mAdView.pause();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
if (mAdView != null)
mAdView.resume();
}
@Override
public void onDestroy() {
if (mAdView != null)
mAdView.destroy();
super.onDestroy();
}
@Override
public void onBackPressed() {
if (drawerMenu && mLeftDrawerLayout.isShownMenu())
mLeftDrawerLayout.closeDrawer();
else
super.onBackPressed();
}
public void closeDrawer(int position) {
viewPager.setCurrentItem(position);
mLeftDrawerLayout.closeDrawer();
}
public ModelManager getModelManager() {
return modelManager;
}
}
| 30.922581 | 117 | 0.677655 |
5a460971d52bfbdb8e04f75753458ae7f133c400 | 2,297 | package theHeart.cards;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.actions.common.ApplyPowerAction;
import com.megacrit.cardcrawl.actions.common.DrawCardAction;
import com.megacrit.cardcrawl.actions.common.ExhaustAction;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.helpers.DrawMaster;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import com.megacrit.cardcrawl.powers.PoisonPower;
import com.megacrit.cardcrawl.powers.RegenPower;
import theHeart.DefaultMod;
import theHeart.characters.TheDefault;
import static theHeart.DefaultMod.makeCardPath;
public class BloodFlow extends AbstractDynamicCard
{
public static final String ID = DefaultMod.makeID( BloodFlow .class.getSimpleName());
public static final String IMG = makeCardPath("Skill.png");
// /TEXT DECLARATION/
// STAT DECLARATION
private static final AbstractCard.CardRarity RARITY = AbstractCard.CardRarity.UNCOMMON;
private static final AbstractCard.CardTarget TARGET = AbstractCard.CardTarget.NONE;
private static final AbstractCard.CardType TYPE = AbstractCard.CardType.SKILL;
public static final AbstractCard.CardColor COLOR = TheDefault.Enums.COLOR_GRAY;
private static final int COST = 1;
private static final int MAGIC_NUMBER = 2;
private static final int UPGRADE_PLUS_MAGIC_NUMBER = 1;
// /STAT DECLARATION/
public BloodFlow () {
super(ID, IMG, COST, TYPE, COLOR, RARITY, TARGET);
baseMagicNumber = magicNumber = MAGIC_NUMBER;
}
// Actions the card should do.
@Override
public void use(AbstractPlayer p, AbstractMonster m) {
AbstractDungeon.actionManager.addToBottom(new ExhaustAction(p,p,1, false, false, false));
AbstractDungeon.actionManager.addToBottom (new DrawCardAction(p,magicNumber,false));
}
public AbstractDynamicCard makeCopy() { return new BloodFlow (); }
// Upgraded stats.
@Override
public void upgrade() {
if (!upgraded) {
upgradeName();
upgradeMagicNumber(UPGRADE_PLUS_MAGIC_NUMBER);
initializeDescription();
}
}
}
| 33.779412 | 97 | 0.75185 |
cd6a35a056a240d573e9fa233346a0aec8e3e73b | 1,858 | package com.competitiveCodes.VPCodingBlocks.Graph;
import java.util.Iterator;
import java.util.LinkedList;
public class CheckCyclicDirectedGraph {
private static int V;
private static LinkedList<Integer> adj[];
static void Graph(int v){
V = v;
adj = new LinkedList[V];
for (int i = 0; i < V; i++)
adj[i] = new LinkedList<>();
}
public static void main(String[] args) {
CheckCyclicDirectedGraph checkCyclicDirectedGraph=new CheckCyclicDirectedGraph();
checkCyclicDirectedGraph.Graph(4);
checkCyclicDirectedGraph.addEdge(0, 1);
checkCyclicDirectedGraph.addEdge(0, 2);
checkCyclicDirectedGraph.addEdge(1, 2);
checkCyclicDirectedGraph.addEdge(2, 0);
checkCyclicDirectedGraph.addEdge(2, 3);
checkCyclicDirectedGraph.addEdge(3, 3);
if(isCyclic())
System.out.println("Graph is cyclic");
else
System.out.println("Graph is not cyclic");
}
public static boolean isCyclic() {
boolean visited[]=new boolean[V];
boolean recStack[] = new boolean[V];
for (int i = 0; i < V; i++) {
if(isCyclicUtil(i,visited,recStack))
return true;
}
return false;
}
private static boolean isCyclicUtil(int v, boolean[] visited, boolean[] recStack) {
if(recStack[v])
return true;
if(visited[v])
return false;
visited[v] = true;
recStack[v] = true;
Iterator<Integer> itrList=adj[v].listIterator();
while (itrList.hasNext()){
if(isCyclicUtil(itrList.next(),visited,recStack))
return true;
}
recStack[v] = false;
return false;
}
private void addEdge(int u, int v) {
adj[u].add(v);
}
}
| 24.447368 | 89 | 0.585576 |
f61b288e771ea45b5e6c82f8a44c167eb651ac5b | 1,817 | package org.rcsb.cif.model;
import java.util.List;
import java.util.stream.Stream;
/**
* The base of all {@link Category} implementations. Provides access to child columns.
*/
public interface Category {
/**
* The name of this {@link Category}.
* @return String of the name
*/
String getCategoryName();
/**
* The number of rows in this {@link Category}. 0 for undefined categories.
* @return the number of rows
*/
int getRowCount();
/**
* Retrieve a specific {@link Column} by name.
* @param name the column name
* @return the {@link Column}, empty {@link BaseColumn} if no column of that name exists
*/
Column getColumn(String name);
/**
* Names of all present columns.
* @return a collection of {@link Column} names
*/
List<String> getColumnNames();
/**
* Traverse all names of present columns.
* @return a {@link Stream} of present {@link Column} names
*/
default Stream<String> columnNamesEncoded() {
return getColumnNamesEncoded().stream();
}
default Stream<String> columnNames() {
return getColumnNames().stream();
}
/**
* Traverse all present columns.
* @return a {@link Stream} of all present columns
*/
default Stream<Column> columns() {
return columnNames().map(this::getColumn);
}
default Category get() {
return this;
}
/**
* States whether this {@link Category} is defined.
* @return <code>true</code> if this {@link Category} contains data
*/
boolean isDefined();
List<String> getColumnNamesEncoded();
double[][] fillFloat(String... colNames);
FloatColumn getFloatColumn(String name);
IntColumn getIntColumn(String name);
StrColumn getStrColumn(String name);
}
| 24.226667 | 92 | 0.63071 |
57fae4aea3cd53a1c8de331176a6c2e44a794c72 | 1,107 | package com.mathlayout.expressions.ast;
import com.mathlayout.expressions.ExpressionParser;
import com.mathlayout.expressions.ast.base.BaseBinaryOperatorAst;
/**
* @author Dmitry
*/
public class AssignAst extends BaseBinaryOperatorAst {
public AssignAst(ExpressionParser expressionParser) {
super(expressionParser);
}
@Override
public float process() {
if (!(leftOperand instanceof VariableAst)) {
throw new IllegalArgumentException("You should put variable name at left of '=' but you have provided [" + leftOperand + "] of class ["+leftOperand.getClass().getSimpleName()+"]");
}
VariableAst varAst = (VariableAst) leftOperand;
float result=rightOperand.process();
expressionParser.setVariable(varAst.getVariableName(), result);
return result;
}
@Override
public float processValues(float left, float right) {
throw new UnsupportedOperationException("Should not be implemented");
}
@Override
public String toString() {
return "" + leftOperand + "=" + rightOperand;
}
}
| 29.918919 | 192 | 0.68654 |
245f06c496d1033a967baac53b679c0754c72752 | 2,335 | package com.jayqqaa12.im.gateway.protool.base;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.jayqqaa12.im.common.model.consts.Resp;
import com.jayqqaa12.im.common.model.vo.TcpReqVO;
import com.jayqqaa12.im.common.model.vo.TcpRespVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
@Data
@Slf4j
public class TcpContext implements Cloneable {
private boolean login;
private Long connectTime;
private RespChannel respChannel;
private String platform;
private Long userId;
private String device;
private static Cache<String, TcpRespVO> cache = CacheBuilder.newBuilder()
.maximumSize(1024 * 1024 * 100)
.expireAfterAccess(10, TimeUnit.MINUTES).build();
public String getUserOrDevice() {
Long id = getUserId();
return id != null ? id + "" : getDevice();
}
public void response(TcpReqVO req, Integer code) {
TcpRespVO vo = TcpRespVO.response(req, code, null);
respChannel.resp(vo);
cache.put(req.getUuid(), vo);
}
public void response(TcpReqVO req, Object data) {
TcpRespVO vo = TcpRespVO.response(req, Resp.OK, data);
respChannel.resp(vo);
cache.put(req.getUuid(), vo);
}
public void response(TcpReqVO req, Integer code, Object data) {
TcpRespVO vo = TcpRespVO.response(req, code, data);
respChannel.resp(vo);
cache.put(req.getUuid(), vo);
}
public void responseError(TcpReqVO req, Integer code, String msg) {
responseError(req,code, msg, null);
}
public void responseError(TcpReqVO req, Integer code, String msg, Object data) {
TcpRespVO vo = TcpRespVO.response(req, code, msg, data);
respChannel.resp(vo);
cache.put(req.getUuid(), vo);
}
public void error( String msg) {
error( Resp.ERROR, msg);
}
public void error( Integer code, String msg) {
TcpRespVO vo = TcpRespVO.response(code, msg, null, null, null);
respChannel.resp(vo);
}
public boolean isRepectResp(TcpReqVO req) {
TcpRespVO respVO = cache.getIfPresent(req.getUuid());
//以前已经有响应的直接返回
if (respVO != null) respChannel.resp(respVO);
return respVO != null;
}
}
| 25.944444 | 84 | 0.656103 |
ea5213d418391c1dc17d17811e1588364c9a359e | 1,457 |
package br.com.correios.webservice.rastro;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
/**
* <p>Classe Java de RastroJsonResponse complex type.
*
* <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe.
*
* <pre>
* <complexType name="RastroJsonResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="return" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RastroJsonResponse", propOrder = {
"_return"
})
public class RastroJsonResponse {
@XmlElement(name = "return")
protected String _return;
/**
* Obtém o valor da propriedade return.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReturn() {
return _return;
}
/**
* Define o valor da propriedade return.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReturn(String value) {
this._return = value;
}
}
| 23.126984 | 100 | 0.625257 |
114115877cbd7f3a37084890e47c8cca6dbca604 | 3,252 |
package mage.cards.c;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.TriggeredAbilityImpl;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.counter.AddCountersTargetEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.counters.CounterType;
import mage.game.Game;
import mage.game.events.DamagedPlayerEvent;
import mage.game.events.GameEvent;
import mage.game.events.GameEvent.EventType;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.TargetPlayer;
import mage.target.targetpointer.FixedTarget;
/**
*
* @author BetaSteward
*/
public final class CurseOfStalkedPrey extends CardImpl {
public CurseOfStalkedPrey(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{1}{R}");
this.subtype.add(SubType.AURA, SubType.CURSE);
// Enchant player
TargetPlayer target = new TargetPlayer();
this.getSpellAbility().addTarget(target);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.AddAbility));
Ability ability = new EnchantAbility(target.getTargetName());
this.addAbility(ability);
// Whenever a creature deals combat damage to enchanted player, put a +1/+1 counter on that creature.
this.addAbility(new CurseOfStalkedPreyTriggeredAbility());
}
private CurseOfStalkedPrey(final CurseOfStalkedPrey card) {
super(card);
}
@Override
public CurseOfStalkedPrey copy() {
return new CurseOfStalkedPrey(this);
}
}
class CurseOfStalkedPreyTriggeredAbility extends TriggeredAbilityImpl {
public CurseOfStalkedPreyTriggeredAbility() {
super(Zone.BATTLEFIELD, new AddCountersTargetEffect(CounterType.P1P1.createInstance()));
}
public CurseOfStalkedPreyTriggeredAbility(final CurseOfStalkedPreyTriggeredAbility ability) {
super(ability);
}
@Override
public CurseOfStalkedPreyTriggeredAbility copy() {
return new CurseOfStalkedPreyTriggeredAbility(this);
}
@Override
public boolean checkEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.DAMAGED_PLAYER;
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
if (((DamagedPlayerEvent) event).isCombatDamage()) {
Permanent enchantment = game.getPermanent(this.sourceId);
if (enchantment != null && enchantment.getAttachedTo() != null) {
Player player = game.getPlayer(enchantment.getAttachedTo());
if (player != null && event.getTargetId().equals(player.getId())) {
getEffects().get(0).setTargetPointer(new FixedTarget(event.getSourceId()));
return true;
}
}
}
return false;
}
@Override
public String getRule() {
return "Whenever a creature deals combat damage to enchanted player, put a +1/+1 counter on that creature";
}
}
| 32.52 | 115 | 0.708795 |
9f24dd72f8c2a7ba042a996ccf827ebdcba024df | 1,539 | package im.actor.core.api;
/*
* Generated by the Actor API Scheme generator. DO NOT EDIT!
*/
import im.actor.runtime.bser.*;
import im.actor.runtime.collections.*;
import static im.actor.runtime.bser.Utils.*;
import im.actor.core.network.parser.*;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
public class ApiPeer extends BserObject {
private ApiPeerType type;
private int id;
public ApiPeer(@NotNull ApiPeerType type, int id) {
this.type = type;
this.id = id;
}
public ApiPeer() {
}
@NotNull
public ApiPeerType getType() {
return this.type;
}
public int getId() {
return this.id;
}
@Override
public void parse(BserValues values) throws IOException {
this.type = ApiPeerType.parse(values.getInt(1));
this.id = values.getInt(2);
}
@Override
public void serialize(BserWriter writer) throws IOException {
if (this.type == null) {
throw new IOException();
}
writer.writeInt(1, this.type.getValue());
writer.writeInt(2, this.id);
}
@Override
public String toString() {
String res = "struct Peer{";
res += "type=" + this.type;
res += ", id=" + this.id;
res += "}";
return res;
}
}
| 23.676923 | 66 | 0.60104 |
3557df046088b1f01a2410849b486d2110deb840 | 737 | package binarysearch;
import java.util.ArrayList;
import java.util.List;
public class RepeatedDeletion {
public String solve(String s) {
List<Character> stack = new ArrayList<>();
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
if (!stack.isEmpty() && stack.get(stack.size() - 1) == c) {
stack.remove(stack.size() - 1);
++i;
while (i < s.length() && s.charAt(i) == c) i++;
} else {
stack.add(c);
i++;
}
}
StringBuilder sb = new StringBuilder();
for (char c : stack) sb.append(c);
return sb.toString();
}
}
| 27.296296 | 72 | 0.451832 |
905f70b4cd78648e4eda9a302055dff5fcb82d28 | 5,485 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.gradle.addon.internal.tasks;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.regex.Pattern;
import org.gradle.api.DefaultTask;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskAction;
public abstract class UpdateChangelogNextDevIter extends DefaultTask {
private static final String CURRENT_VERSION_TOKEN = "@CURRENT_VERSION@";
private static final String UNRELEASED_SECTION = "## Unreleased";
private static final String UNRELEASED_SECTION_LINK = "## [Unreleased]";
private static final Pattern VERSION_SECTION_PATTERN = Pattern.compile("^## \\[?.+]?.*");
private static final Pattern VERSION_LINK_PATTERN = Pattern.compile("^\\[.+]:");
private final Property<String> currentVersionToken;
private final Property<String> unreleasedLink;
public UpdateChangelogNextDevIter() {
ObjectFactory objects = getProject().getObjects();
this.currentVersionToken = objects.property(String.class).value(CURRENT_VERSION_TOKEN);
this.unreleasedLink = objects.property(String.class);
}
@Input
public abstract Property<String> getCurrentVersion();
@Input
public Property<String> getCurrentVersionToken() {
return currentVersionToken;
}
@Input
@Optional
public Property<String> getUnreleasedLink() {
return unreleasedLink;
}
@InputFile
@PathSensitive(PathSensitivity.NONE)
public abstract RegularFileProperty getChangelog();
@TaskAction
public void prepare() throws IOException {
Path updatedChangelog = updateChangelog();
Files.copy(
updatedChangelog,
getChangelog().getAsFile().get().toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
private Path updateChangelog() throws IOException {
Path changelogPath = getChangelog().getAsFile().get().toPath();
Path updatedChangelog =
getTemporaryDir().toPath().resolve("updated-" + changelogPath.getFileName());
boolean insertUnreleased = true;
boolean insertUnreleasedLink = unreleasedLink.isPresent();
try (BufferedReader reader = Files.newBufferedReader(changelogPath);
BufferedWriter writer = Files.newBufferedWriter(updatedChangelog)) {
boolean lastLineEmpty = false;
String line;
while ((line = reader.readLine()) != null) {
if (insertUnreleased) {
if (line.startsWith(UNRELEASED_SECTION)
|| line.startsWith(UNRELEASED_SECTION_LINK)) {
throw new InvalidUserDataException(
"The changelog already contains the unreleased section.");
}
if (VERSION_SECTION_PATTERN.matcher(line).find()) {
writer.write(
insertUnreleasedLink
? UNRELEASED_SECTION_LINK
: UNRELEASED_SECTION);
writer.write("\n\n\n");
insertUnreleased = false;
}
}
if (insertUnreleasedLink && VERSION_LINK_PATTERN.matcher(line).find()) {
writeUnreleaseLink(writer);
insertUnreleasedLink = false;
}
writer.write(line);
writer.write("\n");
lastLineEmpty = line.isEmpty();
}
if (insertUnreleasedLink) {
if (!lastLineEmpty) {
writer.write("\n");
}
writeUnreleaseLink(writer);
}
}
if (insertUnreleased) {
throw new InvalidUserDataException(
"Failed to insert the unreleased section, no version section found.");
}
return updatedChangelog;
}
private void writeUnreleaseLink(Writer writer) throws IOException {
String link =
unreleasedLink.get().replace(currentVersionToken.get(), getCurrentVersion().get());
writer.write("[Unreleased]: " + link + "\n");
}
}
| 36.812081 | 99 | 0.63701 |
c2c1148d1a1e742b8b9b92dcb386eec30a12f073 | 4,156 | package com.franklin.sample.bankbase.atm.api;
import com.franklin.sample.bankbase.atm.Application;
import com.franklin.sample.bankbase.atm.model.ATM;
import com.franklin.sample.bankbase.atm.repository.LocationRepository;
import com.franklin.sample.bankbase.atm.service.ATMInfo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.ws.rs.core.HttpHeaders;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@AutoConfigureWireMock(port = 7777)
@TestPropertySource(properties = {"atm-locator.apiAddress=http://localhost:7777/api/locator/atms/"})
@Transactional
public class LocatorApiTest {
@Autowired
private TestRestTemplate restTemplate;
@Before
public void setUp() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(ImmutableList.of(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
restTemplate.getRestTemplate().setMessageConverters(Arrays.asList(converter, new FormHttpMessageConverter()));
restTemplate.getRestTemplate().getInterceptors().add(new BasicAuthorizationInterceptor("api", "api"));
stubFor(get(urlEqualTo("/api/locator/atms/"))
.willReturn(aResponse().withHeader(HttpHeaders.ACCEPT, javax.ws.rs.core.MediaType.APPLICATION_JSON)
.withBodyFile("service/Schiphol_ATM_Locations.txt")));
}
@Test
public void testListAtmInCity_withAuthorizedUser() throws Exception {
ResponseEntity<List<ATM>> rateResponse = restTemplate.exchange("/api/cities/Schiphol",
HttpMethod.GET, null,
new ParameterizedTypeReference<List<ATM>>() {
});
List<ATM> atmList = rateResponse.getBody();
Set<String> cities = atmList.stream().map(ATM::getAddressCity).collect(Collectors.toSet());
assertThat(cities.size(), is(1));
assertThat(Lists.newArrayList(cities).get(0), is("Schiphol"));
}
@Test
public void testCreateAndListAtmInCity_withAuthorizedUser_andWithDuplicate() throws Exception {
ATMInfo atmInfo = new ATMInfo("Aankomstpassage", "1", "1118 AX", "MyCity", "52.307138", "4.760019", 0, "ING");
HttpEntity<List<ATMInfo>> request = new HttpEntity<>(ImmutableList.of(atmInfo, atmInfo));
ResponseEntity<List<ATMInfo>> rateResponse = restTemplate.exchange("/api/cities",
HttpMethod.POST, request, new ParameterizedTypeReference<List<ATMInfo>>() {
});
List<ATMInfo> atmList = rateResponse.getBody();
assertThat(atmList, everyItem(isIn(ImmutableList.of(atmInfo, atmInfo).stream().distinct().collect(Collectors.toList()))));
}
}
| 47.770115 | 126 | 0.790664 |
c8ccfc5323f18d42b59b81d2d4aa86a3c226e085 | 195 | /**
* 单例模式
*
* 定义:
* --确保一个类只有一个实例,而且自行实例化,并向整个系统提供这个实例
* --Ensure a class has only one instance, and provide a global point of access to it
*/
package com.cowthan.pattern1.singleton; | 24.375 | 86 | 0.687179 |
1f57eb5e73cc6ce9f1d29c4eedf95e139212275c | 9,315 | package com.chutneytesting.task.kafka;
import static com.chutneytesting.task.spi.TaskExecutionResult.Status.Failure;
import static com.chutneytesting.task.spi.TaskExecutionResult.Status.Success;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import com.chutneytesting.task.TestLogger;
import com.chutneytesting.task.TestTarget;
import com.chutneytesting.task.spi.Task;
import com.chutneytesting.task.spi.TaskExecutionResult;
import com.chutneytesting.task.spi.injectable.Target;
import com.google.common.collect.ImmutableList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.internals.RecordHeader;
import org.apache.kafka.common.header.internals.RecordHeaders;
import org.apache.kafka.common.record.TimestampType;
import org.junit.Test;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.listener.MessageListener;
import org.springframework.test.util.ReflectionTestUtils;
import wiremock.com.google.common.collect.ImmutableMap;
public class KafkaBasicConsumeTaskTest {
private static final String TOPIC = "topic";
public static final String GROUP = "mygroup";
private static final long TIMESTAMP = 42L;
private static final TimestampType TIMESTAMP_TYPE = TimestampType.CREATE_TIME;
private static final long FIRST_OFFSET = 0L;
private static final int PARTITION = 0;
private Target getKafkaTarget() {
return TestTarget.TestTargetBuilder.builder()
.withTargetId("kafka")
.withUrl("tcp://127.0.0.1:5555")
.build();
}
@Test
public void basic_consume_task_should_success() throws Exception {
//given
TestLogger logger = new TestLogger();
Task task = new KafkaBasicConsumeTask(getKafkaTarget(), TOPIC, GROUP, Collections.emptyMap(), 1, null, "10 sec", logger);
ConsumerFactory<String, String> cf = mock(ConsumerFactory.class);
Consumer<String, String> consumer = mock(Consumer.class);
given(cf.createConsumer(any(), any(), any(), any())).willReturn(consumer);
ContainerProperties containerProperties = new ContainerProperties(TOPIC);
containerProperties.setGroupId(GROUP);
containerProperties.setMessageListener(ReflectionTestUtils.invokeMethod(task, "createMessageListener"));
ConcurrentMessageListenerContainer<String, String> messageListenerContainer = new ConcurrentMessageListenerContainer<>(cf, containerProperties);
ReflectionTestUtils.setField(task, "messageListenerContainer", messageListenerContainer);
MessageListener<String, String> listener = (MessageListener<String, String>) messageListenerContainer.getContainerProperties().getMessageListener();
RecordHeaders recordHeaders = getHeaders();
ConsumerRecord<String, String> consumerRecord = new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET, TIMESTAMP, TIMESTAMP_TYPE, 0L, 0, 0, "KEY", "{\"value\": \"test message\", \"id\": \"1111\" }", recordHeaders);
listener.onMessage(consumerRecord);
//when
TaskExecutionResult taskExecutionResult = task.execute();
//Then
assertThat(taskExecutionResult.status).isEqualTo(Success);
assertThat(taskExecutionResult.outputs).hasSize(3);
final List<Map<String, Object>> body = (List<Map<String, Object>>) taskExecutionResult.outputs.get("body");
final List<Map<String, Object>> payloads = (List<Map<String, Object>>) taskExecutionResult.outputs.get("payloads");
final List<Map<String, Object>> headers = (List<Map<String, Object>>) taskExecutionResult.outputs.get("headers");
final Map<String, Object> message = body.get(0);
final Map<String, Object> payload1 = (Map<String, Object>) message.get("payload");
final Map<String, Object> headers1 = (Map<String, Object>) message.get("headers");
assertThat(body.size()).isEqualTo(1);
assertThat(payload1.get("value")).isEqualTo("test message");
assertThat(payload1.get("id")).isEqualTo("1111");
assertThat(headers1.get("X-Custom-HeaderKey")).isEqualTo("X-Custom-HeaderValue");
assertThat(headers1).containsAllEntriesOf(ImmutableMap.of("X-Custom-HeaderKey", "X-Custom-HeaderValue", "header1", "value1"));
assertThat(payload1).isEqualTo(payloads.get(0));
assertThat(headers1).isEqualTo(headers.get(0));
assertThat(logger.errors).isEmpty();
}
private RecordHeaders getHeaders() {
List<Header> headersList = ImmutableList.of(new RecordHeader("X-Custom-HeaderKey", "X-Custom-HeaderValue".getBytes()), new RecordHeader("header1", "value1".getBytes()));
return new RecordHeaders(headersList);
}
@Test
public void basic_consume_task_should_success_with_selector() throws Exception {
//given
TestLogger logger = new TestLogger();
Task task = new KafkaBasicConsumeTask(getKafkaTarget(), TOPIC, GROUP, Collections.emptyMap(), 1, "$..[?($.headers.header1=='value1' && $.payload.id==\"1122\")]", "10 sec", logger);
ConsumerFactory<String, String> cf = mock(ConsumerFactory.class);
Consumer<String, String> consumer = mock(Consumer.class);
given(cf.createConsumer(any(), any(), any(), any())).willReturn(consumer);
ContainerProperties containerProperties = new ContainerProperties(TOPIC);
containerProperties.setGroupId(GROUP);
containerProperties.setMessageListener(ReflectionTestUtils.invokeMethod(task, "createMessageListener"));
ConcurrentMessageListenerContainer<String, String> messageListenerContainer = new ConcurrentMessageListenerContainer<>(cf, containerProperties);
ReflectionTestUtils.setField(task, "messageListenerContainer", messageListenerContainer);
MessageListener<String, String> listener = (MessageListener<String, String>) messageListenerContainer.getContainerProperties().getMessageListener();
RecordHeaders recordHeaders = getHeaders();
ConsumerRecord<String, String> consumerRecord1 = new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET, TIMESTAMP, TIMESTAMP_TYPE, 0L, 0, 0, "KEY1", "{\"value\": \"test message1\", \"id\": \"1111\" }", recordHeaders);
ConsumerRecord<String, String> consumerRecord2 = new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET + 1, TIMESTAMP, TIMESTAMP_TYPE, 0L, 0, 0, "KEY2", "{\"value\": \"test message2\", \"id\": \"1122\" }", recordHeaders);
ConsumerRecord<String, String> consumerRecord3 = new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET + 2, TIMESTAMP, TIMESTAMP_TYPE, 0L, 0, 0, "KEY2", "{\"value\": \"test message3\", \"id\": \"1133\" }", recordHeaders);
listener.onMessage(consumerRecord1);
listener.onMessage(consumerRecord2);
listener.onMessage(consumerRecord3);
//when
TaskExecutionResult taskExecutionResult = task.execute();
//Then
assertThat(taskExecutionResult.status).isEqualTo(Success);
final List<Map<String, Object>> body = (List<Map<String, Object>>) taskExecutionResult.outputs.get("body");
final Map<String, Object> message = body.get(0);
final Map<String, Object> payload1 = (Map<String, Object>) message.get("payload");
final Map<String, Object> headers1 = (Map<String, Object>) message.get("headers");
assertThat(body.size()).isEqualTo(1);
assertThat(payload1.get("value")).isEqualTo("test message2");
assertThat(payload1.get("id")).isEqualTo("1122");
assertThat(headers1.get("X-Custom-HeaderKey")).isEqualTo("X-Custom-HeaderValue");
assertThat(logger.errors).isEmpty();
}
@Test
public void basic_consume_task_should_failed_when_timeout() throws Exception {
//given
TestLogger logger = new TestLogger();
Task task = new KafkaBasicConsumeTask(getKafkaTarget(), TOPIC, "mygroup", Collections.emptyMap(), 1, null, "10 sec", logger);
ConsumerFactory<String, String> cf = mock(ConsumerFactory.class);
Consumer<String, String> consumer = mock(Consumer.class);
given(cf.createConsumer(any(), any(), any(), any())).willReturn(consumer);
ContainerProperties containerProperties = new ContainerProperties(TOPIC);
containerProperties.setGroupId(GROUP);
containerProperties.setMessageListener(ReflectionTestUtils.invokeMethod(task, "createMessageListener"));
ConcurrentMessageListenerContainer<String, String> messageListenerContainer = new ConcurrentMessageListenerContainer<>(cf, containerProperties);
ReflectionTestUtils.setField(task, "messageListenerContainer", messageListenerContainer);
//when
TaskExecutionResult taskExecutionResult = task.execute();
//Then
assertThat(taskExecutionResult.status).isEqualTo(Failure);
assertThat(logger.errors).isNotEmpty();
}
}
| 58.955696 | 227 | 0.727644 |
97cd3471d138ff2bdd906f21e8c959eb61cd1253 | 592 | package com.dmall.search.service.impl.handler.mq;
/**
* 订单的步骤
*/
public class OrderStep {
private long orderId;
private String desc;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "OrderStep{" +
"orderId=" + orderId +
", desc='" + desc + '\'' +
'}';
}
} | 17.939394 | 49 | 0.533784 |
9baecadce1eadfafab8e8a1500355583bec4bb8f | 744 | package de.sandstorm.junit.examples.customValidators;
import java.io.UnsupportedEncodingException;
/**
* test entity containing a property which cannot be validated with {@link java.util.Objects#equals(Object, Object)}
*/
public class Utf8String {
private static final String Encoding = "UTF-8";
private final String value;
/**
* constructor
*
* @param value string value
*/
public Utf8String(String value) {
this.value = value;
}
/**
* @return exact clone of this instance
*/
public Utf8String duplicate() {
return new Utf8String(value);
}
public byte[] getBytes() throws UnsupportedEncodingException {
return value.getBytes(Encoding);
}
}
| 21.882353 | 116 | 0.658602 |
12336bc9951e4490745905701a65a31107ef45db | 5,643 | package com.simplelist;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.simplelist.Objects.Item;
import java.sql.Timestamp;
import java.util.ArrayList;
/**
* Created by Yurii on 01.07.2017.
*/
public class ListDataBaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "list.sqlite";
private static final int VERSION = 5;
private static final String TABLE_LIST = "list";
private static final String COLUMN_LIST_ID = "_id";
private static final String COLUMN_LIST_ITEM_NAME = "item_name";
private static final String COLUMN_LIST_ITEM_DESCRIPTION = "item_description";
private static final String COLUMN_LIST_ITEM_DATE = "item_date";
private static final String COLUMN_LIST_ITEM_IMAGE = "item_image";
private static final String COLUMN_LIST_ITEM_COLOR = "item_color";
private static final String SORT_BY_ASC = COLUMN_LIST_ITEM_NAME + " " + "ASC";
private static final String SORT_BY_DESC = COLUMN_LIST_ITEM_NAME + " " + "DESC";
private static final String SORT_BY_DATE_ASC = COLUMN_LIST_ITEM_DATE + " " + "TIMESTAMP ASC";
private static final String SORT_BY_DATE_DESC = COLUMN_LIST_ITEM_DATE + " " + "TIMESTAMP DESC";
public ListDataBaseHelper(Context context){
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE list " +
"(_id, item_name, item_description, item_date DATETIME, item_image, item_color integer default 3);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
if(i != 5){
//db.execSQL("ALTER TABLE " + TABLE_LIST + " ADD COLUMN " + COLUMN_LIST_ITEM_COLOR);
//db.execSQL("UPDATE " + TABLE_LIST + " SET " + COLUMN_LIST_ITEM_COLOR + " = '4';");
//onCreate(db);
}
}
public void insertItem(Item item) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_LIST_ITEM_NAME, item.getTitle());
cv.put(COLUMN_LIST_ID, item.getUuid());
cv.put(COLUMN_LIST_ITEM_DESCRIPTION, item.getDescription());
cv.put(COLUMN_LIST_ITEM_IMAGE, item.getImage());
cv.put(COLUMN_LIST_ITEM_DATE, item.getTimestamp().toString());
cv.put(COLUMN_LIST_ITEM_COLOR, item.getColor());
getWritableDatabase().insert(TABLE_LIST, null, cv);
}
public void insertItems(ArrayList<Item> items){
for(int i = 0; i < items.size(); i++){
ContentValues cv = new ContentValues();
cv.put(COLUMN_LIST_ITEM_NAME, items.get(i).getTitle());
cv.put(COLUMN_LIST_ID, items.get(i).getUuid());
cv.put(COLUMN_LIST_ITEM_DESCRIPTION, items.get(i).getDescription());
cv.put(COLUMN_LIST_ITEM_IMAGE, items.get(i).getImage());
cv.put(COLUMN_LIST_ITEM_DATE, items.get(i).getTimestamp().toString());
cv.put(COLUMN_LIST_ITEM_COLOR, items.get(i).getColor());
getWritableDatabase().insert(TABLE_LIST, null, cv);
}
}
public void updateItem(Item item) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_LIST_ITEM_NAME, item.getTitle());
cv.put(COLUMN_LIST_ITEM_DESCRIPTION, item.getDescription());
cv.put(COLUMN_LIST_ITEM_IMAGE, item.getImage());
cv.put(COLUMN_LIST_ITEM_COLOR, item.getColor());
//getWritableDatabase().update(TABLE_LIST, cv, "_id" + "=" + item.getId(), null);
getWritableDatabase().update(TABLE_LIST, cv, "_id" + "=?", new String[] {item.getUuid()});
}
public void deleteItem(Item item) {
//getWritableDatabase().delete(TABLE_LIST, "_id" + "=" + item.getId(), null);
getWritableDatabase().delete(TABLE_LIST, "_id" + "=?", new String[] {item.getUuid()});
}
public void deleteAllItems(){
getWritableDatabase().delete(TABLE_LIST, null, null);
}
public ArrayList<Item> queryItems(){
ArrayList<Item> list = new ArrayList<Item>();
Cursor cursor = getReadableDatabase().query(TABLE_LIST, null,
null, null, null, null, null);
if (cursor.moveToFirst()){
do{
Item item = new Item(cursor.getString(0), cursor.getString(1), cursor.getString(2), Timestamp.valueOf(cursor.getString(3)), cursor.getString(4), cursor.getInt(5));
list.add(item);
} while(cursor.moveToNext());
}
return list;
}
public ArrayList<Item> queryItems(String Sort){
ArrayList<Item> list = new ArrayList<Item>();
Cursor cursor = getReadableDatabase().query(TABLE_LIST, null,
null, null, null, null, Sort);
if (cursor.moveToFirst()){
do{
Item item = new Item(cursor.getString(0), cursor.getString(1), cursor.getString(2), Timestamp.valueOf(cursor.getString(3)), cursor.getString(4), cursor.getInt(5));
list.add(item);
} while(cursor.moveToNext());
}
return list;
}
/*public Item queryItem(int id) {
id++; //autoincrement starts from 1
Cursor cursor = getReadableDatabase().query(TABLE_LIST, new String[] {"_id", "item_name"}, "_id" + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor.moveToFirst()){
Item item = new Item(Integer.parseInt(cursor.getString(0)), cursor.getString(1));
return item;
}
return null;
}*/
}
| 42.11194 | 179 | 0.645756 |
cd64c21e7493d675ae3147bbb42fdfff89509839 | 4,455 | package com.stripe.android;
import android.app.Activity;
import android.content.Intent;
import com.stripe.android.model.PaymentIntentFixtures;
import com.stripe.android.view.AuthActivityStarter;
import com.stripe.android.view.StripeIntentResultExtras;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
@RunWith(RobolectricTestRunner.class)
public class Stripe3ds2CompletionStarterTest {
private Stripe3ds2CompletionStarter mStarter;
@Mock private Activity mActivity;
@Captor private ArgumentCaptor<Intent> mIntentArgumentCaptor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mStarter = new Stripe3ds2CompletionStarter(
AuthActivityStarter.Host.create(mActivity), 500);
}
@Test
public void start_withSuccessfulCompletion_shouldAddClientSecretAndOutcomeToIntent() {
mStarter.start(new Stripe3ds2CompletionStarter.StartData(
PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2,
Stripe3ds2CompletionStarter.ChallengeFlowOutcome.COMPLETE_SUCCESSFUL));
verify(mActivity).startActivityForResult(mIntentArgumentCaptor.capture(), eq(500));
final Intent intent = mIntentArgumentCaptor.getValue();
assertEquals(PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2.getClientSecret(),
intent.getStringExtra(StripeIntentResultExtras.CLIENT_SECRET));
assertEquals(StripeIntentResult.Outcome.SUCCEEDED,
intent.getIntExtra(StripeIntentResultExtras.FLOW_OUTCOME,
StripeIntentResult.Outcome.UNKNOWN));
}
@Test
public void start_withUnsuccessfulCompletion_shouldAddClientSecretAndOutcomeToIntent() {
mStarter.start(new Stripe3ds2CompletionStarter.StartData(
PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2,
Stripe3ds2CompletionStarter.ChallengeFlowOutcome.COMPLETE_UNSUCCESSFUL));
verify(mActivity).startActivityForResult(mIntentArgumentCaptor.capture(), eq(500));
final Intent intent = mIntentArgumentCaptor.getValue();
assertEquals(PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2.getClientSecret(),
intent.getStringExtra(StripeIntentResultExtras.CLIENT_SECRET));
assertEquals(StripeIntentResult.Outcome.FAILED,
intent.getIntExtra(StripeIntentResultExtras.FLOW_OUTCOME,
StripeIntentResult.Outcome.UNKNOWN));
}
@Test
public void start_withTimeout_shouldAddClientSecretAndOutcomeToIntent() {
mStarter.start(new Stripe3ds2CompletionStarter.StartData(
PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2,
Stripe3ds2CompletionStarter.ChallengeFlowOutcome.TIMEOUT));
verify(mActivity).startActivityForResult(mIntentArgumentCaptor.capture(), eq(500));
final Intent intent = mIntentArgumentCaptor.getValue();
assertEquals(PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2.getClientSecret(),
intent.getStringExtra(StripeIntentResultExtras.CLIENT_SECRET));
assertEquals(StripeIntentResult.Outcome.TIMEDOUT,
intent.getIntExtra(StripeIntentResultExtras.FLOW_OUTCOME,
StripeIntentResult.Outcome.UNKNOWN));
}
@Test
public void start_withProtocolError_shouldAddClientSecretAndOutcomeToIntent() {
mStarter.start(new Stripe3ds2CompletionStarter.StartData(
PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2,
Stripe3ds2CompletionStarter.ChallengeFlowOutcome.PROTOCOL_ERROR));
verify(mActivity).startActivityForResult(mIntentArgumentCaptor.capture(), eq(500));
final Intent intent = mIntentArgumentCaptor.getValue();
assertEquals(PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2.getClientSecret(),
intent.getStringExtra(StripeIntentResultExtras.CLIENT_SECRET));
assertEquals(StripeIntentResult.Outcome.FAILED,
intent.getIntExtra(StripeIntentResultExtras.FLOW_OUTCOME,
StripeIntentResult.Outcome.UNKNOWN));
}
}
| 46.894737 | 92 | 0.751291 |
1728bfb98c1338bc1f4f8016a706a7373f79daa3 | 3,669 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.base.test.params;
import static org.chromium.base.test.params.ParameterAnnotations.MethodParameter;
import static org.chromium.base.test.params.ParameterAnnotations.UseMethodParameter;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.runner.RunWith;
import org.chromium.base.test.params.ParameterAnnotations.ClassParameter;
import org.chromium.base.test.params.ParameterAnnotations.UseMethodParameterAfter;
import org.chromium.base.test.params.ParameterAnnotations.UseMethodParameterBefore;
import org.chromium.base.test.params.ParameterAnnotations.UseParameterProvider;
import org.chromium.base.test.params.ParameterAnnotations.UseRunnerDelegate;
import java.util.Arrays;
import java.util.List;
/**
* Example test that uses ParamRunner
*/
@RunWith(ParameterizedRunner.class)
@UseRunnerDelegate(BlockJUnit4RunnerDelegate.class)
public class ExampleParameterizedTest {
@ClassParameter
private static List<ParameterSet> sClassParams =
Arrays.asList(new ParameterSet().value("hello", "world").name("HelloWorld"),
new ParameterSet().value("Xxxx", "Yyyy").name("XxxxYyyy"),
new ParameterSet().value("aa", "yy").name("AaYy"));
@MethodParameter("A")
private static List<ParameterSet> sMethodParamA =
Arrays.asList(new ParameterSet().value(1, 2).name("OneTwo"),
new ParameterSet().value(2, 3).name("TwoThree"),
new ParameterSet().value(3, 4).name("ThreeFour"));
@MethodParameter("B")
private static List<ParameterSet> sMethodParamB =
Arrays.asList(new ParameterSet().value("a", "b").name("Ab"),
new ParameterSet().value("b", "c").name("Bc"),
new ParameterSet().value("c", "d").name("Cd"),
new ParameterSet().value("d", "e").name("De"));
public static class MethodParamsA implements ParameterProvider {
@Override
public List<ParameterSet> getParameters() {
return sMethodParamA;
}
}
private String mStringA;
private String mStringB;
public ExampleParameterizedTest(String a, String b) {
mStringA = a;
mStringB = b;
}
@Test
public void testSimple() {
Assert.assertEquals(
"A and B string length aren't equal", mStringA.length(), mStringB.length());
}
@Rule
public MethodRule mMethodParamAnnotationProcessor = new MethodParamAnnotationRule();
private Integer mSum;
@UseMethodParameterBefore("A")
public void setupWithOnlyA(int intA, int intB) {
mSum = intA + intB;
}
@Test
@UseMethodParameter("A")
public void testWithOnlyA(int intA, int intB) {
Assert.assertEquals(intA + 1, intB);
Assert.assertEquals(mSum, Integer.valueOf(intA + intB));
mSum = null;
}
@Test
@UseParameterProvider(MethodParamsA.class)
public void testWithOnlyAFromGenerator(int intA, int intB) {
Assert.assertEquals(intA + 1, intB);
}
private String mConcatenation;
@Test
@UseMethodParameter("B")
public void testWithOnlyB(String a, String b) {
Assert.assertTrue(!a.equals(b));
mConcatenation = a + b;
}
@UseMethodParameterAfter("B")
public void teardownWithOnlyB(String a, String b) {
Assert.assertEquals(mConcatenation, a + b);
mConcatenation = null;
}
}
| 33.354545 | 92 | 0.675933 |
7fe39e07bcc1aaf2c69cb5bf6807fa24514cc484 | 2,056 | package org.test;
import com.alibaba.fastjson.JSON;
import org.h819.commons.MyStringUtils;
import org.h819.web.spring.jdbc.Order;
import java.io.IOException;
import java.util.List;
/**
* Description : TODO()
* User: h819
* Date: 2017/8/14
* Time: 11:05
* To change this template use File | Settings | File Templates.
*/
public class Test4 {
public static void main(String[] args) throws IOException {
Test4 t = new Test4();
Order order1 = new Order("A", Order.Direction.DESC);
Order order2 = new Order("b", Order.Direction.ASC);
Order order3 = new Order("c", Order.Direction.ASC);
Order[] orders = {order1, order2, order3};
//t.testOrder(orders);
t.testFastJson(orders);
}
private void testOrder(Order... order) {
// return " order by " + Arrays.toString(sortParameters).replace("[", "").replace("]", "") + " " + sort;
// System.out.println(Arrays.toString(order));
StringBuilder builder = new StringBuilder(order.length);
builder.append(" order by ");
for (Order o : order)
builder.append(o.getProperty()).append(" ").append(o.getDirection()).append(", ");
int last = builder.lastIndexOf(",");
builder.deleteCharAt(last);
builder.append(" ");
System.out.println(builder.toString());
}
private void testFastJson(Order order) {
String str = JSON.toJSONString(order);
System.out.println(str);
System.out.println(MyStringUtils.center(80, "*"));
Order order1 = JSON.parseObject(str, Order.class);
System.out.println(order1.getProperty() + "," + order1.getDirection());
}
private void testFastJson(Order[] order) {
String str = JSON.toJSONString(order);
System.out.println(str);
System.out.println(MyStringUtils.center(80, "*"));
List<Order> order1 = JSON.parseArray(str, Order.class);
for (Order or : order1)
System.out.println(or.getProperty() + "," + or.getDirection());
}
}
| 29.797101 | 107 | 0.618677 |
e84b89ec9bea4ab8ce49fe45a4cabdcbbae98269 | 595 | package com.pj109.xkorey.share.di;
import javax.inject.Scope;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The FragmentScoped custom scoping annotation specifies that the lifespan of a dependency be
* the same as that of a Fragment. This is used to annotate dependencies that behave like a
* singleton within the lifespan of a Fragment
*/
@Scope
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface FragmentScoped {
}
| 31.315789 | 94 | 0.801681 |
5b9132bb6782e8af3000f56a72b8e4022d7682e6 | 859 | package com.bridgeit.Controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/servlet2")
public class LinkServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer= response.getWriter();
ServletContext context= getServletContext();
String attribute=(String) context.getAttribute("Company");
writer.println("Welcome to "+attribute);
writer.close();
}
}
| 26.030303 | 118 | 0.796275 |
f5ede1a70891536a7dda8d5c3a5fe5c9d93f60a5 | 280 | package ch.uzh.ifi.hase.soprafs22.exceptions;
public class PlayerNotFoundException extends Exception{
private final String token;
public PlayerNotFoundException(String token) {
this.token = token;
}
public String token() {
return token;
}
}
| 20 | 55 | 0.689286 |
d0bd626cb3c21e1a4284585bc669fcfe3e200db1 | 694 | /*
Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive). You may assume that the remove string is length 1 or more. Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".
withoutString("Hello there", "llo") → "He there"
withoutString("Hello there", "e") → "Hllo thr"
withoutString("Hello there", "x") → "Hello there"
@author unobatbayar
*/
public String withoutString(String base, String remove) {
base = base.replace(remove.toUpperCase(), "");
base = base.replace(remove.toLowerCase(), "");
base = base.replace(remove, "");
return base;
}
| 36.526316 | 290 | 0.697406 |
6ac19d47ec487104798d6867446f3180a6693502 | 427 | package ru.stqa.pft.sandbox;
public class Point {
private final double x;
private final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double distance(Point p2) {
double dx = this.x - p2.x; // по формуле x2-x1
double dy = this.y - p2.y; // по формуле y2-y1
return Math.sqrt(dx * dx + dy * dy); // выводим квадратный корень
}
}
| 22.473684 | 74 | 0.571429 |
9929af19c83f00b538a9c8567f408960ee85763f | 2,346 | package ru.stqa.pft.mantis.tests;
import org.openqa.selenium.By;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.lanwen.verbalregex.VerbalExpression;
import ru.stqa.pft.mantis.model.MailMessage;
import ru.stqa.pft.mantis.appmanager.HttpSession;
import ru.stqa.pft.mantis.model.MailMessage;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.List;
import static org.testng.Assert.assertTrue;
public class ChangePasswordTests extends TestBase {
@BeforeMethod
public void startMailServer() {
app.mail().start();
}
// 1. Администратор входит в систему, переходит на страницу управления пользователями, выбирает заданного пользователя
// и нажимает кнопку Reset Password
// 2. Отправляется письмо на адрес пользователя, тесты должны получить это письмо,
// извлечь из него ссылку для смены пароля, пройти по этой ссылке и изменить пароль.
// 3. Затем тесты должны проверить, что пользователь может войти в систему с новым паролем.
@Test
public void testChangePassword() throws IOException, MessagingException {
app.changePasswordHelper().loginN("administrator", "root");
app.changePasswordHelper().selectRandomUser();
String randomUserName = app.changePasswordHelper().getRandomUserName();
String randomUserEmail = app.changePasswordHelper().getRandomUserEmail();
app.changePasswordHelper().resetUserPassword();
List<MailMessage> mailMessages = app.mail().waitForMail(1, 10000);
String confirmationLink = findConfirmationLink(mailMessages, randomUserEmail);
String newPassword = "newPassword";
app.changePasswordHelper().changePassword(confirmationLink, newPassword);
HttpSession session = app.newSession();
assertTrue(session.login(randomUserName, newPassword));
assertTrue(session.isLoggedInAs(randomUserName));
}
private String findConfirmationLink(List<MailMessage> mailMessages, String email) {
MailMessage mailMessage = mailMessages.stream().filter((m) -> m.to.equals(email)).findFirst().get();
VerbalExpression regex = VerbalExpression.regex().find("http://").nonSpace().oneOrMore().build();
return regex.getText(mailMessage.text);
}
@AfterMethod(alwaysRun = true)
public void stopMailServer() {
app.mail().stop();
}
}
| 36.092308 | 120 | 0.769821 |
f4ea96ae8a4ebd5ac2e179bd49293841dcdfd044 | 1,111 | package com.vendomatica.vendroid.Fragment;
/*
This screen appears when the user press the images taken at the form.
*/
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;
import com.vendomatica.vendroid.R;
public class PhotoDialog extends Dialog {
private Context pContext;
ImageView imgPhoto;
public PhotoDialog(Context context) {
super(context, android.R.style.Theme_Black_NoTitleBar);
// TODO Auto-generated constructor stub
pContext = context;
// requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.photo_dialog);
// setTitle("Input Post Information");
imgPhoto = (ImageView)findViewById(R.id.imgPhoto);
this.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
// TODO Auto-generated method stub
}
});
}
public void setImage(String path){
imgPhoto.setImageBitmap(BitmapFactory
.decodeFile(path));
imgPhoto.setVisibility(View.VISIBLE);
}
}
| 25.25 | 69 | 0.768677 |
f55f48c55be8c91c10e07f664b0306360b9c25a4 | 3,603 | package com.cjrequena.sample;
import com.cjrequena.sample.dto.BankAccountDTO;
import com.cjrequena.sample.service.BankAccountCommandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*
* <p></p>
* <p></p>
* @author cjrequena
*/
@SpringBootApplication
@EnableAutoConfiguration
public class MainApplication implements CommandLineRunner {
@Autowired
private BankAccountCommandService bankAccountCommandService;
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Override public void run(String... args) throws Exception {
BankAccountDTO bankAccountDTO = new BankAccountDTO();
// bankAccountDTO.setOwner("John Lennon");
// bankAccountDTO.setBalance(BigDecimal.valueOf(100));
// bankAccountCommandService.createAccount(bankAccountDTO); // Account created with balance 100
// moneyAmountDTO.setAmount(BigDecimal.valueOf(50));
// bankAccountCommandService.creditMoneyToAccount(bankAccountDTO.getAccountId(), moneyAmountDTO); // Credit 50 to the account
// moneyAmountDTO.setAmount(BigDecimal.valueOf(100));
// bankAccountCommandService.debitMoneyFromAccount(bankAccountDTO.getAccountId(), moneyAmountDTO); // Debit 100 to the account
// moneyAmountDTO.setAmount(BigDecimal.valueOf(100));
// bankAccountCommandService.creditMoneyToAccount(bankAccountDTO.getAccountId(), moneyAmountDTO); // Credit 100 to the account
// // John lennon balance should be 150
//
// bankAccountDTO = new BankAccountDTO();
// moneyAmountDTO = new MoneyAmountDTO();
// bankAccountDTO.setOwner("Bill Gates");
// bankAccountDTO.setBalance(BigDecimal.valueOf(250));
// bankAccountCommandService.createAccount(bankAccountDTO); // Account created with balance 250
// moneyAmountDTO.setAmount(BigDecimal.valueOf(50));
// bankAccountCommandService.creditMoneyToAccount(bankAccountDTO.getAccountId(), moneyAmountDTO); // Credit 50 to the account
// moneyAmountDTO.setAmount(BigDecimal.valueOf(100));
// bankAccountCommandService.debitMoneyFromAccount(bankAccountDTO.getAccountId(), moneyAmountDTO); // Debit 100 to the account
// moneyAmountDTO.setAmount(BigDecimal.valueOf(120));
// bankAccountCommandService.creditMoneyToAccount(bankAccountDTO.getAccountId(), moneyAmountDTO); // Credit 120 to the account
// // Bill gates balance should be 320
//
// bankAccountDTO = new BankAccountDTO();
// moneyAmountDTO = new MoneyAmountDTO();
// bankAccountDTO.setOwner("Steve Jobs");
// bankAccountDTO.setBalance(BigDecimal.valueOf(1000000)); // Account created with balance 1000000
// bankAccountCommandService.createAccount(bankAccountDTO);
// moneyAmountDTO.setAmount(BigDecimal.valueOf(369000));
// bankAccountCommandService.creditMoneyToAccount(bankAccountDTO.getAccountId(), moneyAmountDTO); // Credit 3690000 to the account
// moneyAmountDTO.setAmount(BigDecimal.valueOf(69000));
// bankAccountCommandService.debitMoneyFromAccount(bankAccountDTO.getAccountId(), moneyAmountDTO); // Debit 69000 to the account
// moneyAmountDTO.setAmount(BigDecimal.valueOf(69000));
// bankAccountCommandService.creditMoneyToAccount(bankAccountDTO.getAccountId(), moneyAmountDTO); // Credit 69000 to the account
// // Steve jobs balance should be 1369000
this.bankAccountCommandService.printAccountsInfo();
}
}
| 50.746479 | 133 | 0.783236 |
98e08342158011ec46dbe56b4fa39d5581d955a6 | 386 | /**
* The <i>Abstract Factory</i> pattern is used to create a family of
* related products (in contrast, the <i>Factory Method</i> pattern
* creates one type of object). This pattern also defines an
* interface for creating objects, but it lets subclasses decide
* which to instantiate.
*
* @author Mincong Huang
*/
package io.mincong.ocpjp.design_principles.factory.abstract_;
| 35.090909 | 68 | 0.746114 |
baa353bc9c8a9d75cc51d3fe965b2e0f997cecc7 | 152 | package com.wqp.domain;
import org.springframework.stereotype.Component;
@Component
public class C {
public C() {
System.out.println("C.C");
}
}
| 12.666667 | 48 | 0.710526 |
8373bca1a6ce4ced1084271eeaa26142324f7cc3 | 3,306 | /*
* #%L
* BroadleafCommerce Profile
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.profile.core.domain;
import org.broadleafcommerce.common.presentation.AdminPresentation;
import org.broadleafcommerce.common.time.domain.TemporalTimestampListener;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Index;
import org.hibernate.annotations.Parameter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@EntityListeners(value = { TemporalTimestampListener.class })
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_ROLE")
public class RoleImpl implements Role {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "RoleId")
@GenericGenerator(
name="RoleId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="RoleImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.profile.core.domain.RoleImpl")
}
)
@Column(name = "ROLE_ID")
protected Long id;
@Column(name = "ROLE_NAME", nullable = false)
@Index(name="ROLE_NAME_INDEX", columnNames={"ROLE_NAME"})
@AdminPresentation(friendlyName = "rolesTitle",prominent = true)
protected String roleName;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getRoleName() {
return roleName;
}
@Override
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((roleName == null) ? 0 : roleName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!getClass().isAssignableFrom(obj.getClass()))
return false;
RoleImpl other = (RoleImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (roleName == null) {
if (other.roleName != null)
return false;
} else if (!roleName.equals(other.roleName))
return false;
return true;
}
}
| 29 | 102 | 0.666364 |
f15ee59aaa4297e92d070ff392afe57fbb6ea978 | 1,083 | package org.janelia.model.access.dao.mongo.utils;
import com.mongodb.MongoClient;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.janelia.jacs2.cdi.ObjectMapperFactory;
import org.janelia.model.jacs2.domain.enums.FileType;
import org.janelia.model.service.JacsServiceState;
import org.janelia.model.service.ProcessingLocation;
public class RegistryHelper {
public static CodecRegistry createCodecRegistry(ObjectMapperFactory objectMapperFactory) {
return CodecRegistries.fromRegistries(
MongoClient.getDefaultCodecRegistry(),
CodecRegistries.fromCodecs(
new ReferenceCodec(),
new BigIntegerCodec(),
new EnumCodec<>(JacsServiceState.class),
new EnumCodec<>(ProcessingLocation.class),
new EnumCodec<>(FileType.class)
),
CodecRegistries.fromProviders(new JacksonCodecProvider(objectMapperFactory))
);
}
}
| 38.678571 | 94 | 0.680517 |
8470c9f1fb06d6d66f56f72a17025b6f88239070 | 12,664 | package view;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.GridLayout;
import java.awt.Dimension;
import javax.swing.border.TitledBorder;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.FlowLayout;
import java.util.Calendar;
import java.util.Vector;
import model.entity.Paciente;
import model.Database;
import controller.PacienteController;
import view.util.CrudToolBar;
import view.util.FormUtils;
public class FormPaciente extends FormEntidade
{
private JFrame frame;
private JFrame formPai;
private PacienteController controller;
private Database database;
private List<Paciente> pacienteList;
private CrudToolBar crudToolBar;
private JPanel painelPrincipal;
private JPanel subPainel_0;
private JPanel subPainel_1;
private JPanel subPainel_2;
//remover beg
private JTextField txtId;
private JTextField txtNome;
private JTextField txtCPF;
private JComboBox<String> cbDia;
private JComboBox<String> cbMes;
private JComboBox<String> cbAno;
private JRadioButton rbFem;
private JRadioButton rbMasc;
private ButtonGroup bgSexo;
private JLabel titlePrincipal;
private JButton botaoVoltar;
//remover end
public FormPaciente (JFrame form, Database database, String n)
{
formPai = form;
this.controller = new PacienteController(database);
setAppNome(n);
}
public void criarExibirForm()
{
// Criando e configurando a janela do formulario
frame = new JFrame(getAppNome());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
painelPrincipal = new JPanel();
painelPrincipal.setLayout(new GridLayout(4,1));
//title principal
subPainel_0 = new JPanel();
subPainel_0.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
titlePrincipal = new JLabel("Cadastro");
titlePrincipal.setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 18));
gbc.gridwidth = 1;
subPainel_0.add(titlePrincipal, gbc);
painelPrincipal.add(subPainel_0);
//Painel de preenchimento
subPainel_1 = new JPanel();
subPainel_1.setBorder(new TitledBorder(
new LineBorder(Color.BLACK), "Paciente:"));
subPainel_1.setLayout(new GridBagLayout());
//GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(3,3,3,3);
// ID
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
subPainel_1.add(new JLabel("ID:",SwingConstants.RIGHT),gbc);
txtId = new JTextField();
txtId.setEnabled(false);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 1;
subPainel_1.add(txtId,gbc);
// Nome
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
subPainel_1.add(new JLabel("Nome:",SwingConstants.RIGHT),gbc);
txtNome = new JTextField();
// txtNome.setEnabled(false);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 2;
subPainel_1.add(txtNome,gbc);
// CPF
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 1;
subPainel_1.add(new JLabel("CPF:",SwingConstants.RIGHT),gbc);
txtCPF = new JTextField();
// txtCPF.setEnabled(false);
//KeyListener para monitorar e permitir somente a insercao numeros no campo do CPF
txtCPF.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyReleased(java.awt.event.KeyEvent evt) {
try {
long number = Long.parseLong(txtCPF.getText());
} catch (Exception e) {
//Retornar somente os valores numericos inseridos
JOptionPane.showMessageDialog(rootPane, "Apenas números são permitidos!");
txtCPF.setText(txtCPF.getText().replaceAll("[^\\d.]", ""));
}
}
} );
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 2;
subPainel_1.add(txtCPF,gbc);
// Sexo
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
subPainel_1.add(new JLabel("Sexo:",SwingConstants.RIGHT),gbc);
bgSexo = new ButtonGroup();
rbFem = new JRadioButton();
bgSexo.add(rbFem);
rbFem.setSelected(true);
// rbFem.setEnabled(false);
rbFem.setText("Feminino");
gbc.gridx = 1;
gbc.gridy = 3;
gbc.gridwidth = 1;
subPainel_1.add(rbFem,gbc);
rbMasc = new JRadioButton();
bgSexo.add(rbMasc);
// rbMasc.setEnabled(false);
rbMasc.setText("Masculino");
gbc.gridx = 2;
gbc.gridy = 3;
gbc.gridwidth = 1;
subPainel_1.add(rbMasc,gbc);
// Nascimento
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 1;
subPainel_1.add(new JLabel("Data de Nascimento:",SwingConstants.RIGHT),gbc);
cbDia = new JComboBox<>();
// cbDia.setEnabled(false);
cbDia.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }));
gbc.gridx = 1;
gbc.gridy = 4;
gbc.gridwidth = 1;
subPainel_1.add(cbDia,gbc);
cbMes = new JComboBox<>();
// cbMes.setEnabled(false);
cbMes.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" }));
gbc.gridx = 2;
gbc.gridy = 4;
gbc.gridwidth = 1;
subPainel_1.add(cbMes,gbc);
cbAno = new JComboBox<>();
// cbAno.setEnabled(false);
//cbAno.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "2021"}));
//Gerar vetor com os anos a partir de 1900 e seta como padrao o ano atual
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
Vector v=new Vector();
for (int i = year; i >= 1900; i--) {
v.add(Integer.toString(i));
}
cbAno.setModel(new javax.swing.DefaultComboBoxModel(v));
cbAno.setSelectedItem(year);
gbc.gridx = 3;
gbc.gridy = 4;
gbc.gridwidth = 1;
subPainel_1.add(cbAno,gbc);
painelPrincipal.add(subPainel_1);
//add toolbar
crudToolBar = new CrudToolBar(this);
painelPrincipal.add(crudToolBar);
subPainel_2 = new JPanel();
subPainel_2.setLayout(new FlowLayout( FlowLayout.CENTER,1,1));
botaoVoltar = new JButton("Fechar");
subPainel_2.add(botaoVoltar);
botaoVoltar.addActionListener(this);
painelPrincipal.add(subPainel_2);
frame.add(painelPrincipal);
frame.pack();
FormUtils.centerForm(frame);
frame.setVisible(true);
lerEntidades();
exibirEntidade(getNumEntidadeCorrente());
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals(botaoVoltar))
{
buttonVoltar_Click();
}
}
public Paciente getEntidadeCorrente()
{
Paciente paciente = new Paciente();
int id;
if(txtId.getText().isEmpty() == false)
{
id = Integer.parseInt(txtId.getText());
paciente.setId(id);
}
if(txtNome.getText().isEmpty() == false)
{
paciente.setNome(txtNome.getText());
}
if(txtCPF.getText().isEmpty() == false)
{
paciente.setCPF(txtCPF.getText());
}
if(rbFem.isSelected())
paciente.setSexo("Feminino");
else
paciente.setSexo("Masculino");
String dataNasc = cbDia.getSelectedItem() + "/" + cbMes.getSelectedItem() + "/" + cbAno.getSelectedItem();
paciente.setDataNascimento(dataNasc);
return paciente;
}
public void salvarEntidade()
{
Paciente paciente;
paciente = getEntidadeCorrente();
Paciente pacienteCriado = controller.create(paciente);
}
public void alterarEntidade()
{
Paciente paciente = new Paciente();
paciente = getEntidadeCorrente();
controller.update(paciente);
lerEntidades();
exibirEntidade(getNumEntidadeCorrente());
}
public void deletarEntidade()
{
Paciente paciente = new Paciente();
paciente = getEntidadeCorrente();
controller.delete(paciente);
lerEntidades();
exibirEntidade(getNumEntidadeCorrente());
}
public void lerEntidades()
{
pacienteList = controller.readAll();
if(pacienteList.isEmpty())
{
setNumEntidadeCorrente(-1);
}
else
{
setNumEntidadeCorrente(0);
}
}
public void exibirEntidade(int index)
{
Paciente paciente;
if (index == -1)
{
FormUtils.clearTextFields(this,subPainel_1);
}
else
{
paciente = pacienteList.get(index);
txtId.setText(Integer.toString(paciente.getId()));
txtNome.setText(paciente.getNome());
txtCPF.setText(paciente.getCPF());
if(paciente.getSexo().equals("Feminino")){
rbFem.setSelected(true);
//rbMasc.setSelected(false);
} else {
//rbFem.setSelected(false);
rbMasc.setSelected(true);
}
//Separar dia, mes e ano da string DataNascimento do BD
String dataArr[] = paciente.getDataNascimento().split("/");
selectDiaByString(dataArr[0]);
selectMesByString(dataArr[1]);
selectAnoByString(dataArr[2]);
}
}
private void selectDiaByString(String s)
{
for (int i=0; i<cbDia.getItemCount(); i++) {
if (cbDia.getItemAt(i).toString().equals(s)) {
cbDia.setSelectedIndex(i);
break;
}
}
return;
}
private void selectMesByString(String s)
{
for (int i=0; i<cbMes.getItemCount(); i++) {
if (cbMes.getItemAt(i).toString().equals(s)) {
cbMes.setSelectedIndex(i);
break;
}
}
return;
}
private void selectAnoByString(String s)
{
for (int i=0; i<cbAno.getItemCount(); i++) {
if (cbAno.getItemAt(i).toString().equals(s)) {
cbAno.setSelectedIndex(i);
break;
}
}
return;
}
public int totalEntidades()
{
return pacienteList.size();
}
public JPanel getSubPainelCampos()
{
return subPainel_1;
}
public JLabel getMainPainelName()
{
return titlePrincipal;
}
/*public void DisableComponents()
{
txtNome.setEnabled(false);
txtCPF.setEnabled(false);
rbFem.setEnabled(false);
rbMasc.setEnabled(false);
cbDia.setEnabled(false);
cbMes.setEnabled(false);
cbAno.setEnabled(false);
}
public void EnableComponents()
{
txtNome.setEnabled(true);
txtCPF.setEnabled(true);
rbFem.setEnabled(true);
rbMasc.setEnabled(true);
cbDia.setEnabled(true);
cbMes.setEnabled(true);
cbAno.setEnabled(true);
}*/
private void buttonVoltar_Click()
{
frame.setVisible(false);
formPai.setEnabled(true);
frame.dispose();
}
} | 30.08076 | 266 | 0.553222 |
794330c9d9922055fde0ff79503a3098f435f6b2 | 266 | /*
* Copyright Calvin Lee Since 2016.
* All Rights Reserved.
*/
package org.calvin.Graph.Dijkstra;
import lombok.Data;
@Data
public class Edge {
private int t, cost;
public Edge(int t, int cost) {
this.t = t;
this.cost = cost;
}
}
| 14 | 35 | 0.609023 |
86d6bf46e19bc465bfa74309eb7c3be70f9e124d | 1,084 | package org.robolectric.shadows;
import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.Shadows.shadowOf;
import android.app.IntentService;
import android.content.Intent;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class ShadowIntentServiceTest {
@Test
public void shouldSetIntentRedelivery() {
IntentService intentService = new TestIntentService();
ShadowIntentService shadowIntentService = shadowOf(intentService);
assertThat(shadowIntentService.getIntentRedelivery()).isFalse();
intentService.setIntentRedelivery(true);
assertThat(shadowIntentService.getIntentRedelivery()).isTrue();
intentService.setIntentRedelivery(false);
assertThat(shadowIntentService.getIntentRedelivery()).isFalse();
}
private static class TestIntentService extends IntentService {
public TestIntentService() {
super("TestIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
}
}
}
| 30.971429 | 70 | 0.78321 |
d968123aa74841f9c0e85e84956f96d571a74e43 | 643 | class Solution {
public boolean XXX(TreeNode root) {
if(root==null) return true;
return XXX(root.left,root.right);
}
public boolean XXX(TreeNode root1,TreeNode root2){
if(root1==null && root2==null) return true;
if(root1==null && root2!=null) return false;
if(root1!=null && root2==null) return false;
return root1.val==root2.val &&
XXX(root1.left,root2.right) &&
XXX(root1.right,root2.left);
}
}
undefined
for (i = 0; i < document.getElementsByTagName("code").length; i++) { console.log(document.getElementsByTagName("code")[i].innerText); }
| 30.619048 | 139 | 0.611198 |
c2c74372069a3dfb16622a4238f5a457ad620649 | 4,657 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.noirofficial.presenter.adapter;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.noirofficial.BR;
import org.noirofficial.BuildConfig;
public class MultiTypeDataBoundAdapter extends BaseDataBoundAdapter {
private List<Object> mItems = new ArrayList<>();
private ActionCallback mActionCallback;
public MultiTypeDataBoundAdapter(ActionCallback actionCallback, Object... items) {
mActionCallback = actionCallback;
if (null != items) {
Collections.addAll(mItems, items);
}
}
protected void setActionCallback(ActionCallback actionCallback) {
this.mActionCallback = actionCallback;
}
@Override
protected void bindItem(DataBoundViewHolder holder, int position, List payloads) {
Object item = mItems.get(position);
holder.binding.setVariable(BR.data, mItems.get(position));
// this will work even if the layout does not have a callback parameter
holder.binding.setVariable(BR.callback, mActionCallback);
if (item instanceof DynamicBinding) {
((DynamicBinding) item).bind(holder);
}
}
@Override
public
@LayoutRes
int getItemLayoutId(int position) {
// use layout ids as types
Object item = getItem(position);
if (item instanceof LayoutBinding) {
return ((LayoutBinding) item).getLayoutId();
}
if (BuildConfig.DEBUG) {
throw new IllegalArgumentException("unknown item type " + item);
}
return -1;
}
@Override
public int getItemCount() {
return mItems.size();
}
public final List<Object> getItems() {
return mItems;
}
public final void setItems(Object... items) {
mItems.clear();
if (null != items) {
Collections.addAll(mItems, items);
}
notifyDataSetChanged();
}
@Nullable
public final Object getItem(int position) {
return position < mItems.size() ? mItems.get(position) : null;
}
public final int indexOf(Object item) {
return mItems.indexOf(item);
}
public final void addItem(Object item) {
mItems.add(item);
notifyItemInserted(mItems.size() - 1);
}
public final Object getItem(Object item) {
int index = mItems.indexOf(item);
if (index == -1) {
return null;
}
return mItems.get(index);
}
public final boolean containsItem(Object item) {
return mItems.contains(item);
}
public final void addItem(int position, Object item) {
mItems.add(position, item);
notifyItemInserted(position);
}
public final void addItems(Object... items) {
if (null != items) {
int start = mItems.size();
Collections.addAll(mItems, items);
notifyItemRangeChanged(start, items.length);
}
}
public final void addItems(List<Object> items) {
if (null != items) {
int start = mItems.size();
Collections.addAll(mItems, items);
notifyItemRangeChanged(start, items.size());
}
}
public final void removeItem(Object item) {
int position = mItems.indexOf(item);
if (position >= 0) {
mItems.remove(position);
notifyItemRemoved(position);
}
}
public final void removeItems(Object... items) {
if (null != items) {
int size = mItems.size();
mItems.removeAll(Arrays.asList(items));
notifyItemRangeChanged(0, size);
}
}
public void clear() {
int size = mItems.size();
mItems.clear();
notifyItemRangeRemoved(0, size);
}
/**
* Class that all action callbacks must extend for the adapter callback.
*/
public interface ActionCallback {
}
} | 28.224242 | 86 | 0.62916 |
75f60361f34c06f29818135596fc083d41e6c858 | 1,604 | package com.zsvg.vboot.module.ass.num.main;
import com.zsvg.vboot.common.mvc.api.RestResult;
import com.zsvg.vboot.common.mvc.dao.Sqler;
import com.zsvg.vboot.common.util.lang.XstringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("ass/num/main")
public class AssNumMainApi {
@GetMapping
public RestResult get(String name) {
Sqler sqler = new Sqler("t.*","as_num_main");
sqler.addLike("t.name",name);
return RestResult.ok(service.findPageData(sqler)) ;
}
@GetMapping("one/{id}")
public RestResult getOne(@PathVariable String id) {
AssNumMain main=repo.findById(id).get();
return RestResult.ok(main);
}
@PostMapping
public synchronized RestResult post(@RequestBody AssNumMain main) {
if(repo.existsById(main.getId())){
return RestResult.build(201,"编号已存在,请修改编号");
}
main.setNflag(true);
repo.save(main);
return RestResult.ok();
}
@PutMapping
public RestResult pust(@RequestBody AssNumMain main) {
if(XstringUtil.isBlank(main.getNunex())){
main.setNflag(true);
}
repo.save(main);
return RestResult.ok();
}
@DeleteMapping("{ids}")
public RestResult delete(@PathVariable String[] ids) {
for (String id : ids) {
repo.deleteById(id);
}
return RestResult.ok();
}
@Autowired
private AssNumMainRepo repo;
@Autowired
private AssNumMainService service;
}
| 26.733333 | 71 | 0.648379 |
a15d0f0f150e335667a08b3afc103d4ae15fdeb3 | 615 | package com.jsky.core.ArraysAndStrings;
/**
* Question 1.1 IsUnique
* Implement an algorithm to determine if a string has all unique characters.
* What if you cannot use additional data structures?
*/
public class IsUnique {
/**
*
* @param s, a string of values between A - 0...
* @return boolean value for if the string is unique or not
*/
public static boolean isUnique(String s) {
int checker = 0;
for (int i = 0; i < s.length(); i++) {
int val = s.charAt(i) - 'a';
if ((checker & (1 << val)) > 0) return false;
checker |= (1 << val);
}
return true;
}
}
| 24.6 | 77 | 0.606504 |
8b292af1c4fc8f4772bbba1e1a043bdef4a63ba9 | 6,123 | /*
* The MIT License
*
* Copyright (c) 2011-2012, Manufacture Francaise des Pneumatiques Michelin, Daniel Petisme, Romain Seguy
* Portions Copyright 2019 Lexmark
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.michelin.cio.jenkins.plugin.requests.action;
import hudson.Functions;
import java.util.logging.Level;
import hudson.model.Item;
import hudson.model.Job;
import jenkins.model.Jenkins;
import hudson.model.Action;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.verb.POST;
import com.michelin.cio.jenkins.plugin.requests.RequestsPlugin;
import com.michelin.cio.jenkins.plugin.requests.model.RenameJobRequest;
import com.michelin.cio.jenkins.plugin.requests.model.RequestsUtility;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.logging.Logger;
import static java.util.logging.Level.FINE;
// Represents the "Ask for renaming" action appearing on a given project's page.
//
// @author Daniel Petisme <[email protected]> <http://danielpetisme.blogspot.com/>
//
public class RequestRenameJobAction implements Action {
private Job<?, ?> project;
public RequestRenameJobAction(Job<?, ?> target) {
this.project = target;
}
@POST
public HttpResponse doCreateRenameJobRequest(StaplerRequest request,
StaplerResponse response) throws IOException, ServletException, MessagingException {
try {
if (isIconDisplayed()) {
final String newName = request.getParameter("new-name");
final String username = request.getParameter("username");
RequestsPlugin plugin = Jenkins.get().getPlugin(RequestsPlugin.class);
String projectName = project.getFullName();
String projectFullName = project.getFullName();
LOGGER.info("Rename Job Request Before: " + projectName + " - " + projectFullName);
// Check if a folder job type:
if (!projectFullName.contains("/job/") && projectFullName.contains("/")) {
RequestsUtility requestsUtility = new RequestsUtility();
projectFullName = requestsUtility.constructFolderJobName(projectFullName);
}
if (projectName.contains("/")) {
String [] projectnameList = projectName.split("/");
int nameCount = projectnameList.length;
projectName = projectnameList[nameCount-1];
}
LOGGER.info("Rename Job Request After: " + projectName + " - " + projectFullName);
String[] emailData = {projectName + " -> " + newName, username, "A Rename Job", project.getAbsoluteUrl()};
plugin.addRequestPlusEmail(new RenameJobRequest("renameJob", username, projectName, projectFullName, newName), emailData);
LOGGER.log(Level.INFO,
"The request to rename the job {0} to {1} has been sent to the administrator",
new Object[] { project.getName(), newName });
}
} catch (NullPointerException e) {
LOGGER.log(Level.SEVERE, "[ERROR] Exception: " + e.getMessage());
return null;
}
return new HttpRedirect(
request.getContextPath() + '/' + project.getUrl());
}
public String getDisplayName() {
if (isIconDisplayed()) {
return Messages.RequestRenameJobAction_DisplayName();
}
return null;
}
public String getIconFileName() {
if (isIconDisplayed()) {
return "/images/24x24/setting.png";
}
return null;
}
public Job<?, ?> getProject() {
return project;
}
public String getUrlName() {
return "request-rename-job";
}
/*
* Permission computing 1: The user has the permission 0: The user has not
* the permission
*
* Create | 1 | 0 | Delete | 0 | 1 | Configure | 0 | 0 |
*
* So, the action has to be enabled when: Create AND !Delete AND !Configure
* OR Delete AND !Create AND !Configure
*/
private boolean isIconDisplayed() {
boolean isDisplayed = false;
try {
isDisplayed = (!hasDeletePermission() && !hasConfigurePermission() && hasCreatePermission())
|| (!hasCreatePermission() && !hasConfigurePermission() && hasDeletePermission())
|| (!hasDeletePermission() && !hasCreatePermission() && !hasConfigurePermission());
} catch (IOException | ServletException e) {
LOGGER.log(Level.WARNING,
"Impossible to know if the icon has to be displayed", e);
}
return isDisplayed;
}
private boolean hasConfigurePermission()
throws IOException, ServletException {
return Functions.hasPermission(project, Item.CONFIGURE);
}
private boolean hasCreatePermission() throws IOException, ServletException {
return Functions.hasPermission(project, Item.CREATE);
}
private boolean hasDeletePermission() throws IOException, ServletException {
return Functions.hasPermission(project, Item.DELETE);
}
private static final Logger LOGGER = Logger
.getLogger(RequestRenameJobAction.class.getName());
}
| 36.017647 | 127 | 0.715826 |
c5d1cbddef13ed9581bd2f93cdbbf081a28ccd15 | 3,797 | /*
* Copyright © 2010 www.myctu.cn. All rights reserved.
*/
package com.chinatelecom.myctu.upnsa.core.injection;
import java.lang.reflect.*;
import static java.lang.String.format;
/**
* Given a DependencyInjectingObjectFactory, injects dependencies into a class.
*/
public class DependencyInjector {
private DependencyInjectingObjectFactory dependencyInjectingObjectFactory;
public DependencyInjector(DependencyInjectingObjectFactory aDependencyInjectingObjectFactory) {
dependencyInjectingObjectFactory = aDependencyInjectingObjectFactory;
}
@SuppressWarnings("unchecked")
public <T> void injectDependenciesForClassHierarchy(T anObject) {
// the reflection API requires that each class in the hierarchy be considered
// start with the lowest class in the hierarchy
Class<?> interfaceOfObject = anObject.getClass();
do {
// inject the dependencies for this class
injectDependenciesForSingleClass(anObject, (Class<T>) interfaceOfObject);
// move on up the class hierarchy...
interfaceOfObject = interfaceOfObject.getSuperclass();
// until the top is reached
} while (interfaceOfObject != null);
}
private <T, S extends T> void injectDependenciesForSingleClass(S anObject, Class<T> aClass) {
// for each
for (Field field : aClass.getDeclaredFields()) {
if (field.isAnnotationPresent(Dependency.class)) {
field.setAccessible(true);
try {
// if the field has not already been set (possibly through injection)...
if (field.get(anObject) == null) {
Class<?> classOfDependency = field.getType();
final Object injectedValue;
final int modifiers = classOfDependency.getModifiers();
if (Modifier.isInterface(modifiers) || Modifier.isAbstract(modifiers)) {
injectedValue = createProxy(classOfDependency);
} else {
injectedValue = dependencyInjectingObjectFactory.getObject(classOfDependency);
}
field.set(anObject, injectedValue);
}
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(format("Unable to access field %s.", field.getName()), e);
}
}
}
}
@SuppressWarnings("unchecked")
private <T> T createProxy(final Class<T> aClass) {
// TODO optimize this to replace the proxy once the object is lazily created
return (T) Proxy.newProxyInstance(DependencyInjectingObjectFactory.class.getClassLoader(),
new Class[]{aClass}, new InvocationHandler() {
private T object;
public Object invoke(Object aProxy, Method aMethod, Object[] anArrayOfArguments) throws Throwable {
if (object == null) {
final ObjectSource<T> objectSource = dependencyInjectingObjectFactory
.getObjectSource(aClass);
if (objectSource == null) {
throw new RuntimeException(format(
"No source was registered for the dependecy of type %s.", aClass.getName()));
}
object = (T) objectSource.getObject();
}
return aMethod.invoke(object, anArrayOfArguments);
}
});
}
}
| 43.147727 | 112 | 0.580985 |
d30f30891a232b356c4028a5ce91308399a3731c | 122 | public class Warning {
public Warning() {
// assertions are ignored at runtime
assert false;
}
}
| 15.25 | 44 | 0.581967 |
3c277e0275212d140d2a6d3eb53a0187bd4f20c0 | 2,667 | package kariminf.sentrep.ston;
import java.util.regex.Pattern;
public class StonBlocks {
//Indentation character: it can be \t or 4 spaces or anything else
public static final String INDENT = " ";
// These are the characters to be ignored
public static final String BL = "[\\t \\n\\r]+";
private static final String Block =
StonKeys.BLOCKSIGN + "%1\\:\\[(.*)%1\\:\\]";
private static final String InternBlock =
Block + ";?";
// Adjective
//TODO modify to [aA][dD][jJ]
public static final String ADJblock =
InternBlock.replaceAll("%1", StonKeys.ADJBL);
public static final String beginADJ =
StonKeys.BLOCKSIGN + StonKeys.ADJBL;
public static final String ADVblock =
InternBlock.replaceAll("%1", StonKeys.ADVBL);
//"@adv\\:\\[(.*)adv\\:\\];?";
public static final String beginROLE =
StonKeys.BLOCKSIGN + StonKeys.ROLEBL;
public static final String beginACTION =
StonKeys.BLOCKSIGN + StonKeys.ACTBL;
public static final String beginSENT =
StonKeys.BLOCKSIGN + StonKeys.SENTBL;
public static final String beginADV =
StonKeys.BLOCKSIGN + StonKeys.ADVBL;
// Relative clauses
public static final String RELblock =
InternBlock.replaceAll("%1", StonKeys.RELBL);
//"@rel\\:\\[(.*)rel\\:\\];?";
public static final String beginREL =
StonKeys.BLOCKSIGN + StonKeys.RELBL;
// Comparison block
public static final String CMPblock =
InternBlock.replaceAll("%1", StonKeys.COMPBL);
//"@cmp\\:\\[(.*)cmp\\:\\];?";
public static final String beginCMP =
StonKeys.BLOCKSIGN + StonKeys.COMPBL;
public static final String ROLEblock =
Block.replaceAll("%1", StonKeys.ROLEBL);
public static final String ACTblock =
Block.replaceAll("%1", StonKeys.ACTBL);
public static final String SENTblock =
Block.replaceAll("%1", StonKeys.SENTBL);
// This is the regular expression used to separate main blocks
public static final Pattern CONT =
Pattern.compile(ROLEblock + ACTblock + SENTblock);
//Pattern.compile("@r\\:\\[(.+)r\\:\\]@act\\:\\[(.+)act\\:\\]@st\\:\\[(.+)st\\:\\]");
public static final String IGNOREblock =
"\\" + StonKeys.BCOMMENT + "[^\\" + StonKeys.ECOMMENT
+"]*\\" + StonKeys.ECOMMENT;
/**
* Return the desired indentation
* @param n this is the level of indentation
* @return the string of indentation
*/
public static String getIndentation(int n){
if (n <= 0)
return "";
return new String(new char[n]).replace("\0", INDENT);
/*
String result = "";
for (int i=0; i< n; i++)
result += INDENT;
return result;
*/
}
public static void main(String[] args) {
System.out.println(CMPblock);
}
}
| 26.67 | 88 | 0.659168 |
d3d0af908198ff4f07bb77a8ac605a786efe09ea | 3,804 | /**
* 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 com.dtstack.flinkx.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* The configuration of writer configuration
*
* Company: www.dtstack.com
* @author [email protected]
*/
public class WriterConfig extends AbstractConfig {
public static String KEY_PARAMETER_CONFIG = "parameter";
public static String KEY_WRITER_NAME = "name";
ParameterConfig parameter;
public WriterConfig(Map<String, Object> map) {
super(map);
parameter = new ParameterConfig((Map<String, Object>) getVal(KEY_PARAMETER_CONFIG));
}
public String getName() {
return getStringVal(KEY_WRITER_NAME);
}
public void setName(String name) {
setStringVal(KEY_WRITER_NAME, name);
}
public ParameterConfig getParameter() {
return parameter;
}
public void setParameter(ParameterConfig parameter) {
this.parameter = parameter;
}
public static class ParameterConfig extends AbstractConfig {
public static final String KEY_COLUMN_LIST = "column";
public static final String KEY_CONNECTION_CONFIG_LIST = "connection";
List column;
List<ConnectionConfig> connection;
public ParameterConfig(Map<String, Object> map) {
super(map);
column = (List) getVal(KEY_COLUMN_LIST);
List<Map<String,Object>> connList = (List<Map<String, Object>>) getVal(KEY_CONNECTION_CONFIG_LIST);
connection = new ArrayList<>();
if(connList != null) {
for(Map<String,Object> conn : connList) {
connection.add(new ConnectionConfig(conn));
}
}
}
public List getColumn() {
return column;
}
public void setColumn(List column) {
this.column = column;
}
public List<ConnectionConfig> getConnection() {
return connection;
}
public void setConnection(List<ConnectionConfig> connection) {
this.connection = connection;
}
public class ConnectionConfig extends AbstractConfig {
private static final String KEY_JDBC_URL = "jdbcUrl";
private static final String KEY_TABLE_LIST = "table";
private String jdbcUrl;
private List<String> table;
public ConnectionConfig(Map<String, Object> map) {
super(map);
jdbcUrl = getStringVal(KEY_JDBC_URL);
table = (List<String>) getVal(KEY_TABLE_LIST);
}
public String getJdbcUrl() {
return jdbcUrl;
}
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
public List<String> getTable() {
return table;
}
public void setTable(List<String> table) {
this.table = table;
}
}
}
}
| 29.71875 | 111 | 0.626446 |
2f0cca290739b7d9f39db1be146cb107f8126d7a | 4,371 | /*
* Copyright 2017 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 console;
import base.core;
import org2.beryx.textio.TextIO;
import org2.beryx.textio.TextIoFactory;
import org2.beryx.textio.TextTerminal;
import org2.beryx.textio.web.RunnerData;
import java.util.function.BiConsumer;
import ratpack.handling.Context;
import user.User;
import user.UserType;
import user.Users;
/**
* Illustrates some features introduced in version 3 of Text-IO: line reset, bookmarking etc.
*/
public class BootStart implements BiConsumer<TextIO, RunnerData> {
public static void main(String[] args) {
TextIO textIO = TextIoFactory.getTextIO();
new BootStart().accept(textIO, null);
}
@Override
public void accept(TextIO textIO, RunnerData runnerData) {
TextTerminal<?> terminal = textIO.getTextTerminal();
@SuppressWarnings("null")
Context context = runnerData.getContext();
String key = context.getRequest().oneCookie(core.dbUserKey);
String password = context.getRequest().oneCookie(core.dbUserPassword);
User user = User.getUserSHA1(key);
// password needs to be accepted
if(user.getPassword().equals(password) == false){
user = Users.getAnon();
}
// start the main banner
terminal.println(AsciiArt.nya());
terminal.println();
// show that we are logged
if(user.getUserType() != UserType.anon){
//terminal.println("logged as: " + user.getId());
}else{
terminal.println("Welcome! Type \"help\" to get started");
}
// reset the current folder
user.setFolderCurrent(user.getFilesystem());
terminal.println();
terminal.setBookmark("MAIN");
boolean continueLooping = true;
while(continueLooping) {
// generate the command prompt
String commandPrompt = generateCommandPrompt(user);
// wait for a command to be input
String command = textIO.newStringInputReader().read(commandPrompt);
// try to process the command
DataExchange data = processCommand(command, user, terminal, context);
if(data != null && data.getUser() != null){
user = data.getUser();
}
// put it in memory
ConsoleWeb.addDataExchange(data, context);
//delay(500);
}
}
@SuppressWarnings("CallToPrintStackTrace")
public static void delay(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Process a command and acts accordingly
* @param command
* @param user
* @param terminal
* @param context
*/
private DataExchange processCommand(String command, User user,
TextTerminal<?> terminal, Context context) {
if(command == null){
command = "";
}
// avoid overflow
if(command.length() > 1000){
command = command.substring(0, 1000);
}
// run it
DataExchange data = core.commands.run(command, user, terminal, context);
return data;
}
private String getFolder(User user) {
return user.getFolderCurrent().getPath();
}
private String generateCommandPrompt(User user) {
String commandPrompt = user.getId()
+ "@nya:~";
if (getFolder(user).equalsIgnoreCase("/") == false) {
commandPrompt += getFolder(user);
}
commandPrompt += "$";
return commandPrompt;
}
}
| 30.78169 | 93 | 0.601464 |
74770eac5d19e26a9237501e4181253d5fa4805b | 1,956 | package org.frameworkset.security.session.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.frameworkset.util.ValueObjectUtil;
public class JVMSessionSerial extends BBossSessionSerial {
@Override
public String serialize(Object object) {
if(object == null)
return null;
else
{
if(object instanceof java.io.Serializable)
{
java.io.ObjectOutputStream out =null;
ByteArrayOutputStream byteout = null;
try {
byteout = new ByteArrayOutputStream();
out = new ObjectOutputStream(byteout);
out.writeObject(object);
return ValueObjectUtil.byteArrayEncoder(byteout.toByteArray());
} catch (IOException e) {
throw new SessionException(e);
}
finally
{
try {
if(byteout != null)
byteout.close();
if(out != null)
out.close();
} catch (IOException e) {
}
}
}
else
{
StringBuilder ret = new StringBuilder();
ret.append("b:");
return ret.append(super.serialize(object)).toString();
}
}
}
@Override
public Object deserialize(String object) {
if(object == null)
return null;
if(!object.startsWith("b:"))
{
ByteArrayInputStream in = null;
ObjectInputStream ois = null;
try {
byte[] v = ValueObjectUtil.byteArrayDecoder(object);
in = new ByteArrayInputStream(v);
ois = new ObjectInputStream(in);
return ois.readObject();
} catch (Exception e) {
throw new SessionException(e);
}
finally
{
try {
if(in != null)
in.close();
if(ois != null)
ois.close();
} catch (IOException e) {
}
}
}
else
{
object = object.substring(2);
return super.deserialize(object);
}
}
public static void main(String[] args)
{
System.out.println("b:sss".substring(2));
}
}
| 20.164948 | 68 | 0.638037 |
20e7be785e4d381c55ce80c218926812e7782f7c | 19,291 | /*
* -\-\-
* Spotify Styx Scheduler Service
* --
* Copyright (C) 2017 Spotify AB
* --
* 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.spotify.styx.client;
import static com.google.common.collect.Iterables.getLast;
import static com.spotify.styx.util.StringIsValidUuid.isValidUuid;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.ImmutableList;
import com.spotify.apollo.Client;
import com.spotify.apollo.Request;
import com.spotify.apollo.Response;
import com.spotify.apollo.Status;
import com.spotify.styx.api.Api;
import com.spotify.styx.client.auth.GoogleIdTokenAuth;
import com.spotify.styx.model.Backfill;
import com.spotify.styx.model.BackfillInput;
import com.spotify.styx.model.EditableBackfillInput;
import com.spotify.styx.model.Schedule;
import com.spotify.styx.model.Workflow;
import com.spotify.styx.model.WorkflowConfiguration;
import com.spotify.styx.model.WorkflowId;
import com.spotify.styx.model.WorkflowInstance;
import com.spotify.styx.model.WorkflowState;
import com.spotify.styx.model.data.WorkflowInstanceExecutionData;
import com.spotify.styx.serialization.Json;
import java.io.IOException;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import okhttp3.HttpUrl;
import okio.ByteString;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@RunWith(JUnitParamsRunner.class)
public class StyxApolloClientTest {
private static final WorkflowConfiguration WORKFLOW_CONFIGURATION_1 = WorkflowConfiguration.builder()
.id("bar-wf_1")
.dockerImage("busybox")
.dockerArgs(ImmutableList.of("echo", "hello world"))
.schedule(Schedule.DAYS)
.build();
private static final WorkflowConfiguration WORKFLOW_CONFIGURATION_2 = WorkflowConfiguration.builder()
.id("bar-wf_2")
.dockerImage("busybox")
.dockerArgs(ImmutableList.of("echo", "hello world"))
.schedule(Schedule.DAYS)
.build();
private static final Workflow WORKFLOW_1 = Workflow.create("foo-comp", WORKFLOW_CONFIGURATION_1);
private static final Workflow WORKFLOW_2 = Workflow.create("foo-comp", WORKFLOW_CONFIGURATION_2);
private static final Instant START = Instant.parse("2017-01-01T00:00:00Z");
private static final Instant END = Instant.parse("2017-01-30T00:00:00Z");
private static final BackfillInput BACKFILL_INPUT =
BackfillInput.newBuilder()
.start(START)
.end(END)
.component("foo-comp")
.workflow("bar-wf")
.concurrency(1)
.build();
private static final Backfill BACKFILL = Backfill.newBuilder()
.id("backfill-2")
.start(START)
.end(END)
.workflowId(WorkflowId.create("foo-comp", "bar-wf"))
.concurrency(1)
.nextTrigger(Instant.parse("2017-01-01T00:00:00Z"))
.schedule(Schedule.DAYS)
.build();
@Mock Client client;
@Mock GoogleIdTokenAuth auth;
@Captor ArgumentCaptor<Request> requestCaptor;
private static final String API_VERSION = getLast(asList(Api.Version.values())).name().toLowerCase();
private static final HttpUrl API_URL = new HttpUrl.Builder()
.scheme("https").host("foo.bar")
.addPathSegment("api").addPathSegment(API_VERSION).build();
private static final String CLIENT_HOST = API_URL.scheme() + "://" + API_URL.host() ;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(auth.getToken(any())).thenReturn(Optional.of("foobar"));
}
@Test
@Parameters({
"foo.bar, https://foo.bar",
"foo.bar:80, https://foo.bar",
"foo.bar:17, https://foo.bar:17",
"http://foo.bar, http://foo.bar",
"http://foo.bar:80, http://foo.bar",
"http://foo.bar:17, http://foo.bar:17",
"https://foo.bar, https://foo.bar",
"https://foo.bar:443, https://foo.bar",
"https://foo.bar:17, https://foo.bar:17",
})
public void testHosts(String host, String expectedUriPrefix) {
final CompletableFuture<Response<ByteString>> responseFuture = new CompletableFuture<>();
when(client.send(any(Request.class))).thenReturn(responseFuture);
final StyxApolloClient styx = new StyxApolloClient(client, host, auth);
styx.resourceList();
verify(client, timeout(30_000)).send(requestCaptor.capture());
final Request request = requestCaptor.getValue();
assertThat(request.uri(), startsWith(expectedUriPrefix));
}
@Test
public void shouldGetAllWorkflows() throws Exception {
final List<Workflow> workflows = ImmutableList.of(WORKFLOW_1, WORKFLOW_2);
when(client.send(any(Request.class))).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK).withPayload(Json.serialize(workflows))));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<List<Workflow>> r = styx.workflows().toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
final Request request = requestCaptor.getValue();
assertThat(request.uri(), is(API_URL + "/workflows"));
assertThat(request.method(), is("GET"));
assertThat(r.get(), is(workflows));
}
@Test
public void shouldGetWorkflowInstance() throws Exception {
final WorkflowInstanceExecutionData workflowInstanceExecutionData =
WorkflowInstanceExecutionData.create(
WorkflowInstance.create(
WorkflowId.create("component", "workflow"),
"2017-01-01T00"),
Collections.emptyList());
when(client.send(any(Request.class))).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK).withPayload(Json.serialize(workflowInstanceExecutionData))));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<WorkflowInstanceExecutionData> r =
styx.workflowInstanceExecutions("component", "workflow", "2017-01-01T00")
.toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
final Request request = requestCaptor.getValue();
assertThat(request.uri(),
is(API_URL + "/workflows/component/workflow/instances/2017-01-01T00"));
assertThat(request.method(), is("GET"));
assertThat(r.get(), is(workflowInstanceExecutionData));
}
@Test
public void deleteWorkflow() {
when(client.send(any(Request.class))).thenReturn(
CompletableFuture.completedFuture(Response.forStatus(Status.NO_CONTENT)));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<Void> r = styx.deleteWorkflow("foo-comp", "bar-wf").toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
assertThat(r.isCompletedExceptionally(), is(false));
final Request request = requestCaptor.getValue();
assertThat(request.uri(), is(API_URL + "/workflows/foo-comp/bar-wf"));
assertThat(request.method(), is("DELETE"));
}
@Test
public void createOrUpdateWorkflow() throws Exception {
when(client.send(any(Request.class))).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK).withPayload(Json.serialize(WORKFLOW_1))));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<Workflow> r = styx.createOrUpdateWorkflow("foo-comp",
WORKFLOW_CONFIGURATION_1).toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
final Request request = requestCaptor.getValue();
assertThat(request.uri(), is(API_URL + "/workflows/foo-comp"));
assertThat(Json.deserialize(request.payload().get(), WorkflowConfiguration.class),
is(WORKFLOW_CONFIGURATION_1));
assertThat(request.method(), is("POST"));
}
@Test
public void shouldCreateBackfill() throws Exception {
when(client.send(any(Request.class))).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK).withPayload(Json.serialize(BACKFILL))));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<Backfill> r = styx.backfillCreate("foo-comp", "bar-wf",
"2017-01-01T00:00:00Z", "2017-01-30T00:00:00Z", 1)
.toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
final Request request = requestCaptor.getValue();
assertThat(request.uri(), is(API_URL + "/backfills"));
assertThat(Json.deserialize(request.payload().get(), BackfillInput.class),
equalTo(BACKFILL_INPUT));
assertThat(request.method(), is("POST"));
}
@Test
public void shouldCreateBackfillFromInput() throws Exception {
final BackfillInput backfillInput = BACKFILL_INPUT.builder()
.reverse(true)
.build();
when(client.send(any(Request.class))).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK).withPayload(Json.serialize(BACKFILL))));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<Backfill> r = styx.backfillCreate(backfillInput)
.toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
final Request request = requestCaptor.getValue();
assertThat(request.uri(), is(API_URL + "/backfills"));
assertThat(Json.deserialize(request.payload().get(), BackfillInput.class),
equalTo(backfillInput));
assertThat(request.method(), is("POST"));
}
@Test
public void shouldCreateBackfillWithDescription() throws Exception {
final BackfillInput backfillInput = BACKFILL_INPUT.builder()
.description("Description")
.build();
when(client.send(any(Request.class))).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK).withPayload(Json.serialize(BACKFILL))));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<Backfill> r = styx.backfillCreate("foo-comp", "bar-wf",
"2017-01-01T00:00:00Z",
"2017-01-30T00:00:00Z", 1,
"Description")
.toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
final Request request = requestCaptor.getValue();
assertThat(request.uri(), is(API_URL + "/backfills"));
assertThat(Json.deserialize(request.payload().get(), BackfillInput.class),
equalTo(backfillInput));
assertThat(request.method(), is("POST"));
}
@Test
public void shouldUpdateBackfillConcurrency() throws IOException {
final EditableBackfillInput backfillInput = EditableBackfillInput.newBuilder()
.id(BACKFILL.id())
.concurrency(4)
.build();
when(client.send(any(Request.class))).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK).withPayload(Json.serialize(
BACKFILL.builder().concurrency(4).build()))));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<Backfill> r = styx.backfillEditConcurrency(BACKFILL.id(), 4)
.toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
final Request request = requestCaptor.getValue();
assertThat(request.uri(), is(API_URL + "/backfills/" + BACKFILL.id()));
assertThat(Json.deserialize(request.payload().get(), EditableBackfillInput.class),
equalTo(backfillInput));
assertThat(request.method(), is("PUT"));
}
@Test
public void shouldUpdateWorkflowState() throws Exception {
final WorkflowState workflowState = WorkflowState.builder()
.enabled(true)
.nextNaturalTrigger(Instant.parse("2017-01-03T21:00:00Z"))
.nextNaturalTrigger(Instant.parse("2017-01-03T22:00:00Z"))
.build();
when(client.send(any(Request.class))).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK).withPayload(Json.serialize(workflowState))));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<WorkflowState> r =
styx.updateWorkflowState("foo-comp", "bar-wf", workflowState).toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
final Request request = requestCaptor.getValue();
assertThat(request.uri(), is(API_URL + "/workflows/foo-comp/bar-wf/state"));
assertThat(Json.deserialize(request.payload().get(), WorkflowState.class), is(workflowState));
assertThat(request.method(), is("PATCH"));
}
@Test
public void testTokenSuccess() {
when(client.send(any(Request.class))).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK)));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<Void> r =
styx.triggerWorkflowInstance("foo", "bar", "baz").toCompletableFuture();
verify(client, timeout(30_000)).send(requestCaptor.capture());
assertThat(r.isDone(), is(true));
final Request request = requestCaptor.getValue();
assertThat(request.header("Authorization").get(), is("Bearer foobar"));
}
@Test
public void testTokenFailure() throws Exception {
final IOException rootCause = new IOException("netsplit!");
when(auth.getToken(any())).thenThrow(rootCause);
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final CompletableFuture<Void> f = styx.triggerWorkflowInstance("foo", "bar", "baz")
.toCompletableFuture();
try {
f.get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause(), instanceOf(ClientErrorException.class));
assertThat(e.getCause().getMessage(), is("Authentication failure: " + rootCause.getMessage()));
assertThat(e.getCause().getCause(), is(rootCause));
}
}
@Test
public void testUnathorizedMissingCredentialsApiError() throws Exception {
when(auth.getToken(any())).thenReturn(Optional.empty());
when(client.send(any()))
.thenReturn(CompletableFuture.completedFuture(Response.forStatus(Status.UNAUTHORIZED)));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
try {
styx.triggerWorkflowInstance("foo", "bar", "baz").toCompletableFuture().get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause(), instanceOf(ApiErrorException.class));
ApiErrorException apiErrorException = (ApiErrorException) e.getCause();
assertThat(apiErrorException.isAuthenticated(), is(false));
}
}
@Test
public void testUnauthorizedWithCredentialsApiError() throws Exception {
when(client.send(any()))
.thenReturn(CompletableFuture.completedFuture(Response.forStatus(Status.UNAUTHORIZED)));
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
try {
styx.triggerWorkflowInstance("foo", "bar", "baz").toCompletableFuture().get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause(), instanceOf(ApiErrorException.class));
ApiErrorException apiErrorException = (ApiErrorException) e.getCause();
assertThat(apiErrorException.isAuthenticated(), is(true));
}
}
@Test
public void testSendsRequestId() throws JsonProcessingException {
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
when(client.send(requestCaptor.capture())).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.OK).withPayload(Json.serialize(Collections.emptyList()))));
styx.workflows();
final Request request = requestCaptor.getValue();
assertThat(request.header("X-Request-Id").get(), isValidUuid());
}
@Test
public void testUsesServerRequestIdOnMismatch() throws JsonProcessingException, InterruptedException {
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
final String responseRequestId = "foobar";
when(client.send(any())).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.INTERNAL_SERVER_ERROR)
.withHeader("X-Request-Id", responseRequestId)
.withPayload(Json.serialize(Collections.emptyList()))));
try {
styx.workflows().toCompletableFuture().get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause(), instanceOf(ApiErrorException.class));
final ApiErrorException apiError = (ApiErrorException) e.getCause();
assertThat(apiError.getRequestId(), is(responseRequestId));
}
}
@Test
public void testUsesClientRequestIdOnNoResponseRequestId() throws JsonProcessingException, InterruptedException {
final StyxApolloClient styx = new StyxApolloClient(client, CLIENT_HOST, auth);
when(client.send(requestCaptor.capture())).thenReturn(CompletableFuture.completedFuture(
Response.forStatus(Status.INTERNAL_SERVER_ERROR)
.withPayload(Json.serialize(Collections.emptyList()))));
try {
styx.workflows().toCompletableFuture().get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause(), instanceOf(ApiErrorException.class));
final ApiErrorException apiError = (ApiErrorException) e.getCause();
final Request request = requestCaptor.getValue();
assertThat(apiError.getRequestId(), is(request.header("X-Request-Id").get()));
}
}
}
| 43.943052 | 115 | 0.715671 |
7f5c3ab8e789f605ea49052dcd30fb7f7ba0f9f6 | 3,430 | package ca.uhn.fhir.example;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.flipkart.zjsonpatch.JsonPatch;
import org.hl7.fhir.instance.model.api.IBaseResource;
import javax.ws.rs.client.Entity;
public class Mapper {
private final static String TYPE = "type";
private final static String RESOURCE_TYPE = "resourceType";
private final static String ID = "id";
protected final FhirContext ctx = FhirContext.forR4();
protected final ObjectMapper oMapper = new ObjectMapper();
public Entity resourceToEntity(IBaseResource resource) {
ObjectNode resourceJson = resourceToJson(resource);
resourceJson.set(TYPE, resourceJson.get(RESOURCE_TYPE));
if (resourceJson.has(TYPE))
resourceJson.remove(RESOURCE_TYPE);
return Entity.json(resourceJson.toString());
}
public IBaseResource entityToResource(Entity entity, Class<? extends IBaseResource> resourceClass) {
ObjectNode entityJson = entityToJson(entity);
entityJson.set(RESOURCE_TYPE, entityJson.get(TYPE));
if(entityJson.has(RESOURCE_TYPE))
entityJson.remove(TYPE);
IParser parser = ctx.newJsonParser();
return parser.parseResource(resourceClass, entityJson.toString());
}
public Entity prepareEntityForUpdate(Entity entity) {
ObjectNode entityJson = entityToJson(entity);
entityJson.remove(TYPE);
entityJson.remove(ID);
return Entity.json(entityJson.toString());
}
public IBaseResource applyPatchToResource(String patchBody, IBaseResource resource) {
JsonNode patch = patchBodyToJson(patchBody);
JsonNode resourceJson = resourceToJson(resource);
JsonPatch.validate(patch);
JsonNode patchedResourceJson = JsonPatch.apply(patch, resourceJson);
return jsonToResource(patchedResourceJson, resource.getClass());
}
private IBaseResource jsonToResource(JsonNode resourceJson, Class<? extends IBaseResource> resourceClass) {
IParser parser = ctx.newJsonParser();
return parser.parseResource(resourceClass, resourceJson.toString());
}
private ObjectNode resourceToJson(IBaseResource resource) {
IParser parser = ctx.newJsonParser();
try {
return (ObjectNode) oMapper.readTree(parser.encodeResourceToString(resource));
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new UnprocessableEntityException("Error when converting Resource to Json");
}
}
private ObjectNode entityToJson(Entity entity) {
try {
return (ObjectNode) oMapper.readTree(entity.getEntity().toString());
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new UnprocessableEntityException("Error when converting Entity to Json");
}
}
private JsonNode patchBodyToJson(String patchBody) {
try {
return oMapper.readTree(patchBody);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new UnprocessableEntityException("Wrong patch body");
}
}
}
| 33.960396 | 110 | 0.729738 |
4f957095ca6f3d12f6d57bc6f4a64dd8bbb1cd18 | 615 | package com.test.list;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CircleSingleLinkedTest {
@Test
void add() {
CircleSingleLinked circleSingleLinked = new CircleSingleLinked();
circleSingleLinked.add(5);
circleSingleLinked.list();
}
@Test
void outListTest(){
CircleSingleLinked circleSingleLinked = new CircleSingleLinked();
int size = 5;
circleSingleLinked.add(size);
circleSingleLinked.list();
System.out.println("开始出圈");
circleSingleLinked.outList(1, 2, size);
}
} | 24.6 | 73 | 0.661789 |
81fe1b6db926c470eb8d452cb7d46f3301db6909 | 1,278 | package com.niki.appbase.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by Bob on 2018/3/16.
*/
public class MD5Util {
/**
* 对签名字符串进行MD5加密,生成16位的字符串
* @param source
* @return
*/
public static String encryption16(String source){
return encryption32(source).substring(8, 24);
}
/**
* 对签名字符串进行MD5加密,生成32位的字符串
* @param source
* @return
*/
public static String encryption32(String source) {
String result = "";
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(source.getBytes());
byte [] b= md5.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
result = buf.toString();
} catch (NoSuchAlgorithmException e) {
// logger.error(e.getMessage());
}
return result;
}
}
| 26.625 | 66 | 0.498435 |
2286bf366b28dd05a17069c8de8053e635f4049f | 6,389 | package com.atjl.kafka.consumer;
import com.atjl.util.common.CheckUtil;
import com.atjl.util.queue.QueueManager;
import com.atjl.kafka.core.KafkaConsumeContext;
import com.atjl.kafka.core.thread.FetchDataMCThread;
import com.atjl.kafka.core.thread.ProcessMCThread;
import com.atjl.kafka.core.thread.TimingBatchEventForceSendThread;
import com.atjl.kafka.core.thread.TimingCommitThread;
import com.atjl.kafka.domain.constant.KafkaConfigConstant;
import com.atjl.kafka.domain.constant.KafkaInnerConstant;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Properties;
/**
* Kafka consumer 手动提交
*
* use high level consumer API
* for version <= 0.8.2
* <p>
* ZookeeperConsumerConnector
* Consumer:
* /consumers/[group_id]/ids[consumer_id] -> topic1,...topicN
* <p>
* Consumer Offset Value:
* /consumers/[group_id]/offsets/[topic]/[broker_id-partition_id] --> offset_counter_value
* <p>
* if you provide more threads than there are partitions on the topic, some threads will never see a message
* if you have more partitions than you have threads, some threads will receive data from multiple partitions
* if you have multiple partitions per thread there is NO guarantee about the order you receive messages, other than that within the partition the offsets will be sequential.
* For example, you may receive 5 messages from partition 10 and 6 from partition 11, then 5 more from partition 10 followed by 5 more from partition 10 even if partition 11 has data available.
* adding more processes/threads will cause Kafka to re-balance, possibly changing the assignment of a Partition to a Thread.
*
* @since 1.0
*/
public class TConsumer extends Consumer {
private static Logger LOG = LoggerFactory.getLogger(TConsumer.class);
/**
* configs
*/
private KafkaConsumeContext context;
public TConsumer() {
this.propertiesFile = KafkaConfigConstant.DFT_CONF_FILE;
}
public TConsumer(String propertiesFile) {
this.propertiesFile = propertiesFile;
}
public void initMethod() {
//properties file or spring inject
CheckUtil.checkAllNull(this.propertiesFile, this.config);
//generate config
// this.config = ConfigModelUtil.generateConfigModel(ConsumerConfig.class,KafkaConfigConstant.CCONF_PREFIX, KafkaConfigConstant.DFT_CONF_FILE, null);
CheckUtil.checkExistNull(this.config);
Properties properties = this.config.createConsumerConfig();
kafka.consumer.ConsumerConfig config = new kafka.consumer.ConsumerConfig(properties);
consumer = kafka.consumer.Consumer.createJavaConsumerConnector(config);
if (LOG.isDebugEnabled()) {
LOG.debug("construct mq config {}", this.config);
}
context = new KafkaConsumeContext();
status = Consumer.Status.INIT;
}
/**
* 启动consumer
*/
public void start() {
constructStream();
initPool(this.config.getTimingThreadPoolSize() + 1);
/**
* resume threads
*/
int timingId = 0;
startFetchThread();
startFetchTimngBatchEventForceSendThread(timingId++);
startProcessThread();
startCommitThread(timingId++);
startStatThread(timingId++);
this.status = Status.RUNNING;
if (LOG.isInfoEnabled()) {
LOG.info("resume running");
}
}
/**
* fetch data thread
*
* @return
*/
private void startFetchThread() {
int threadNumber = 0;
for (final KafkaStream<String, String> stream : streams) {
fetchDataPool.submit(new FetchDataMCThread(threadNumber, this.config, this.context, stream, QueueManager.getQueue(KafkaInnerConstant.DATA_QUEUE_KEY)));
threadNumber++;
}
if (LOG.isDebugEnabled()) {
LOG.debug("resume thread fetch count {}", threadNumber);
}
}
/**
* 启动定时强制发送数据
*/
private void startFetchTimngBatchEventForceSendThread(int id) {
TimingBatchEventForceSendThread t = new TimingBatchEventForceSendThread(id, this.config.getBatchEventForceSendInterval());
timerProcessPool.scheduleAtFixedRate(
t,
t.getDelay(),
t.getInterval(),
t.getTimeUnit());
if (LOG.isDebugEnabled()) {
LOG.debug("resume thread force send,interval {}", t.getInterval());
}
}
private void startProcessThread() {
int processThreadCount = this.config.getProcessThreadPoolSize();
int threadNumber = 0;
for (int i = 0; i < processThreadCount; i++) {
fetchDataPool.submit(new ProcessMCThread(threadNumber, this.context, QueueManager.getQueue(KafkaInnerConstant.DATA_QUEUE_KEY), this.config.getTopicHandler()));
threadNumber++;
}
if (LOG.isDebugEnabled()) {
LOG.debug("resume thread process count {}", processThreadCount);
}
}
/**
* resume commit thread
*/
private void startCommitThread(int id) {
TimingCommitThread tct = new TimingCommitThread(id,
this.config.getCommitInterval(),
this.config.getTopic(),
this.getConsumer(),
this.context);
timerProcessPool.scheduleAtFixedRate(
tct,
tct.getDelay(),
tct.getInterval(),
tct.getTimeUnit());
if (LOG.isDebugEnabled()) {
LOG.debug("resume thread commit,interval {}", tct.getInterval());
}
}
public ConsumerConnector getConsumer() {
return consumer;
}
public void setConsumer(ConsumerConnector consumer) {
this.consumer = consumer;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public KafkaConsumeContext getContext() {
return context;
}
public List<KafkaStream<String, String>> getStreams() {
return streams;
}
}
| 33.626316 | 194 | 0.640945 |
4fb1188497cf3e1c61ab5701885a2e0e78f4902e | 184 | package com.fsck.k9.preferences;
/**
* Controls when to hide the subject in the notification area.
*/
public enum NotificationHideSubject {
ALWAYS,
WHEN_LOCKED,
NEVER
}
| 16.727273 | 62 | 0.711957 |
cac16295af0c6df872a1f4bd9e33b13adb3c925b | 762 | /*
Sistema de Gestão de Pistas
(C) 2016 Tecsidel
Updated by wilson.souza (WR DevInfo)
Description:
*/
package br.com.tk.mcs.Component;
import android.content.Context;
import android.widget.ListView;
/**
* Created by wilsonsouza on 3/2/17.
*/
public class CustomListView extends LinearVertical
{
public ListView Data = null;
//-----------------------------------------------------------------------------------------------------------------//
public CustomListView(Context context)
{
super(context);
this.Data = new ListView(this.getContext());
this.addView(this.Data, this.Params);
}
//-----------------------------------------------------------------------------------------------------------------//
}
| 23.8125 | 120 | 0.469816 |
60a39b612c205b86a4a3f690c8db04e2bfe40571 | 5,871 | /*****************************************************************
* 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
* <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 org.apache.cayenne.dba.ingres;
import org.apache.cayenne.CayenneRuntimeException;
import org.apache.cayenne.access.DataNode;
import org.apache.cayenne.access.translator.ParameterBinding;
import org.apache.cayenne.access.translator.select.QualifierTranslator;
import org.apache.cayenne.access.translator.select.QueryAssembler;
import org.apache.cayenne.access.translator.select.SelectTranslator;
import org.apache.cayenne.access.translator.select.TrimmingQualifierTranslator;
import org.apache.cayenne.access.types.ExtendedType;
import org.apache.cayenne.access.types.ExtendedTypeFactory;
import org.apache.cayenne.access.types.ExtendedTypeMap;
import org.apache.cayenne.access.types.ValueObjectTypeRegistry;
import org.apache.cayenne.configuration.Constants;
import org.apache.cayenne.configuration.RuntimeProperties;
import org.apache.cayenne.dba.JdbcAdapter;
import org.apache.cayenne.dba.PkGenerator;
import org.apache.cayenne.dba.TypesMapping;
import org.apache.cayenne.di.Inject;
import org.apache.cayenne.map.DbAttribute;
import org.apache.cayenne.map.EntityResolver;
import org.apache.cayenne.query.Query;
import org.apache.cayenne.query.SQLAction;
import org.apache.cayenne.query.SelectQuery;
import org.apache.cayenne.resource.ResourceLocator;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;
/**
* DbAdapter implementation for <a
* href="http://opensource.ca.com/projects/ingres/">Ingres</a>. Sample
* connection settings to use with Ingres are shown below:
*
* <pre>
* ingres.jdbc.username = test
* ingres.jdbc.password = secret
* ingres.jdbc.url = jdbc:ingres://serverhostname:II7/cayenne
* ingres.jdbc.driver = ca.ingres.jdbc.IngresDriver
* </pre>
*/
public class IngresAdapter extends JdbcAdapter {
public static final String TRIM_FUNCTION = "TRIM";
public IngresAdapter(@Inject RuntimeProperties runtimeProperties,
@Inject(Constants.SERVER_DEFAULT_TYPES_LIST) List<ExtendedType> defaultExtendedTypes,
@Inject(Constants.SERVER_USER_TYPES_LIST) List<ExtendedType> userExtendedTypes,
@Inject(Constants.SERVER_TYPE_FACTORIES_LIST) List<ExtendedTypeFactory> extendedTypeFactories,
@Inject(Constants.SERVER_RESOURCE_LOCATOR) ResourceLocator resourceLocator,
@Inject ValueObjectTypeRegistry valueObjectTypeRegistry) {
super(runtimeProperties, defaultExtendedTypes, userExtendedTypes, extendedTypeFactories, resourceLocator, valueObjectTypeRegistry);
setSupportsUniqueConstraints(true);
setSupportsGeneratedKeys(true);
}
/**
* @since 4.0
*/
@Override
public SelectTranslator getSelectTranslator(SelectQuery<?> query, EntityResolver entityResolver) {
return new IngresSelectTranslator(query, this, entityResolver);
}
@Override
public QualifierTranslator getQualifierTranslator(QueryAssembler queryAssembler) {
return new IngresQualifierTranslator(queryAssembler);
}
@Override
public SQLAction getAction(Query query, DataNode node) {
return query.createSQLAction(new IngresActionBuilder(node));
}
@Override
protected void configureExtendedTypes(ExtendedTypeMap map) {
super.configureExtendedTypes(map);
map.registerType(new IngresCharType());
// configure boolean type to work with numeric columns
map.registerType(new IngresBooleanType());
}
/**
* @see JdbcAdapter#createPkGenerator()
*/
@Override
protected PkGenerator createPkGenerator() {
return new IngresPkGenerator(this);
}
@Override
public void bindParameter(PreparedStatement statement, ParameterBinding binding)
throws SQLException, Exception {
if (binding.getValue() == null && (binding.getJdbcType() == Types.BIT)) {
statement.setNull(binding.getStatementPosition(), Types.SMALLINT);
} else {
super.bindParameter(statement, binding);
}
}
@Override
public void createTableAppendColumn(StringBuffer buf, DbAttribute at) {
String[] types = externalTypesForJdbcType(at.getType());
if (types == null || types.length == 0) {
throw new CayenneRuntimeException("Undefined type for attribute '%s.%s': %s"
, at.getEntity().getFullyQualifiedName(), at.getName(), at.getType());
}
String type = types[0];
buf.append(quotingStrategy.quotedName(at)).append(' ').append(type);
// append size and precision (if applicable)
if (typeSupportsLength(at.getType())) {
int len = at.getMaxLength();
int scale = TypesMapping.isDecimal(at.getType()) ? at.getScale() : -1;
// sanity check
if (scale > len) {
scale = -1;
}
if (len > 0) {
buf.append('(').append(len);
if (scale >= 0) {
buf.append(", ").append(scale);
}
buf.append(')');
}
}
if (at.isGenerated()) {
buf.append(" GENERATED BY DEFAULT AS IDENTITY ");
}
// Ingres does not like "null" for non mandatory fields
if (at.isMandatory()) {
buf.append(" NOT NULL");
}
}
}
| 35.155689 | 133 | 0.735479 |
ffe6076962884840b8d40cabe9a573528a25235f | 471 | package com.central.common.lock;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 锁对象抽象
*
* @author zlt
* @date 2020/7/28
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@AllArgsConstructor
public class ZLock implements AutoCloseable {
@Getter
private final Object lock;
private final DistributedLock locker;
@Override
public void close() throws Exception {
locker.unlock(lock);
}
}
| 17.444444 | 45 | 0.685775 |
f96b0c71107cf1c4ac6c9a327e55eb9c49ec81af | 586 | package org.springframework.security.web.authentication.session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Uses {@code HttpServletRequest.changeSessionId()} to protect against session fixation
* attacks. This is the default implementation.
*
* @author Rob Winch
* @since 3.2
*/
public final class ChangeSessionIdAuthenticationStrategy extends AbstractSessionFixationProtectionStrategy {
@Override
HttpSession applySessionFixation(HttpServletRequest request) {
request.changeSessionId();
return request.getSession();
}
}
| 26.636364 | 108 | 0.802048 |
deb5c9366380aca4c42406d1390b6749ab0d7a43 | 295 | package obs.order;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
import java.util.*;
public interface Order extends EJBObject
{
public String addOrder(int userid, ArrayList items)
throws RemoteException;
public boolean cancelOrder(int ordid) throws RemoteException;
}
| 21.071429 | 63 | 0.789831 |
74b2457eb1ba118e0e1dc90253b1614c069034f1 | 1,940 | package net.sjava.appstore;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
/**
* Amazon Store class
*
* @author [email protected]
* @date Dec 10, 2014 2:04:02 PM
* @version 1.0.0
*/
public class AmazonStoreApp extends AppStore implements PublisherAppOpenable {
private static final String APPSTORE_URI = "amzn://apps/android?";
private static final String APP_URL = "https://www.amazon.com/gp/mas/dl/android?";
public static AmazonStoreApp newInstance() {
return new AmazonStoreApp();
}
@Override
public boolean isInstalled(Context ctx) {
return isAppInstalled(ctx, PACKAGE_NAME_AMAZON);
}
@Override
public void openApp(Context ctx, String uniqueId) {
if(isInstalled(ctx)) {
try {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APPSTORE_URI + "p=" + uniqueId));
ctx.startActivity(intent);
return;
} catch (ActivityNotFoundException e) { // ignore
}
}
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_URL + "p=" + uniqueId));
ctx.startActivity(intent);
}
@Override
public void searchApp(Context ctx, String keyword) {
if(isInstalled(ctx)) {
try {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APPSTORE_URI +"s=" + keyword));
ctx.startActivity(intent);
return;
} catch (ActivityNotFoundException e) { // ignore
}
}
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_URL + "s="+ keyword));
ctx.startActivity(intent);
}
@Override
public void openPublisherApps(Context ctx, String key) {
if(isInstalled(ctx)) {
try {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APPSTORE_URI + "p=" + key +"&showAll=1"));
ctx.startActivity(intent);
return;
} catch (ActivityNotFoundException e) { // ignore
}
}
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_URL + "p=" + key +"&showAll=1"));
ctx.startActivity(intent);
}
}
| 26.575342 | 96 | 0.700515 |
9c41146dcd62f7c0449ef7b74c1558003657b2c4 | 5,610 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.refactoring.java.plugins;
import com.sun.source.tree.*;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import java.util.Iterator;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.type.TypeMirror;
import org.netbeans.api.java.source.ElementUtilities;
import org.netbeans.api.java.source.GeneratorUtilities;
import org.netbeans.modules.refactoring.java.spi.RefactoringVisitor;
/**
*
* @author Ralph Ruijs
*/
public class InlineVariableTransformer extends RefactoringVisitor {
@Override
public Tree visitIdentifier(IdentifierTree node, Element p) {
replaceUsageIfMatch(getCurrentPath(), node, p);
return super.visitIdentifier(node, p);
}
@Override
public Tree visitMemberSelect(MemberSelectTree node, Element p) {
replaceUsageIfMatch(getCurrentPath(), node, p);
return super.visitMemberSelect(node, p);
}
private void replaceUsageIfMatch(TreePath path, Tree tree, Element elementToFind) {
if (workingCopy.getTreeUtilities().isSynthetic(path)) {
return;
}
Trees trees = workingCopy.getTrees();
Element el = workingCopy.getTrees().getElement(path);
if (el == null) {
path = path.getParentPath();
if (path != null && path.getLeaf().getKind() == Tree.Kind.IMPORT) {
ImportTree impTree = (ImportTree) path.getLeaf();
if (!impTree.isStatic()) {
return;
}
Tree idTree = impTree.getQualifiedIdentifier();
if (idTree.getKind() != Tree.Kind.MEMBER_SELECT) {
return;
}
final Name id = ((MemberSelectTree) idTree).getIdentifier();
if (id == null || id.contentEquals("*")) { // NOI18N
// skip import static java.lang.Math.*
return;
}
Tree classTree = ((MemberSelectTree) idTree).getExpression();
path = trees.getPath(workingCopy.getCompilationUnit(), classTree);
el = trees.getElement(path);
if (el == null) {
return;
}
Iterator<? extends Element> iter = workingCopy.getElementUtilities().getMembers(el.asType(), new ElementUtilities.ElementAcceptor() {
@Override
public boolean accept(Element e, TypeMirror type) {
return id.equals(e.getSimpleName());
}
}).iterator();
if (iter.hasNext()) {
el = iter.next();
}
if (iter.hasNext()) {
return;
}
} else {
return;
}
}
if (el.equals(elementToFind)) {
GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy);
TreePath resolvedPath = trees.getPath(elementToFind);
VariableTree varTree = (VariableTree)resolvedPath.getLeaf();
varTree = genUtils.importComments(varTree, resolvedPath.getCompilationUnit());
ExpressionTree body = varTree.getInitializer();
boolean parenthesize = OperatorPrecedence.needsParentheses(path, elementToFind, varTree.getInitializer(), workingCopy);
if (parenthesize) {
body = make.Parenthesized((ExpressionTree) body);
}
genUtils.copyComments(varTree, body, true);
rewrite(tree, body);
}
}
@Override
public Tree visitVariable(VariableTree node, Element p) {
Element el = workingCopy.getTrees().getElement(getCurrentPath());
if (p.equals(el)) {
Tree parent = getCurrentPath().getParentPath().getLeaf();
switch(el.getKind()) {
case LOCAL_VARIABLE:
Tree newOne = null;
if(parent.getKind() == Tree.Kind.CASE) {
newOne = make.removeCaseStatement((CaseTree) parent, node);
} else {
newOne = make.removeBlockStatement((BlockTree) parent, node);
}
if (newOne != null) {
rewrite(parent, newOne);
}
break;
case FIELD:
ClassTree removeClassMember = make.removeClassMember((ClassTree)parent, node);
if (removeClassMember != null) {
rewrite(parent, removeClassMember);
}
break;
}
}
return super.visitVariable(node, p);
}
}
| 40.071429 | 149 | 0.581462 |
0aa3a157167fd7466de8851d69509943a57a7884 | 5,295 | /*
* MIT License
*
* Copyright (c) 2018 CUTBOSS
*
* 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 cutboss.support.dialog;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import java.io.Serializable;
/**
* SingleChoiceDialog.
*
* @author CUTBOSS
*/
public class SingleChoiceDialog extends DialogFragment {
/** TAG */
public static final String TAG = SingleChoiceDialog.class.getSimpleName();
/** KEY */
public static final String KEY_ITEMS = "items";
public static final String KEY_CHECKED_ITEM = "checked_item";
public static final String KEY_LISTENER = "listener";
/**
* Default constructor.
*/
public SingleChoiceDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Log.d(TAG, "onCreateDialog: start");
// get arguments
Bundle args = getArguments();
Log.d(TAG, "onCreateDialog: args: " + args);
CharSequence[] items;
int checkedItem;
final OnClickListener listener;
if (null != args) {
// get items
if (args.containsKey(KEY_ITEMS)) {
items = args.getCharSequenceArray(KEY_ITEMS);
} else {
throw new IllegalArgumentException("Items no exist.");
}
// get checked item
if (args.containsKey(KEY_CHECKED_ITEM)) {
checkedItem = args.getInt(KEY_CHECKED_ITEM, 0);
} else {
checkedItem = 0;
}
Log.d(TAG, "onCreateDialog: checkedItem: " + checkedItem);
// get listener
if (args.containsKey(KEY_LISTENER)) {
listener = (OnClickListener) args.getSerializable(KEY_LISTENER);
} else {
listener = null;
}
Log.d(TAG, "onCreateDialog: listener: " + listener);
} else {
throw new IllegalArgumentException("Args no exist.");
}
// create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "onClick: start");
Log.d(TAG, "onClick: which: " + which);
// listen?
Log.d(TAG, "onClick: listener: " + listener);
if (null != listener) {
// get tag
String tag = getTag();
Log.d(TAG, "onClick: tag: " + tag);
// item click
listener.onItemClick(tag, which);
}
// dismiss
dismiss();
Log.d(TAG, "onClick: end");
}
});
return builder.create();
}
/**
* OnClickListener.
*/
public interface OnClickListener extends Serializable {
void onItemClick(String tag, int which);
}
/**
* Set the OnClickListener.
*
* @param listener OnClickListener
* @return SingleChoiceDialog
*/
public SingleChoiceDialog setOnClickListener(OnClickListener listener) {
Log.d(TAG, "setOnClickListener: start");
Log.d(TAG, "setOnClickListener: listener: " + listener);
// is null?
if (null == listener) {
return this;
}
// set args
Bundle args = new Bundle();
args.putSerializable(KEY_LISTENER, listener);
setArguments(args);
Log.d(TAG, "setOnClickListener: args: " + args);
Log.d(TAG, "setOnClickListener: end");
return this;
}
@Override
public void setArguments(Bundle args) {
Log.d(TAG, "setArguments: start");
Log.d(TAG, "setArguments: args: " + args);
// get args
if (null != getArguments()) {
args.putAll(getArguments());
}
// set args
Log.d(TAG, "setArguments: args: " + args);
super.setArguments(args);
Log.d(TAG, "setArguments: end");
}
} | 31.706587 | 96 | 0.599056 |
374c6570ef41a9701be13d07aa0f7cdc73601b65 | 17,495 | package mk.ukim.finki.location.web.rest;
import mk.ukim.finki.location.LocationApp;
import mk.ukim.finki.location.domain.Place;
import mk.ukim.finki.location.repository.PlaceRepository;
import mk.ukim.finki.location.service.PlaceService;
import mk.ukim.finki.location.web.rest.errors.ExceptionTranslator;
import mk.ukim.finki.location.service.dto.PlaceCriteria;
import mk.ukim.finki.location.service.PlaceQueryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.util.List;
import static mk.ukim.finki.location.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the PlaceResource REST controller.
*
* @see PlaceResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LocationApp.class)
public class PlaceResourceIntTest {
private static final String DEFAULT_NAME = "AAAAAAAAAA";
private static final String UPDATED_NAME = "BBBBBBBBBB";
private static final String DEFAULT_ADDRESS_LINE = "AAAAAAAAAA";
private static final String UPDATED_ADDRESS_LINE = "BBBBBBBBBB";
private static final BigDecimal DEFAULT_POS_X = new BigDecimal(1);
private static final BigDecimal UPDATED_POS_X = new BigDecimal(2);
private static final BigDecimal DEFAULT_POS_Y = new BigDecimal(1);
private static final BigDecimal UPDATED_POS_Y = new BigDecimal(2);
@Autowired
private PlaceRepository placeRepository;
@Autowired
private PlaceService placeService;
@Autowired
private PlaceQueryService placeQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restPlaceMockMvc;
private Place place;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final PlaceResource placeResource = new PlaceResource(placeService, placeQueryService);
this.restPlaceMockMvc = MockMvcBuilders.standaloneSetup(placeResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Place createEntity(EntityManager em) {
Place place = new Place()
.name(DEFAULT_NAME)
.addressLine(DEFAULT_ADDRESS_LINE)
.posX(DEFAULT_POS_X)
.posY(DEFAULT_POS_Y);
return place;
}
@Before
public void initTest() {
place = createEntity(em);
}
@Test
@Transactional
public void createPlace() throws Exception {
int databaseSizeBeforeCreate = placeRepository.findAll().size();
// Create the Place
restPlaceMockMvc.perform(post("/api/places")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(place)))
.andExpect(status().isCreated());
// Validate the Place in the database
List<Place> placeList = placeRepository.findAll();
assertThat(placeList).hasSize(databaseSizeBeforeCreate + 1);
Place testPlace = placeList.get(placeList.size() - 1);
assertThat(testPlace.getName()).isEqualTo(DEFAULT_NAME);
assertThat(testPlace.getAddressLine()).isEqualTo(DEFAULT_ADDRESS_LINE);
assertThat(testPlace.getPosX()).isEqualTo(DEFAULT_POS_X);
assertThat(testPlace.getPosY()).isEqualTo(DEFAULT_POS_Y);
}
@Test
@Transactional
public void createPlaceWithExistingId() throws Exception {
int databaseSizeBeforeCreate = placeRepository.findAll().size();
// Create the Place with an existing ID
place.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restPlaceMockMvc.perform(post("/api/places")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(place)))
.andExpect(status().isBadRequest());
// Validate the Place in the database
List<Place> placeList = placeRepository.findAll();
assertThat(placeList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllPlaces() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList
restPlaceMockMvc.perform(get("/api/places?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(place.getId().intValue())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
.andExpect(jsonPath("$.[*].addressLine").value(hasItem(DEFAULT_ADDRESS_LINE.toString())))
.andExpect(jsonPath("$.[*].posX").value(hasItem(DEFAULT_POS_X.intValue())))
.andExpect(jsonPath("$.[*].posY").value(hasItem(DEFAULT_POS_Y.intValue())));
}
@Test
@Transactional
public void getPlace() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get the place
restPlaceMockMvc.perform(get("/api/places/{id}", place.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(place.getId().intValue()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()))
.andExpect(jsonPath("$.addressLine").value(DEFAULT_ADDRESS_LINE.toString()))
.andExpect(jsonPath("$.posX").value(DEFAULT_POS_X.intValue()))
.andExpect(jsonPath("$.posY").value(DEFAULT_POS_Y.intValue()));
}
@Test
@Transactional
public void getAllPlacesByNameIsEqualToSomething() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where name equals to DEFAULT_NAME
defaultPlaceShouldBeFound("name.equals=" + DEFAULT_NAME);
// Get all the placeList where name equals to UPDATED_NAME
defaultPlaceShouldNotBeFound("name.equals=" + UPDATED_NAME);
}
@Test
@Transactional
public void getAllPlacesByNameIsInShouldWork() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where name in DEFAULT_NAME or UPDATED_NAME
defaultPlaceShouldBeFound("name.in=" + DEFAULT_NAME + "," + UPDATED_NAME);
// Get all the placeList where name equals to UPDATED_NAME
defaultPlaceShouldNotBeFound("name.in=" + UPDATED_NAME);
}
@Test
@Transactional
public void getAllPlacesByNameIsNullOrNotNull() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where name is not null
defaultPlaceShouldBeFound("name.specified=true");
// Get all the placeList where name is null
defaultPlaceShouldNotBeFound("name.specified=false");
}
@Test
@Transactional
public void getAllPlacesByAddressLineIsEqualToSomething() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where addressLine equals to DEFAULT_ADDRESS_LINE
defaultPlaceShouldBeFound("addressLine.equals=" + DEFAULT_ADDRESS_LINE);
// Get all the placeList where addressLine equals to UPDATED_ADDRESS_LINE
defaultPlaceShouldNotBeFound("addressLine.equals=" + UPDATED_ADDRESS_LINE);
}
@Test
@Transactional
public void getAllPlacesByAddressLineIsInShouldWork() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where addressLine in DEFAULT_ADDRESS_LINE or UPDATED_ADDRESS_LINE
defaultPlaceShouldBeFound("addressLine.in=" + DEFAULT_ADDRESS_LINE + "," + UPDATED_ADDRESS_LINE);
// Get all the placeList where addressLine equals to UPDATED_ADDRESS_LINE
defaultPlaceShouldNotBeFound("addressLine.in=" + UPDATED_ADDRESS_LINE);
}
@Test
@Transactional
public void getAllPlacesByAddressLineIsNullOrNotNull() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where addressLine is not null
defaultPlaceShouldBeFound("addressLine.specified=true");
// Get all the placeList where addressLine is null
defaultPlaceShouldNotBeFound("addressLine.specified=false");
}
@Test
@Transactional
public void getAllPlacesByPosXIsEqualToSomething() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where posX equals to DEFAULT_POS_X
defaultPlaceShouldBeFound("posX.equals=" + DEFAULT_POS_X);
// Get all the placeList where posX equals to UPDATED_POS_X
defaultPlaceShouldNotBeFound("posX.equals=" + UPDATED_POS_X);
}
@Test
@Transactional
public void getAllPlacesByPosXIsInShouldWork() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where posX in DEFAULT_POS_X or UPDATED_POS_X
defaultPlaceShouldBeFound("posX.in=" + DEFAULT_POS_X + "," + UPDATED_POS_X);
// Get all the placeList where posX equals to UPDATED_POS_X
defaultPlaceShouldNotBeFound("posX.in=" + UPDATED_POS_X);
}
@Test
@Transactional
public void getAllPlacesByPosXIsNullOrNotNull() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where posX is not null
defaultPlaceShouldBeFound("posX.specified=true");
// Get all the placeList where posX is null
defaultPlaceShouldNotBeFound("posX.specified=false");
}
@Test
@Transactional
public void getAllPlacesByPosYIsEqualToSomething() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where posY equals to DEFAULT_POS_Y
defaultPlaceShouldBeFound("posY.equals=" + DEFAULT_POS_Y);
// Get all the placeList where posY equals to UPDATED_POS_Y
defaultPlaceShouldNotBeFound("posY.equals=" + UPDATED_POS_Y);
}
@Test
@Transactional
public void getAllPlacesByPosYIsInShouldWork() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where posY in DEFAULT_POS_Y or UPDATED_POS_Y
defaultPlaceShouldBeFound("posY.in=" + DEFAULT_POS_Y + "," + UPDATED_POS_Y);
// Get all the placeList where posY equals to UPDATED_POS_Y
defaultPlaceShouldNotBeFound("posY.in=" + UPDATED_POS_Y);
}
@Test
@Transactional
public void getAllPlacesByPosYIsNullOrNotNull() throws Exception {
// Initialize the database
placeRepository.saveAndFlush(place);
// Get all the placeList where posY is not null
defaultPlaceShouldBeFound("posY.specified=true");
// Get all the placeList where posY is null
defaultPlaceShouldNotBeFound("posY.specified=false");
}
/**
* Executes the search, and checks that the default entity is returned
*/
private void defaultPlaceShouldBeFound(String filter) throws Exception {
restPlaceMockMvc.perform(get("/api/places?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(place.getId().intValue())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
.andExpect(jsonPath("$.[*].addressLine").value(hasItem(DEFAULT_ADDRESS_LINE.toString())))
.andExpect(jsonPath("$.[*].posX").value(hasItem(DEFAULT_POS_X.intValue())))
.andExpect(jsonPath("$.[*].posY").value(hasItem(DEFAULT_POS_Y.intValue())));
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultPlaceShouldNotBeFound(String filter) throws Exception {
restPlaceMockMvc.perform(get("/api/places?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
}
@Test
@Transactional
public void getNonExistingPlace() throws Exception {
// Get the place
restPlaceMockMvc.perform(get("/api/places/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updatePlace() throws Exception {
// Initialize the database
placeService.save(place);
int databaseSizeBeforeUpdate = placeRepository.findAll().size();
// Update the place
Place updatedPlace = placeRepository.findById(place.getId()).get();
// Disconnect from session so that the updates on updatedPlace are not directly saved in db
em.detach(updatedPlace);
updatedPlace
.name(UPDATED_NAME)
.addressLine(UPDATED_ADDRESS_LINE)
.posX(UPDATED_POS_X)
.posY(UPDATED_POS_Y);
restPlaceMockMvc.perform(put("/api/places")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedPlace)))
.andExpect(status().isOk());
// Validate the Place in the database
List<Place> placeList = placeRepository.findAll();
assertThat(placeList).hasSize(databaseSizeBeforeUpdate);
Place testPlace = placeList.get(placeList.size() - 1);
assertThat(testPlace.getName()).isEqualTo(UPDATED_NAME);
assertThat(testPlace.getAddressLine()).isEqualTo(UPDATED_ADDRESS_LINE);
assertThat(testPlace.getPosX()).isEqualTo(UPDATED_POS_X);
assertThat(testPlace.getPosY()).isEqualTo(UPDATED_POS_Y);
}
@Test
@Transactional
public void updateNonExistingPlace() throws Exception {
int databaseSizeBeforeUpdate = placeRepository.findAll().size();
// Create the Place
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restPlaceMockMvc.perform(put("/api/places")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(place)))
.andExpect(status().isBadRequest());
// Validate the Place in the database
List<Place> placeList = placeRepository.findAll();
assertThat(placeList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deletePlace() throws Exception {
// Initialize the database
placeService.save(place);
int databaseSizeBeforeDelete = placeRepository.findAll().size();
// Get the place
restPlaceMockMvc.perform(delete("/api/places/{id}", place.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Place> placeList = placeRepository.findAll();
assertThat(placeList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Place.class);
Place place1 = new Place();
place1.setId(1L);
Place place2 = new Place();
place2.setId(place1.getId());
assertThat(place1).isEqualTo(place2);
place2.setId(2L);
assertThat(place1).isNotEqualTo(place2);
place1.setId(null);
assertThat(place1).isNotEqualTo(place2);
}
}
| 37.950108 | 105 | 0.69397 |
15d781b72b3453edfba62b7b9026336ef58e5744 | 2,765 | /*
* 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 org.kie.container.services.endpoint.api;
import org.kie.container.services.endpoint.exception.BusinessException;
import java.util.List;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.kie.container.services.info.ContainerInstanceProviderInfo;
import org.kie.container.spi.model.ContainerInstanceInfo;
import org.kie.container.spi.model.base.BaseContainerInstanceConfiguration;
import org.kie.container.spi.model.providers.base.BaseContainerProviderConfiguration;
import org.kie.container.spi.model.providers.info.ContainerProviderInfo;
/**
*
* @author salaboy
*/
@Path("containers")
public interface ContainerManagerService {
@GET
@Produces(value = MediaType.APPLICATION_JSON)
@Path("providers")
List<ContainerProviderInfo> getAllContainerProviders() throws BusinessException;
@GET
@Produces(value = MediaType.APPLICATION_JSON)
@Path("providers/instances")
List<ContainerInstanceProviderInfo> getAllContainerProvidersInstances() throws BusinessException;
@POST
@Consumes(value = MediaType.APPLICATION_JSON)
@Path("providers/instances")
void registerContainerProviderInstance(@NotNull BaseContainerProviderConfiguration conf) throws BusinessException;
@DELETE
@Path("providers/instances")
void unregisterContainerProviderInstance(@FormParam(value = "name") String name) throws BusinessException;
@POST
@Path("instances/")
@Consumes(value = MediaType.APPLICATION_JSON)
public String newContainerInstance(@NotNull BaseContainerInstanceConfiguration conf) throws BusinessException;
@GET
@Produces("application/json")
@Path("instances/")
public List<ContainerInstanceInfo> getAllContainerInstances() throws BusinessException;
@DELETE
@Path("instances/{id}")
public void removeContainerInstance(@PathParam(value = "id") String id) throws BusinessException;
@POST
@Path("instances/{id}/start")
public void startContainerInstance(@PathParam(value = "id") String id) throws BusinessException;
@POST
@Path("instances/{id}/stop")
public void stopContainerInstance(@PathParam(value = "id") String id) throws BusinessException;
@POST
@Path("instances/{id}/restart")
public void restartContainerInstance(@PathParam(value = "id") String id) throws BusinessException;
}
| 35 | 118 | 0.769982 |
da0ae7e162036926fdeb607ca42408267343a8a3 | 2,081 | /**
*
*/
package features.keyboard;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeSet;
import extractors.data.Answer;
import extractors.data.DataNode;
import extractors.data.ExtractionModule;
import extractors.data.Feature;
import features.pause.KSE;
/**
* @author agoodkind
* Generate a list of lag times before each of 5 fingers
*/
public class FingerSpeed implements ExtractionModule{
private final Set<String> fingerNames = new HashSet<String>(Arrays.asList("Pinky_Finger","Ring_Finger","Middle_Finger","Index_Finger","Thumb_Finger"));
private Set<String> searchSpace = new TreeSet<String>();
private HashMap<String, LinkedList<Long>> featureMap = new HashMap<String, LinkedList<Long>>();
public FingerSpeed() {
searchSpace.clear();
featureMap.clear();
generateSearchSpace();
}
public void generateSearchSpace() {
for (String finger : fingerNames)
searchSpace.add(finger);
}
@Override
public Collection<Feature> extract(DataNode data) {
for (String s : searchSpace) // create feature
featureMap.put(s, new LinkedList<Long>()); // add a LinkedList for each String in searchSpace
for (Answer a : data) {
Collection<KSE> kseArray = KSE.parseSessionToKSE(a.getKeyStrokes()); // create KSE array from KeyStrokes
for (KSE kse : kseArray) {
if (kse.isKeyPress()) // only look at KeyPresses
if (searchSpace.contains(kse.kseGetFinger()))
featureMap.get(kse.kseGetFinger()).add(kse.getM_pauseMs()); // add to Feature Map
}
}
//create output feature list
LinkedList<Feature> output = new LinkedList<Feature>();
//iterate over the featureMap using searchSpace because it is auto-sorted by TreeSet class.
for (String s : searchSpace)
output.add(new Feature("Speed_"+s, featureMap.get(s)));
// for (Feature f : output) System.out.println(f.toTemplate());
return output;
}
@Override
public String getName() {
return "Finger_Speed";
}
}
| 28.902778 | 152 | 0.720327 |
b9fd4199baca51f2b1e95ce7fe01f2214f1f7e58 | 584 | package com.grantburgess.creditprovider.provider1;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Provider2Response {
private String cardName;
private String url;
private BigDecimal apr;
private BigDecimal eligibility;
private List<String> features;
} | 25.391304 | 62 | 0.782534 |
0069737141ed6f1255329deff379a5f045ff6c68 | 7,325 | /*
* Copyright 2022 Kiritron's Space
*
* 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 space.kiritron.pixel.compressors;
import space.kiritron.pixel.filefunc.DirControls;
import space.kiritron.pixel.filefunc.FileControls;
import space.kiritron.pixel.filefunc.GetPathOfAPP;
import space.kiritron.pixel.console.toConsole;
import java.io.*;
import java.nio.file.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* @author Киритрон Стэйблкор & Mkyong
*/
public class Zip {
/**
* Архивировать файл в ZIP архив.
* @param source Адрес файла.
* @param nameZipFile Адрес архива. Обратите внимание, что данный метод может заменить уже существующий архив.
*/
public static void zipFile(String source, String nameZipFile) throws Exception {
zipping(source, nameZipFile);
}
/**
* Архивировать директорию в ZIP архив.
* @param source Адрес директории.
* @param nameZipFile Адрес архива. Обратите внимание, что данный метод может заменить уже существующий архив.
*/
public static void zipDir(String source, String nameZipFile) throws Exception {
zipping(source, nameZipFile);
}
/**
* Архивировать несколько элементов(файлы и папки) в ZIP архив.
* @param sources Массив адресов файлов и папок.
* @param nameZipFile Адрес архива. Обратите внимание, что данный метод может заменить уже существующий архив.
*/
public static void zipMultipleElements(String[] sources, String nameZipFile) throws Exception {
zipping(sources, nameZipFile);
}
/**
* Распаковать ZIP архив.
* @param zipFileName Адрес архива.
* @param dirName Адрес директории, в которую будет распаковано содержимое архива.
*/
public static void unzipFile(String zipFileName, String dirName) throws IOException {
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName))) {
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
boolean isDirectory = false;
// Киритрон: ...вот об этом фрагменте речь
if (zipEntry.getName().endsWith(GetPathOfAPP.GetSep())) {
isDirectory = true;
}
// Киритрон: Фрагмент выше от Mkyong, как мне показалось, работает недостаточно хорошо, если вообще работает.
// Проблема была в том, что он плохо определял, с каталогом имеется дело или нет, из-за чего
// распаковка архивов с каталогами внутри была проблематичной.
if (zipEntry.isDirectory()) {
isDirectory = true;
}
Path newPath = zipSlipProtect(zipEntry, Paths.get(dirName));
if (isDirectory) {
Files.createDirectories(newPath);
} else {
if (newPath.getParent() != null) {
if (Files.notExists(newPath.getParent())) {
Files.createDirectories(newPath.getParent());
}
}
try (FileOutputStream fos = new FileOutputStream(newPath.toFile())) {
byte[] buffer = new byte[4096];
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
}
}
private static void zipping(String source, String nameZipFile) throws Exception {
FileOutputStream fos = new FileOutputStream(nameZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
if (FileControls.isFile(source) && !DirControls.isDir(source)) {
FileInputStream fis = new FileInputStream(source);
zos.putNextEntry(new ZipEntry(source));
byte[] buffer = new byte[4096];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
} else if (!FileControls.isFile(source) && DirControls.isDir(source)) {
scanDirectory(zos, new File(source));
} else {
throw new IOException("Это не файл и не каталог. Непонятно, что с этим делать.");
}
zos.closeEntry();
zos.close();
}
private static void zipping(String[] sources, String nameZipFile) throws Exception {
FileOutputStream fos = new FileOutputStream(nameZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (int i = 0; i < sources.length;) {
if (FileControls.isFile(sources[i]) && !DirControls.isDir(sources[i])) {
FileInputStream fis = new FileInputStream(sources[i]);
zos.putNextEntry(new ZipEntry(sources[i]));
byte[] buffer = new byte[4096];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
} else if (!FileControls.isFile(sources[i]) && DirControls.isDir(sources[i])) {
scanDirectory(zos, new File(sources[i]));
} else {
toConsole.println_error("Это не файл и не каталог. Непонятно, что с этим делать.");
// throw new IOException("Это не файл и не каталог. Непонятно, что с этим делать.");
}
i++;
}
zos.closeEntry();
zos.close();
}
private static Path zipSlipProtect(ZipEntry zipEntry, Path targetDir) throws IOException {
Path targetDirResolved = targetDir.resolve(zipEntry.getName());
Path normalizePath = targetDirResolved.normalize();
if (!normalizePath.startsWith(targetDir)) {
throw new IOException("Плохая запись в ZIP - " + zipEntry.getName());
}
return normalizePath;
}
private static void scanDirectory(ZipOutputStream zos, File fileSource) throws Exception {
File[] files = fileSource.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
scanDirectory(zos, files[i]);
continue;
}
FileInputStream fis = new FileInputStream(files[i]);
zos.putNextEntry(new ZipEntry(files[i].getPath()));
byte[] buffer = new byte[4096];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
}
}
}
| 36.083744 | 125 | 0.591126 |
02ea56ab261dfbb610488ee576e7253b2ac47c92 | 752 | package util;
/**
* Exception to be thrown when an integer does not have an inverse.
*
* @author Ashkan Moatamed
*/
public class UndefinedInverseException extends ArithmeticException {
/**
* No dependencies.
*/
/**
* Eclipse automatically generated serial version UID.
*/
private static final long serialVersionUID = 4787475305008371946L;
/**
* Constructs an <code>UndefinedInverseException</code> with no detail message.
*/
public UndefinedInverseException() {
super();
}
/**
* Constructs an <code>UndefinedInverseException</code> with the specified detail message.
*
* @param s
* the detail message
*/
public UndefinedInverseException(String s) {
super(s);
}
}
| 21.485714 | 92 | 0.667553 |
b0ba0d4b5e87433df9bb72fd7f91c3943a5fd50e | 192 | package org.xxpay.shop.module.service;
import org.xxpay.shop.module.modle.Machine;
public interface MachineService {
Machine findByImei(String imei);
void doSave(Machine terminal);
}
| 24 | 43 | 0.776042 |
6bd5ead02d32af35f0291bde1b3e949cda6dfc1c | 7,463 | package main;
import exceptions.InvalidFormatException;
import exceptions.InvalidHashException;
import exceptions.InvalidPublicKeyException;
import org.json.simple.parser.ParseException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PublicKey;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException, ParseException, GeneralSecurityException, InvalidFormatException {
final double VERSION = 1.0;
System.out.println("JCERT v" + VERSION);
Scanner scanner = new Scanner(System.in);
KeyManager keyManager = new KeyManager();
while(true) {
System.out.println("""
Please select a choice:
0. Exit
1. Open JCERT file
2. Create a new JCERT file
3. Generate new keys
""");
System.out.print("Choice: ");
String choice = scanner.nextLine();
switch (choice) {
case "0" -> System.exit(0);
case "1" -> openCert(scanner);
case "2" -> createCert(scanner, keyManager);
case "3" -> generateKeys(scanner, keyManager);
default -> System.out.println("Invalid choice\n");
}
}
}
public static void openCert(Scanner scanner) throws IOException, ParseException, GeneralSecurityException {
System.out.print("Enter path to JCert file: ");
String path = scanner.nextLine();
CertFile certFile;
try {
certFile = new CertFile(path, true);
} catch (FileNotFoundException e) {
System.out.println("Error: File not found");
return;
} catch (IOException e) {
System.out.println("Error: Path specified is either invalid or there was an error reading from the file");
return;
} catch (InvalidFormatException e) {
System.out.println("Error: File specified is in an invalid or unsupported format");
return;
}
PublicKey key;
if(PublicKeyManager.savedKeyExists(certFile.keyHash)) {
System.out.printf("""
Associated key for file is saved under name:
%s
""", PublicKeyManager.getSavedKeyName(certFile.keyHash));
while(true) {
System.out.print("Would you like to continue opening this file? (Y/N): ");
String choice = scanner.nextLine();
if(choice.equalsIgnoreCase("N")) {
return;
} else if (choice.equalsIgnoreCase("Y")) {
break;
} else {
System.out.println("Invalid choice");
}
}
key = PublicKeyManager.getSavedKey(certFile.keyHash);
} else {
while(true) {
System.out.print("Enter path to public key file associated with JCert file: ");
path = scanner.nextLine();
try {
key = PublicKeyManager.getKeyFromFile(new File(path));
break;
} catch (IOException e) {
System.out.println("Error: Path specified is either invalid or there was an error reading from the file");
} catch (IllegalArgumentException e) {
System.out.println("Error: Public key file is invalid");
}
}
}
try {
System.out.printf("JCert file verification successful. The opened file can be found at %s%n", certFile.openCertFile(key).getCanonicalPath());
if(!PublicKeyManager.savedKeyExists(certFile.keyHash)) {
while (true) {
System.out.print("Would you like to save this key? (Y/N): ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("Y")) {
System.out.print("Enter name of key issuer: ");
choice = scanner.nextLine();
PublicKeyManager.savePublicKey(key, choice);
System.out.println("Public key has been saved.");
break;
} else if (choice.equalsIgnoreCase("N")) {
break;
} else {
System.out.println("Invalid choice");
}
}
}
} catch (InvalidPublicKeyException e) {
System.out.println("The public key that was specified does not correspond to the certificate file");
} catch (InvalidHashException e) {
System.out.println("Verification failed - file tampering detected.");
}
}
public static void createCert(Scanner scanner, KeyManager keyManager) throws IOException, InvalidFormatException, GeneralSecurityException {
if(!keyManager.keyExists()) {
System.out.println("Error: public/private keys not found. Please generate them before creating jcert files.");
return;
}
keyManager.refreshKeys();
System.out.println("Please note that only plaintext and UTF-8 encoded files are supported in this version.");
System.out.print("Enter path to file: ");
File file = new File(scanner.nextLine());
if(!file.isFile()) {
System.out.println("Error: Specified path is invalid or file not found.");
return;
}
CertFile certFile = new CertFile("output" + File.separator + file.getName() + ".jcert", false);
certFile.createCertFile(keyManager, file);
System.out.printf("""
.jcert file has been successfully created at %s
Be sure to include your public key also, which is found at %s
""", certFile.getCanonicalPath(), new File(".").getCanonicalPath() + File.separator + "public.key");
}
public static void generateKeys(Scanner scanner, KeyManager keyManager) throws GeneralSecurityException, IOException {
if(keyManager.keyExists()) {
while (true) {
System.out.println("""
Warning: Continuing will overwrite existing keys.
Certificates generated in the past will no longer be verifiable without the old public key.
""");
System.out.print("Are you sure you want to continue? (Y/N): ");
String choice = scanner.nextLine();
if(choice.equalsIgnoreCase("Y")) {
break;
} else if(choice.equalsIgnoreCase("N")) {
return;
} else {
System.out.println("Invalid choice");
}
}
}
keyManager.generateKeys();
System.out.println("New key generation successful");
System.out.println("Never share your private key. Doing so poses the risk of others being able to send files as you.");
System.out.printf("Your public key can be found at %s%n", new File(".").getCanonicalPath() + File.separator + "public.key");
}
}
| 39.486772 | 153 | 0.553129 |
c3aea78a1498bc8dd84dfe7035ecea0a22471168 | 16,406 | /*
* Copyright (c) 2012-2014 Arne Schwabe
* Distributed under the GNU GPL v2. For full terms see the file doc/LICENSE.txt
*/
package de.blinkt.openvpn.core;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import de.blinkt.openvpn.R;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.FormatFlagsConversionMismatchException;
import java.util.LinkedList;
import java.util.Locale;
import java.util.UnknownFormatConversionException;
import java.util.Vector;
public class VpnStatus {
public static LinkedList<LogItem> logbuffer;
private static Vector<LogListener> logListener;
private static Vector<StateListener> stateListener;
private static Vector<ByteCountListener> byteCountListener;
private static String mLaststatemsg="";
private static String mLaststate = "NOPROCESS";
private static int mLastStateresid=R.string.state_noprocess;
private static long mlastByteCount[]={0,0,0,0};
public static void logException(LogLevel ll, String context, Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LogItem li;
if (context !=null) {
li = new LogItem(ll, R.string.unhandled_exception_context, e.getMessage(), sw.toString(), context);
} else {
li = new LogItem(ll, R.string.unhandled_exception, e.getMessage(), sw.toString());
}
newLogItem(li);
}
public static void logException(Exception e) {
logException(LogLevel.ERROR, null, e);
}
public static void logException(String context, Exception e) {
logException(LogLevel.ERROR, context, e);
}
private static final int MAXLOGENTRIES = 1000;
public static final String MANAGMENT_PREFIX = "M:";
public enum ConnectionStatus {
LEVEL_CONNECTED,
LEVEL_VPNPAUSED,
LEVEL_CONNECTING_SERVER_REPLIED,
LEVEL_CONNECTING_NO_SERVER_REPLY_YET,
LEVEL_NONETWORK,
LEVEL_NOTCONNECTED,
LEVEL_AUTH_FAILED,
LEVEL_WAITING_FOR_USER_INPUT,
UNKNOWN_LEVEL
}
public enum LogLevel {
INFO(2),
ERROR(-2),
WARNING(1),
VERBOSE(3),
DEBUG(4);
protected int mValue;
LogLevel(int value) {
mValue = value;
}
public int getInt() {
return mValue;
}
public static LogLevel getEnumByValue(int value) {
switch (value) {
case 1: return INFO;
case 2: return ERROR;
case 3: return WARNING;
case 4: return DEBUG;
default: return null;
}
}
}
// keytool -printcert -jarfile de.blinkt.openvpn_85.apk
public static final byte[] officalkey = {-58, -42, -44, -106, 90, -88, -87, -88, -52, -124, 84, 117, 66, 79, -112, -111, -46, 86, -37, 109};
public static final byte[] officaldebugkey = {-99, -69, 45, 71, 114, -116, 82, 66, -99, -122, 50, -70, -56, -111, 98, -35, -65, 105, 82, 43};
public static final byte[] amazonkey = {-116, -115, -118, -89, -116, -112, 120, 55, 79, -8, -119, -23, 106, -114, -85, -56, -4, 105, 26, -57};
public static final byte[] fdroidkey = {-92, 111, -42, -46, 123, -96, -60, 79, -27, -31, 49, 103, 11, -54, -68, -27, 17, 2, 121, 104};
private static ConnectionStatus mLastLevel=ConnectionStatus.LEVEL_NOTCONNECTED;
static {
logbuffer = new LinkedList<LogItem>();
logListener = new Vector<VpnStatus.LogListener>();
stateListener = new Vector<VpnStatus.StateListener>();
byteCountListener = new Vector<VpnStatus.ByteCountListener>();
logInformation();
}
public static class LogItem implements Parcelable {
private Object [] mArgs = null;
private String mMessage = null;
private int mRessourceId;
// Default log priority
LogLevel mLevel = LogLevel.INFO;
private long logtime = System.currentTimeMillis();
private int mVerbosityLevel = -1;
private LogItem(int ressourceId, Object[] args) {
mRessourceId = ressourceId;
mArgs = args;
}
public LogItem(LogLevel level, int verblevel, String message) {
mMessage=message;
mLevel = level;
mVerbosityLevel = verblevel;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeArray(mArgs);
dest.writeString(mMessage);
dest.writeInt(mRessourceId);
dest.writeInt(mLevel.getInt());
dest.writeInt(mVerbosityLevel);
dest.writeLong(logtime);
}
public LogItem(Parcel in) {
mArgs = in.readArray(Object.class.getClassLoader());
mMessage = in.readString();
mRessourceId = in.readInt();
mLevel = LogLevel.getEnumByValue(in.readInt());
mVerbosityLevel = in.readInt();
logtime = in.readLong();
}
public static final Parcelable.Creator<LogItem> CREATOR
= new Parcelable.Creator<LogItem>() {
public LogItem createFromParcel(Parcel in) {
return new LogItem(in);
}
public LogItem[] newArray(int size) {
return new LogItem[size];
}
};
public LogItem(LogLevel loglevel,int ressourceId, Object... args) {
mRessourceId = ressourceId;
mArgs =args;
mLevel = loglevel;
}
public LogItem(LogLevel loglevel, String msg) {
mLevel = loglevel;
mMessage = msg;
}
public LogItem(LogLevel loglevel, int ressourceId) {
mRessourceId =ressourceId;
mLevel = loglevel;
}
public String getString(Context c) {
try {
if(mMessage !=null) {
return mMessage;
} else {
if(c!=null) {
if(mRessourceId==R.string.mobile_info)
return getMobileInfoString(c);
if(mArgs == null)
return c.getString(mRessourceId);
else
return c.getString(mRessourceId,mArgs);
} else {
String str = String.format(Locale.ENGLISH,"Log (no context) resid %d", mRessourceId);
if(mArgs !=null)
for(Object o:mArgs)
str += "|" + o.toString();
return str;
}
}
} catch (UnknownFormatConversionException e) {
if (c != null)
throw new UnknownFormatConversionException(e.getLocalizedMessage() + getString(null));
else
throw e;
} catch (java.util.FormatFlagsConversionMismatchException e) {
if (c != null)
throw new FormatFlagsConversionMismatchException(e.getLocalizedMessage() + getString(null),e.getConversion());
else
throw e;
}
}
public LogLevel getLogLevel()
{
return mLevel;
}
// The lint is wrong here
@SuppressLint("StringFormatMatches")
private String getMobileInfoString(Context c) {
c.getPackageManager();
String apksign="error getting package signature";
String version="error getting version";
try {
Signature raw = c.getPackageManager().getPackageInfo(c.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray()));
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
if (Arrays.equals(digest, officalkey))
apksign = c.getString(R.string.official_build);
else if (Arrays.equals(digest, officaldebugkey))
apksign = c.getString(R.string.debug_build);
else if (Arrays.equals(digest, amazonkey))
apksign = "amazon version";
else if (Arrays.equals(digest, fdroidkey))
apksign = "F-Droid built and signed version";
else
apksign = c.getString(R.string.built_by,cert.getSubjectX500Principal().getName());
PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
version = packageinfo.versionName;
} catch (NameNotFoundException e) {
} catch (CertificateException e) {
} catch (NoSuchAlgorithmException e) {
}
Object[] argsext = Arrays.copyOf(mArgs, mArgs.length+2);
argsext[argsext.length-1]=apksign;
argsext[argsext.length-2]=version;
return c.getString(R.string.mobile_info_extended, argsext);
}
public long getLogtime() {
return logtime;
}
public int getVerbosityLevel() {
if (mVerbosityLevel==-1) {
// Hack:
// For message not from OpenVPN, report the status level as log level
return mLevel.getInt();
}
return mVerbosityLevel;
}
}
public interface LogListener {
void newLog(LogItem logItem);
}
public interface StateListener {
void updateState(String state, String logmessage, int localizedResId, ConnectionStatus level);
}
public interface ByteCountListener {
void updateByteCount(long in, long out, long diffIn, long diffOut);
}
public synchronized static void logMessage(LogLevel level,String prefix, String message)
{
newLogItem(new LogItem(level, prefix + message));
}
public synchronized static void clearLog() {
logbuffer.clear();
logInformation();
}
private static void logInformation() {
logInfo(R.string.mobile_info,Build.MODEL, Build.BOARD,Build.BRAND,Build.VERSION.SDK_INT);
}
public synchronized static void addLogListener(LogListener ll){
logListener.add(ll);
}
public synchronized static void removeLogListener(LogListener ll) {
logListener.remove(ll);
}
public synchronized static void addByteCountListener(ByteCountListener bcl) {
bcl.updateByteCount(mlastByteCount[0], mlastByteCount[1], mlastByteCount[2], mlastByteCount[3]);
byteCountListener.add(bcl);
}
public synchronized static void removeByteCountListener(ByteCountListener bcl) {
byteCountListener.remove(bcl);
}
public synchronized static void addStateListener(StateListener sl){
if(!stateListener.contains(sl)){
stateListener.add(sl);
if(mLaststate!=null)
sl.updateState(mLaststate, mLaststatemsg, mLastStateresid, mLastLevel);
}
}
private static int getLocalizedState(String state){
if (state.equals("CONNECTING"))
return R.string.state_connecting;
else if (state.equals("WAIT"))
return R.string.state_wait;
else if (state.equals("AUTH"))
return R.string.state_auth;
else if (state.equals("GET_CONFIG"))
return R.string.state_get_config;
else if (state.equals("ASSIGN_IP"))
return R.string.state_assign_ip;
else if (state.equals("ADD_ROUTES"))
return R.string.state_add_routes;
else if (state.equals("CONNECTED"))
return R.string.state_connected;
else if (state.equals("DISCONNECTED"))
return R.string.state_disconnected;
else if (state.equals("RECONNECTING"))
return R.string.state_reconnecting;
else if (state.equals("EXITING"))
return R.string.state_exiting;
else if (state.equals("RESOLVE"))
return R.string.state_resolve;
else if (state.equals("TCP_CONNECT"))
return R.string.state_tcp_connect;
else
return R.string.unknown_state;
}
public static void updateStatePause(OpenVPNManagement.pauseReason pauseReason) {
switch (pauseReason) {
case noNetwork:
VpnStatus.updateStateString("NONETWORK", "", R.string.state_nonetwork, ConnectionStatus.LEVEL_NONETWORK);
break;
case screenOff:
VpnStatus.updateStateString("SCREENOFF", "", R.string.state_screenoff, ConnectionStatus.LEVEL_VPNPAUSED);
break;
case userPause:
VpnStatus.updateStateString("USERPAUSE", "", R.string.state_userpause, ConnectionStatus.LEVEL_VPNPAUSED);
break;
}
}
private static ConnectionStatus getLevel(String state){
String[] noreplyet = {"CONNECTING","WAIT", "RECONNECTING", "RESOLVE", "TCP_CONNECT"};
String[] reply = {"AUTH","GET_CONFIG","ASSIGN_IP","ADD_ROUTES"};
String[] connected = {"CONNECTED"};
String[] notconnected = {"DISCONNECTED", "EXITING"};
for(String x:noreplyet)
if(state.equals(x))
return ConnectionStatus.LEVEL_CONNECTING_NO_SERVER_REPLY_YET;
for(String x:reply)
if(state.equals(x))
return ConnectionStatus.LEVEL_CONNECTING_SERVER_REPLIED;
for(String x:connected)
if(state.equals(x))
return ConnectionStatus.LEVEL_CONNECTED;
for(String x:notconnected)
if(state.equals(x))
return ConnectionStatus.LEVEL_NOTCONNECTED;
return ConnectionStatus.UNKNOWN_LEVEL;
}
public synchronized static void removeStateListener(StateListener sl) {
stateListener.remove(sl);
}
synchronized public static LogItem[] getlogbuffer() {
// The stoned way of java to return an array from a vector
// brought to you by eclipse auto complete
return logbuffer.toArray(new LogItem[logbuffer.size()]);
}
public static void updateStateString (String state, String msg) {
int rid = getLocalizedState(state);
ConnectionStatus level = getLevel(state);
updateStateString(state, msg, rid, level);
}
public synchronized static void updateStateString(String state, String msg, int resid, ConnectionStatus level) {
// Workound for OpenVPN doing AUTH and wait and being connected
// Simply ignore these state
if (mLastLevel == ConnectionStatus.LEVEL_CONNECTED &&
(state.equals("WAIT") || state.equals("AUTH")))
{
newLogItem(new LogItem((LogLevel.DEBUG), String.format("Ignoring OpenVPN Status in CONNECTED state (%s->%s): %s",state,level.toString(),msg)));
return;
}
mLaststate= state;
mLaststatemsg = msg;
mLastStateresid = resid;
mLastLevel = level;
for (StateListener sl : stateListener) {
sl.updateState(state,msg,resid,level);
}
//newLogItem(new LogItem((LogLevel.DEBUG), String.format("New OpenVPN Status (%s->%s): %s",state,level.toString(),msg)));
}
public static void logInfo(String message) {
newLogItem(new LogItem(LogLevel.INFO, message));
}
public static void logInfo(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.INFO, resourceId, args));
}
public static void logDebug(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.DEBUG, resourceId, args));
}
private synchronized static void newLogItem(LogItem logItem) {
logbuffer.addLast(logItem);
if(logbuffer.size()>MAXLOGENTRIES)
logbuffer.removeFirst();
for (LogListener ll : logListener) {
ll.newLog(logItem);
}
}
public static void logError(String msg) {
newLogItem(new LogItem(LogLevel.ERROR, msg));
}
public static void logWarning(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.WARNING, resourceId, args));
}
public static void logWarning(String msg) {
newLogItem(new LogItem(LogLevel.WARNING, msg));
}
public static void logError(int resourceId) {
newLogItem(new LogItem(LogLevel.ERROR, resourceId));
}
public static void logError(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.ERROR, resourceId, args));
}
public static void logMessageOpenVPN(LogLevel level, int ovpnlevel, String message) {
newLogItem(new LogItem(level, ovpnlevel, message));
}
public static synchronized void updateByteCount(long in, long out) {
long lastIn = mlastByteCount[0];
long lastOut = mlastByteCount[1];
long diffIn = mlastByteCount[2] = in - lastIn;
long diffOut = mlastByteCount[3] = out - lastOut;
mlastByteCount = new long[] {in,out,diffIn,diffOut};
for(ByteCountListener bcl:byteCountListener){
bcl.updateByteCount(in, out, diffIn,diffOut);
}
}
}
| 30.047619 | 155 | 0.677069 |
99eba89a38d3ec0e4d609f9f3acf2b2720597fd7 | 3,075 | package com.goboomtown.sdk.swagger.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.goboomtown.sdk.swagger.model.Member;
import com.goboomtown.sdk.swagger.model.MemberLocation;
import com.goboomtown.sdk.swagger.model.MemberUser;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-03-23T11:55:09.982-06:00")
public class MemberTuple {
private Member member = null;
private MemberUser memberUser = null;
private MemberLocation memberLocation = null;
/**
**/
public MemberTuple member(Member member) {
this.member = member;
return this;
}
@ApiModelProperty(example = "null", required = true, value = "")
@JsonProperty("member")
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
/**
**/
public MemberTuple memberUser(MemberUser memberUser) {
this.memberUser = memberUser;
return this;
}
@ApiModelProperty(example = "null", required = true, value = "")
@JsonProperty("member_user")
public MemberUser getMemberUser() {
return memberUser;
}
public void setMemberUser(MemberUser memberUser) {
this.memberUser = memberUser;
}
/**
**/
public MemberTuple memberLocation(MemberLocation memberLocation) {
this.memberLocation = memberLocation;
return this;
}
@ApiModelProperty(example = "null", required = true, value = "")
@JsonProperty("member_location")
public MemberLocation getMemberLocation() {
return memberLocation;
}
public void setMemberLocation(MemberLocation memberLocation) {
this.memberLocation = memberLocation;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MemberTuple memberTuple = (MemberTuple) o;
return Objects.equals(this.member, memberTuple.member) &&
Objects.equals(this.memberUser, memberTuple.memberUser) &&
Objects.equals(this.memberLocation, memberTuple.memberLocation);
}
@Override
public int hashCode() {
return Objects.hash(member, memberUser, memberLocation);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class MemberTuple {\n");
sb.append(" member: ").append(toIndentedString(member)).append("\n");
sb.append(" memberUser: ").append(toIndentedString(memberUser)).append("\n");
sb.append(" memberLocation: ").append(toIndentedString(memberLocation)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 25.204918 | 131 | 0.681951 |
1ce787db1f896c7021203b5d9d81f0ed7e9b7438 | 113 | package nodebox.graphics;
import java.awt.*;
public interface Drawable {
public void draw(Graphics2D g);
}
| 14.125 | 35 | 0.734513 |
9c87863f4c50887e8f67807e04d3fe7ce02dfaef | 451 | package de.mickare.armortools.permission;
import org.bukkit.Location;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public interface PermissionCheck {
public boolean canModify(Player player, ArmorStand armorstand);
default boolean canModify(Player player, Entity entity) {
return canBuild(player, entity.getLocation());
}
boolean canBuild(Player player, Location location);
}
| 23.736842 | 65 | 0.78714 |
a162155a16aba454aa988a6976acfa4667909b27 | 191 | //
// Decompiled by Procyon v0.5.36
//
package org.codehaus.groovy.antlr;
import groovyjarjarantlr.collections.AST;
public interface AntlrASTProcessor
{
AST process(final AST p0);
}
| 14.692308 | 41 | 0.743455 |
f4a990a2f738f132caa46cef78619f2188fb7db9 | 4,134 | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 Code Technology Studio
*
* 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 io.jpom.controller.node.script;
import cn.jiangzeyin.common.JsonMessage;
import cn.jiangzeyin.common.validator.ValidatorItem;
import io.jpom.common.BaseServerController;
import io.jpom.common.forward.NodeForward;
import io.jpom.common.forward.NodeUrl;
import io.jpom.model.PageResultDto;
import io.jpom.model.data.NodeModel;
import io.jpom.model.node.ScriptExecuteLogCacheModel;
import io.jpom.plugin.ClassFeature;
import io.jpom.plugin.Feature;
import io.jpom.plugin.MethodFeature;
import io.jpom.service.node.script.NodeScriptExecuteLogServer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @author bwcx_jzy
* @since 2021/12/24
*/
@RestController
@RequestMapping(value = "/node/script_log")
@Feature(cls = ClassFeature.NODE_SCRIPT_LOG)
public class NodeScriptLogController extends BaseServerController {
private final NodeScriptExecuteLogServer nodeScriptExecuteLogServer;
public NodeScriptLogController(NodeScriptExecuteLogServer nodeScriptExecuteLogServer) {
this.nodeScriptExecuteLogServer = nodeScriptExecuteLogServer;
}
/**
* get script log list
*
* @return json
*/
@RequestMapping(value = "list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public String scriptList() {
PageResultDto<ScriptExecuteLogCacheModel> pageResultDto = nodeScriptExecuteLogServer.listPageNode(getRequest());
return JsonMessage.getString(200, "", pageResultDto);
}
/**
* 查日志
*
* @return json
*/
@RequestMapping(value = "log", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@Feature(method = MethodFeature.LIST)
public String log() {
NodeModel node = getNode();
return NodeForward.request(node, getRequest(), NodeUrl.SCRIPT_LOG).toString();
}
/**
* 删除日志
*
* @param id 模版ID
* @param executeId 日志ID
* @return json
*/
@RequestMapping(value = "del", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@Feature(method = MethodFeature.DEL)
public String del(@ValidatorItem String id, String executeId) {
NodeModel node = getNode();
ScriptExecuteLogCacheModel scriptExecuteLogCacheModel = new ScriptExecuteLogCacheModel();
scriptExecuteLogCacheModel.setId(executeId);
scriptExecuteLogCacheModel.setScriptId(id);
scriptExecuteLogCacheModel.setNodeId(node.getId());
ScriptExecuteLogCacheModel executeLogModel = nodeScriptExecuteLogServer.queryByBean(scriptExecuteLogCacheModel);
Assert.notNull(executeLogModel, "没有对应的执行日志");
JsonMessage<Object> request = NodeForward.request(node, getRequest(), NodeUrl.SCRIPT_DEL_LOG);
if (request.getCode() == HttpStatus.OK.value()) {
nodeScriptExecuteLogServer.delByKey(executeId);
}
return request.toString();
}
}
| 39 | 114 | 0.782777 |
c61c5c8c078de609fe3cc7a36e446c45e878e36e | 843 | package fr.lium.spkDiarization.parameter;
/**
* The Class ParameterModelSetInputFile2.
*/
public class ParameterModelSetInputFile2 extends ParameterModelSet implements Cloneable {
/**
* Instantiates a new parameter model set input file2.
*
* @param parameter the parameter
*/
public ParameterModelSetInputFile2(Parameter parameter) {
super(parameter);
type = "Input";
addOption(new fr.lium.spkDiarization.parameter.LongOptWithAction("t" + type + "Mask2", new ActionMask(), ""));
addOption(new LongOptWithAction("t" + type + "ModelType2", new ActionFormat(), ""));
}
/*
* (non-Javadoc)
* @see fr.fr.lium.spkDiarization.parameter.ParameterModelSet#clone()
*/
@Override
protected ParameterModelSetInputFile2 clone() throws CloneNotSupportedException {
return (ParameterModelSetInputFile2) super.clone();
}
}
| 28.1 | 112 | 0.7414 |
989d307907a0d61d1e6c487be2b24d9c7a586f22 | 455 | package com.toker.project.douyin.common.http;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.io.File;
/**
* 文件类型的请求体
*
* @author mdmbct [email protected]
* @date 2021/3/11 14:28
* @modified mdmbct
* @since 1.0
*/
@Getter
@RequiredArgsConstructor
public class FileRequestBody {
private final String name;
private final String fileName;
private final String mediaType;
private final File file;
}
| 14.677419 | 45 | 0.723077 |
8c398359bf44c331378949e22ca24043bcb0ba29 | 25,932 | /*
* (C) Copyright 2016 Nuxeo SA (http://nuxeo.com/) and 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.
*
* Contributors:
* <a href="mailto:[email protected]">Guillaume</a>
* Yannis JULIENNE
*/
package org.nuxeo.functionaltests;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.InvalidSelectorException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.NotFoundException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.google.common.base.Function;
/**
* Helper class providing find and wait methods with or without timeout. When requiring timeout, the polling frequency
* is every 100 milliseconds if not specified.
*
* @since 5.9.2
*/
public class Locator {
// Timeout for waitUntilURLDifferentFrom in seconds
public static final int URLCHANGE_MAX_WAIT = 30;
public static WebElement findElement(By by) {
return AbstractTest.driver.findElement(by);
}
/**
* Finds the first {@link WebElement} using the given method, with the default timeout. Then waits until the element
* is enabled, with the default timeout.
*
* @param by the locating mechanism
* @return the first matching element on the current page, if found
* @throws NotFoundException if the element is not found or not enabled
*/
public static WebElement findElementAndWaitUntilEnabled(By by) throws NotFoundException {
return findElementAndWaitUntilEnabled(by, AbstractTest.LOAD_TIMEOUT_SECONDS * 1000,
AbstractTest.AJAX_TIMEOUT_SECONDS * 1000);
}
/**
* Finds the first {@link WebElement} using the given method, with a {@code findElementTimeout}. Then waits until
* the element is enabled, with a {@code waitUntilEnabledTimeout}.
*
* @param by the locating mechanism
* @param findElementTimeout the find element timeout in milliseconds
* @param waitUntilEnabledTimeout the wait until enabled timeout in milliseconds
* @return the first matching element on the current page, if found
* @throws NotFoundException if the element is not found or not enabled
*/
public static WebElement findElementAndWaitUntilEnabled(final By by, final int findElementTimeout,
final int waitUntilEnabledTimeout) throws NotFoundException {
return findElementAndWaitUntilEnabled(null, by, findElementTimeout, waitUntilEnabledTimeout);
}
/**
* Finds the first {@link WebElement} using the given method, with a {@code findElementTimeout}, inside an optional
* {@code parentElement}. Then waits until the element is enabled, with a {@code waitUntilEnabledTimeout}.
*
* @param parentElement the parent element (can be null)
* @param by the locating mechanism
* @param findElementTimeout the find element timeout in milliseconds
* @param waitUntilEnabledTimeout the wait until enabled timeout in milliseconds
* @return the first matching element on the current page, if found, with optional parent element
* @throws NotFoundException if the element is not found or not enabled
* @since 8.3
*/
public static WebElement findElementAndWaitUntilEnabled(WebElement parentElement, final By by,
final int findElementTimeout, final int waitUntilEnabledTimeout) throws NotFoundException {
Wait<WebDriver> wait = getFluentWait();
Function<WebDriver, WebElement> function = new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
WebElement element = null;
try {
// Find the element.
element = findElementWithTimeout(by, findElementTimeout, parentElement);
// Try to wait until the element is enabled.
waitUntilEnabled(element, waitUntilEnabledTimeout);
} catch (StaleElementReferenceException sere) {
AbstractTest.log.debug("StaleElementReferenceException: " + sere.getMessage());
return null;
}
return element;
}
};
return wait.until(function);
}
public static List<WebElement> findElementsWithTimeout(final By by) throws NoSuchElementException {
FluentWait<WebDriver> wait = getFluentWait();
wait.ignoring(NoSuchElementException.class);
return wait.until(new Function<WebDriver, List<WebElement>>() {
@Override
public List<WebElement> apply(WebDriver driver) {
List<WebElement> elements = driver.findElements(by);
return elements.isEmpty() ? null : elements;
}
});
}
/**
* Finds the first {@link WebElement} using the given method, with the default timeout. Then waits until the element
* is enabled, with the default timeout. Then clicks on the element.
*
* @param by the locating mechanism
* @throws NotFoundException if the element is not found or not enabled
*/
public static void findElementWaitUntilEnabledAndClick(By by) throws NotFoundException {
findElementWaitUntilEnabledAndClick(null, by, AbstractTest.LOAD_TIMEOUT_SECONDS * 1000,
AbstractTest.AJAX_TIMEOUT_SECONDS * 1000);
}
/**
* Finds the first {@link WebElement} using the given method, with the default timeout, inside an optional
* {@code parentElement}. Then waits until the element is enabled, with the default timeout. Then clicks on the
* element.
*
* @param parentElement the parent element (can be null)
* @param by the locating mechanism
* @throws NotFoundException if the element is not found or not enabled
* @since 8.3
*/
public static void findElementWaitUntilEnabledAndClick(WebElement parentElement, By by) throws NotFoundException {
findElementWaitUntilEnabledAndClick(parentElement, by, AbstractTest.LOAD_TIMEOUT_SECONDS * 1000,
AbstractTest.AJAX_TIMEOUT_SECONDS * 1000);
}
/**
* Finds the first {@link WebElement} using the given method, with a timeout.
*
* @param by the locating mechanism
* @return the first matching element on the current page, if found
* @throws NoSuchElementException when not found
*/
public static WebElement findElementWithTimeout(By by) throws NoSuchElementException {
return findElementWithTimeout(by, AbstractTest.LOAD_TIMEOUT_SECONDS * 1000);
}
/**
* Checks if a corresponding elements is present, with a timeout.
*
* @param by the locating mechanism
* @return true if element exists, false otherwise
* @since 9.3
*/
public static boolean hasElementWithTimeout(By by) {
try {
return findElementWithTimeout(by) != null;
} catch (NoSuchElementException nsee) {
return false;
}
}
/**
* Finds the first {@link WebElement} using the given method, with a timeout.
*
* @param by the locating mechanism
* @param timeout the timeout in milliseconds
* @return the first matching element on the current page, if found
* @throws NoSuchElementException when not found
*/
public static WebElement findElementWithTimeout(By by, int timeout) throws NoSuchElementException {
return findElementWithTimeout(by, timeout, null);
}
/**
* Checks if a corresponding elements is present, with a timeout.
*
* @param by the locating mechanism
* @param timeout the timeout in milliseconds
* @return true if element exists, false otherwise
* @since 9.3
*/
public static boolean hasElementWithTimeout(By by, int timeout) {
try {
return findElementWithTimeout(by, timeout) != null;
} catch (NoSuchElementException nsee) {
return false;
}
}
/**
* Finds the first {@link WebElement} using the given method, with a timeout.
*
* @param by the locating mechanism
* @param timeout the timeout in milliseconds
* @param parentElement find from the element
* @return the first matching element on the current page, if found
* @throws NoSuchElementException when not found
*/
public static WebElement findElementWithTimeout(final By by, int timeout, final WebElement parentElement)
throws NoSuchElementException {
FluentWait<WebDriver> wait = getFluentWait();
wait.withTimeout(timeout, TimeUnit.MILLISECONDS).ignoring(StaleElementReferenceException.class);
try {
return wait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
try {
if (parentElement == null) {
return driver.findElement(by);
} else {
return parentElement.findElement(by);
}
} catch (NoSuchElementException e) {
return null;
}
}
});
} catch (TimeoutException e) {
throw new NoSuchElementException(String.format("Couldn't find element '%s' after timeout", by));
}
}
/**
* Finds the first {@link WebElement} using the given method, with a timeout.
*
* @param by the locating mechanism
* @param timeout the timeout in milliseconds
* @param parentElement find from the element
* @return the first matching element on the current page, if found
* @throws NoSuchElementException when not found
*/
public static WebElement findElementWithTimeout(By by, WebElement parentElement) throws NoSuchElementException {
return findElementWithTimeout(by, AbstractTest.LOAD_TIMEOUT_SECONDS * 1000, parentElement);
}
public static FluentWait<WebDriver> getFluentWait() {
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(AbstractTest.driver);
wait.withTimeout(AbstractTest.LOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.pollingEvery(AbstractTest.POLLING_FREQUENCY_MILLISECONDS, TimeUnit.MILLISECONDS);
return wait;
}
/**
* Fluent wait for text to be not present in the given element.
*
* @since 5.7.3
*/
public static void waitForTextNotPresent(final WebElement element, final String text) {
Wait<WebDriver> wait = getFluentWait();
wait.until((new Function<WebDriver, Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
return !element.getText().contains(text);
} catch (StaleElementReferenceException e) {
return null;
}
}
}));
}
/**
* Fluent wait for text to be present in the element retrieved with the given method.
*
* @since 5.7.3
*/
public static void waitForTextPresent(By locator, String text) {
Wait<WebDriver> wait = getFluentWait();
wait.until(ExpectedConditions.textToBePresentInElementLocated(locator, text));
}
/**
* Fluent wait for text to be present in the given element.
*
* @since 5.7.3
*/
public static void waitForTextPresent(final WebElement element, final String text) {
Wait<WebDriver> wait = getFluentWait();
wait.until((new Function<WebDriver, Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
return element.getText().contains(text);
} catch (StaleElementReferenceException e) {
return null;
}
}
}));
}
/**
* Finds the first {@link WebElement} using the given method, with a {@code findElementTimeout}. Then waits until
* the element is enabled, with a {@code waitUntilEnabledTimeout}. Scroll to it, then clicks on the element.
*
* @param by the locating mechanism
* @param findElementTimeout the find element timeout in milliseconds
* @param waitUntilEnabledTimeout the wait until enabled timeout in milliseconds
* @throws NotFoundException if the element is not found or not enabled
* @deprecated since 8.3, use {@link #findElementWaitUntilEnabledAndClick(WebElement, By)}
*/
@Deprecated
public static void findElementWaitUntilEnabledAndClick(final By by, final int findElementTimeout,
final int waitUntilEnabledTimeout) throws NotFoundException {
findElementWaitUntilEnabledAndClick(null, by, findElementTimeout, waitUntilEnabledTimeout);
}
/**
* Finds the first {@link WebElement} using the given method, with a {@code findElementTimeout}, inside an optional
* {@code parentElement}. Then waits until the element is enabled, with a {@code waitUntilEnabledTimeout}. Scroll to
* it, then clicks on the element.
*
* @param parentElement the parent element (can be null)
* @param by the locating mechanism
* @param findElementTimeout the find element timeout in milliseconds
* @param waitUntilEnabledTimeout the wait until enabled timeout in milliseconds
* @throws NotFoundException if the element is not found or not enabled
* @since 8.3
*/
public static void findElementWaitUntilEnabledAndClick(WebElement parentElement, final By by,
final int findElementTimeout, final int waitUntilEnabledTimeout) throws NotFoundException {
WebElement element = findElementAndWaitUntilEnabled(parentElement, by, findElementTimeout,
waitUntilEnabledTimeout);
waitUntilGivenFunctionIgnoring(new Function<WebDriver, Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return scrollAndForceClick(element);
}
}, StaleElementReferenceException.class);
}
/**
* Waits until the element is enabled, with a default timeout. Then clicks on the element.
*
* @param element the element
* @throws NotFoundException if the element is not found or not enabled
* @since 8.3
*/
public static void waitUntilEnabledAndClick(final WebElement element) throws NotFoundException {
waitUntilEnabledAndClick(element, AbstractTest.AJAX_TIMEOUT_SECONDS * 1000);
}
/**
* Waits until the element is enabled, with a {@code waitUntilEnabledTimeout}. Scroll to it, then clicks on the
* element.
*
* @param element the element
* @param waitUntilEnabledTimeout the wait until enabled timeout in milliseconds
* @throws NotFoundException if the element is not found or not enabled
* @since 8.3
*/
public static void waitUntilEnabledAndClick(final WebElement element, final int waitUntilEnabledTimeout)
throws NotFoundException {
waitUntilEnabled(element, waitUntilEnabledTimeout);
waitUntilGivenFunctionIgnoring(new Function<WebDriver, Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return scrollAndForceClick(element);
}
}, StaleElementReferenceException.class);
}
/**
* Finds the first {@link WebElement} using the given method, with a {@code findElementTimeout}. Then clicks on the
* element.
*
* @param by the locating mechanism
* @throws NotFoundException if the element is not found or not enabled
* @since 5.9.4
*/
public static void findElementWithTimeoutAndClick(final By by) throws NotFoundException {
waitUntilGivenFunctionIgnoring(new Function<WebDriver, Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
// Find the element.
WebElement element = findElementWithTimeout(by);
element.click();
return true;
}
}, StaleElementReferenceException.class);
}
/**
* Fluent wait for an element not to be present, checking every 100 ms.
*
* @since 5.7.2
*/
public static void waitUntilElementNotPresent(final By locator) {
Wait<WebDriver> wait = getFluentWait();
wait.until((new Function<WebDriver, By>() {
@Override
public By apply(WebDriver driver) {
try {
driver.findElement(locator);
} catch (NoSuchElementException ex) {
// ok
return locator;
}
return null;
}
}));
}
/**
* @since 9.3
*/
public static void waitUntilWindowClosed(final String windowHandle) {
Wait<WebDriver> wait = getFluentWait();
wait.until(driver -> !driver.getWindowHandles().contains(windowHandle));
}
/**
* Fluent wait for an element to be present, checking every 100 ms.
*
* @since 5.7.2
*/
public static void waitUntilElementPresent(final By locator) {
FluentWait<WebDriver> wait = getFluentWait();
wait.ignoring(NoSuchElementException.class);
wait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
});
}
/**
* Waits until an element is enabled, with a timeout.
*
* @param element the element
*/
public static void waitUntilEnabled(WebElement element) throws NotFoundException {
waitUntilEnabled(element, AbstractTest.AJAX_TIMEOUT_SECONDS * 1000);
}
/**
* Waits until an element is enabled, with a timeout.
*
* @param element the element
* @param timeout the timeout in milliseconds
*/
public static void waitUntilEnabled(final WebElement element, int timeout) throws NotFoundException {
FluentWait<WebDriver> wait = getFluentWait();
wait.withTimeout(timeout, TimeUnit.MILLISECONDS);
Function<WebDriver, Boolean> function = new Function<WebDriver, Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return element.isEnabled();
}
};
try {
wait.until(function);
} catch (TimeoutException e) {
throw new NotFoundException("Element not enabled after timeout: " + element);
}
}
/**
* Fluent wait on a the given function, checking every 100 ms.
*
* @param function
* @since 5.9.2
*/
public static void waitUntilGivenFunction(Function<WebDriver, Boolean> function) {
waitUntilGivenFunctionIgnoring(function, null);
}
/**
* Fluent wait on a the given function, checking every 100 ms.
*
* @param function
* @param ignoredExceptions the types of exceptions to ignore.
* @since 5.9.2
*/
@SafeVarargs
public static <K extends java.lang.Throwable> void waitUntilGivenFunctionIgnoreAll(
Function<WebDriver, Boolean> function, java.lang.Class<? extends K>... ignoredExceptions) {
FluentWait<WebDriver> wait = getFluentWait();
if (ignoredExceptions != null) {
if (ignoredExceptions.length == 1) {
wait.ignoring(ignoredExceptions[0]);
} else {
wait.ignoreAll(Arrays.asList(ignoredExceptions));
}
}
wait.until(function);
}
/**
* Fluent wait on a the given function, checking every 100 ms.
*
* @param function
* @param ignoredException the type of exception to ignore.
* @since 5.9.2
*/
public static <K extends java.lang.Throwable> void waitUntilGivenFunctionIgnoring(
Function<WebDriver, Boolean> function, java.lang.Class<? extends K> ignoredException) {
FluentWait<WebDriver> wait = getFluentWait();
if (ignoredException != null) {
wait.ignoring(ignoredException);
}
wait.until(function);
}
/**
* Waits until the URL contains the string given in parameter, with a timeout.
*
* @param string the string that is to be contained
* @since 5.9.2
*/
public static void waitUntilURLContains(String string) {
waitUntilURLContainsOrNot(string, true);
}
/**
* @since 5.9.2
*/
private static void waitUntilURLContainsOrNot(String string, final boolean contain) {
final String refurl = string;
ExpectedCondition<Boolean> condition = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver d) {
String currentUrl = d.getCurrentUrl();
boolean result = !(currentUrl.contains(refurl) ^ contain);
if (!result) {
AbstractTest.log.debug("currentUrl is : " + currentUrl);
AbstractTest.log.debug((contain ? "It should contains : " : "It should not contains : ") + refurl);
}
return result;
}
};
WebDriverWait wait = new WebDriverWait(AbstractTest.driver, URLCHANGE_MAX_WAIT);
wait.until(condition);
}
/**
* Waits until the URL is different from the one given in parameter, with a timeout.
*
* @param url the URL to compare to
*/
public static void waitUntilURLDifferentFrom(String url) {
final String refurl = url;
AbstractTest.log.debug("Watch URL: " + refurl);
ExpectedCondition<Boolean> urlchanged = d -> {
if (d == null) {
return false;
}
String currentUrl = d.getCurrentUrl();
AbstractTest.log.debug("currentUrl is still: " + currentUrl);
return !currentUrl.equals(refurl);
};
WebDriverWait wait = new WebDriverWait(AbstractTest.driver, URLCHANGE_MAX_WAIT);
wait.until(urlchanged);
if (AbstractTest.driver.getCurrentUrl().equals(refurl)) {
AbstractTest.log.warn("Page change failed");
}
}
/**
* Waits until the URL does not contain the string given in parameter, with a timeout.
*
* @param string the string that is not to be contained
* @since 5.9.2
*/
public static void waitUntilURLNotContain(String string) {
waitUntilURLContainsOrNot(string, false);
}
/**
* Return parent element with given tag name.
* <p>
* Throws a {@link NoSuchElementException} error if no element found.
*
* @since 7.3
*/
public static WebElement findParentTag(WebElement elt, String tagName) {
try {
By parentBy = By.xpath("..");
WebElement p = elt.findElement(parentBy);
while (p != null) {
if (tagName.equals(p.getTagName())) {
return p;
}
p = p.findElement(parentBy);
}
} catch (InvalidSelectorException e) {
}
throw new NoSuchElementException(String.format("No parent element found with tag %s.", tagName));
}
/**
* Scrolls to the element in the view: allows to safely click on it afterwards.
*
* @param executor the javascript executor, usually {@link WebDriver}
* @param element the element to scroll to
* @since 8.3
*/
public static final void scrollToElement(WebElement element) {
((JavascriptExecutor) AbstractTest.driver).executeScript("arguments[0].scrollIntoView(false);", element);
}
/**
* Forces a click on an element, to workaround non-effective clicks in miscellaneous situations, after having
* scrolled to it.
*
* @param executor the javascript executor, usually {@link WebDriver}
* @param element the element to scroll to
* @return true if element is clickable
* @since 8.3
*/
public static final boolean scrollAndForceClick(WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) AbstractTest.driver;
scrollToElement(element);
try {
// forced click to workaround non-effective clicks in miscellaneous situations
executor.executeScript("arguments[0].click();", element);
return true;
} catch (WebDriverException e) {
if (e.getMessage().contains("Element is not clickable at point")) {
AbstractTest.log.debug("Element is not clickable yet");
return false;
}
throw e;
}
}
}
| 39.231467 | 120 | 0.645882 |
0934845c19638825795cd5026d5c230a9b16c1be | 2,676 | package net.jgp.labs.spark.datasources.x.ds.exif;
import org.apache.spark.sql.SQLContext;
import org.apache.spark.sql.sources.BaseRelation;
import org.apache.spark.sql.sources.RelationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.jgp.labs.spark.datasources.x.extlib.RecursiveExtensionFilteredLister;
import net.jgp.labs.spark.datasources.x.utils.K;
import static scala.collection.JavaConverters.mapAsJavaMapConverter;
import scala.collection.immutable.Map;
public class ExifDirectoryDataSource implements RelationProvider {
private static transient Logger log = LoggerFactory
.getLogger(ExifDirectoryDataSource.class);
@Override
public BaseRelation createRelation(
SQLContext sqlContext,
Map<String, String> params) {
log.debug("-> createRelation()");
java.util.Map<String, String> javaMap = mapAsJavaMapConverter(params).asJava();
ExifDirectoryRelation br = new ExifDirectoryRelation();
br.setSqlContext(sqlContext);
RecursiveExtensionFilteredLister photoLister = new RecursiveExtensionFilteredLister();
for (java.util.Map.Entry<String, String> entry : javaMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
log.debug("[{}] --> [{}]", key, value);
switch (key) {
case K.PATH:
photoLister.setPath(value);
break;
case K.RECURSIVE:
if (value.toLowerCase().charAt(0) == 't') {
photoLister.setRecursive(true);
} else {
photoLister.setRecursive(false);
}
break;
case K.LIMIT:
int limit;
try {
limit = Integer.valueOf(value);
} catch (NumberFormatException e) {
log.error(
"Illegal value for limit, exting a number, got: {}. {}. Ignoring parameter.",
value, e.getMessage());
limit = -1;
}
photoLister.setLimit(limit);
break;
case K.EXTENSIONS:
String[] extensions = value.split(",");
for (int i = 0; i < extensions.length; i++) {
photoLister.addExtension(extensions[i]);
}
break;
default:
log.warn("Unrecognized parameter: [{}].", key);
break;
}
}
br.setPhotoLister(photoLister);
return br;
}
}
| 35.68 | 105 | 0.560164 |
5aed9274dd857cfce18127f6416abfbf65ea5e4e | 2,570 | package com.debut.ellipsis.freehit.Matches.PastMatches;
public class PastMatchCardItem {
private String mMatchName;
private String mMatchID;
private String mSeriesName;
private String mStadiumName;
private String mTeam1LogoURL;
private String mTeam1SN;
private String mTeam1Innings1;
private String mTeam1Innings2;
private String mTeam2LogoURL;
private String mTeam2SN;
private String mTeam2Innings1;
private String mTeam2Innings2;
private String mMatchDate;
private String mViewMore;
private String mMatchResult;
public PastMatchCardItem(String MatchName, String MatchID, String SeriesName, String StadiumName, String Team1LogoURL, String Team1SN, String Team1Innings1, String Team1Innings2, String Team2LogoURL, String Team2SN, String Team2Innings1, String Team2Innings2, String MatchDate, String MatchResult) {
mMatchName = MatchName;
mMatchID = MatchID;
mSeriesName = SeriesName;
mStadiumName = StadiumName;
mTeam1LogoURL = Team1LogoURL;
mTeam1SN = Team1SN;
mTeam1Innings1 = Team1Innings1;
mTeam1Innings2 = Team1Innings2;
mTeam2LogoURL = Team2LogoURL;
mTeam2SN = Team2SN;
mTeam2Innings1 = Team2Innings1;
mTeam2Innings2 = Team2Innings2;
mMatchDate = MatchDate;
mMatchResult = MatchResult;
}
public PastMatchCardItem(String ViewMore) {
mViewMore = ViewMore;
}
public String getmMatchName() {
return mMatchName;
}
public String getmMatchID() {
return mMatchID;
}
public String getmSeriesName() {
return mSeriesName;
}
public String getmStadiumName() {
return mStadiumName;
}
public String getmTeam1LogoURL() {
return mTeam1LogoURL;
}
public String getmTeam1SN() {
return mTeam1SN;
}
public String getmTeam1Innings1() {
return mTeam1Innings1;
}
public String getmTeam1Innings2() {
return mTeam1Innings2;
}
public String getmTeam2LogoURL() {
return mTeam2LogoURL;
}
public String getmTeam2SN() {
return mTeam2SN;
}
public String getmTeam2Innings1() {
return mTeam2Innings1;
}
public String getmTeam2Innings2() {
return mTeam2Innings2;
}
public String getmMatchDate() {
return mMatchDate;
}
public String getmViewMore() {
return mViewMore;
}
public String getmMatchResult() {
return mMatchResult;
}
}
| 21.779661 | 303 | 0.666148 |
0bea0b1e767c9b66065ade1e9cb1b1f918d96671 | 327 | package randomappsinc.com.sqlpractice.utils;
import android.content.Context;
import android.widget.Toast;
import androidx.annotation.StringRes;
public class ToastUtils {
public static void showLongToast(Context context, @StringRes int resId) {
Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
}
}
| 23.357143 | 77 | 0.764526 |
4cd5ebd948f6799c4dd8309c18e684047ed43ae7 | 4,199 | package org.telegram.telegrambots.meta.api.objects.replykeyboard;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents a custom keyboard with reply options.
* @date 20 of June of 2015
*/
public class ReplyKeyboardMarkup implements ReplyKeyboard {
private static final String KEYBOARD_FIELD = "keyboard";
private static final String RESIZEKEYBOARD_FIELD = "resize_keyboard";
private static final String ONETIMEKEYBOARD_FIELD = "one_time_keyboard";
private static final String SELECTIVE_FIELD = "selective";
@JsonProperty(KEYBOARD_FIELD)
private List<KeyboardRow> keyboard; ///< Array of button rows, each represented by an Array of Strings
@JsonProperty(RESIZEKEYBOARD_FIELD)
private Boolean resizeKeyboard; ///< Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false.
@JsonProperty(ONETIMEKEYBOARD_FIELD)
private Boolean oneTimeKeyboard; ///< Optional. Requests clients to hide the keyboard as soon as it's been used. Defaults to false.
/**
* Optional. Use this parameter if you want to show the keyboard to specific users only.
* Targets:
* 1) users that are @mentioned in the text of the Message object;
* 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
*/
@JsonProperty(SELECTIVE_FIELD)
private Boolean selective;
public ReplyKeyboardMarkup() {
super();
keyboard = new ArrayList<>();
}
public List<KeyboardRow> getKeyboard() {
return keyboard;
}
public ReplyKeyboardMarkup setKeyboard(List<KeyboardRow> keyboard) {
this.keyboard = keyboard;
return this;
}
public Boolean getResizeKeyboard() {
return resizeKeyboard;
}
public ReplyKeyboardMarkup setResizeKeyboard(Boolean resizeKeyboard) {
this.resizeKeyboard = resizeKeyboard;
return this;
}
public Boolean getOneTimeKeyboard() {
return oneTimeKeyboard;
}
public ReplyKeyboardMarkup setOneTimeKeyboard(Boolean oneTimeKeyboard) {
this.oneTimeKeyboard = oneTimeKeyboard;
return this;
}
public Boolean getSelective() {
return selective;
}
public ReplyKeyboardMarkup setSelective(Boolean selective) {
this.selective = selective;
return this;
}
@Override
public void validate() throws TelegramApiValidationException {
if (keyboard == null) {
throw new TelegramApiValidationException("Keyboard parameter can't be null", this);
}
for (KeyboardRow keyboardButtons : keyboard) {
keyboardButtons.validate();
}
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof ReplyKeyboardMarkup)) {
return false;
}
ReplyKeyboardMarkup replyKeyboardMarkup = (ReplyKeyboardMarkup) o;
return Objects.equals(keyboard, replyKeyboardMarkup.keyboard)
&& Objects.equals(oneTimeKeyboard, replyKeyboardMarkup.oneTimeKeyboard)
&& Objects.equals(resizeKeyboard, replyKeyboardMarkup.resizeKeyboard)
&& Objects.equals(selective, replyKeyboardMarkup.selective)
;
}
@Override
public int hashCode() {
return Objects.hash(
keyboard,
oneTimeKeyboard,
resizeKeyboard,
selective);
}
@Override
public String toString() {
return "ReplyKeyboardMarkup{" +
"keyboard=" + keyboard +
", resizeKeyboard=" + resizeKeyboard +
", oneTimeKeyboard=" + oneTimeKeyboard +
", selective=" + selective +
'}';
}
}
| 33.862903 | 209 | 0.668969 |
c5bfa3bcb98ea81c2171b8a715e98c4b1e8f0cdf | 297 | /// This file was auto-generated by RegisterGenerator. Any changes to it will be overwritten!
package io.treehopper.libraries.sensors.pressure.bmp280;
enum Modes
{
Sleep (0),
Forced (1),
Normal (3);
int val;
Modes(int val) { this.val = val; }
public int getVal() { return val; }
}
| 19.8 | 93 | 0.683502 |
e35cc8a34fb79b2ebc20ee4c37ec5d07fcb803f4 | 2,226 | /*
* Copyright (c) 2009-2018, b3log.org & hacpai.com
*
* 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.b3log.latke.servlet.annotation;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.URIPatternMode;
import org.b3log.latke.servlet.converter.ConvertSupport;
import java.lang.annotation.*;
/**
* Indicates that an annotated method for HTTP servlet request processing.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @author <a href="mailto:[email protected]">Love Yao</a>
* @version 1.0.0.5, Dec 23, 2015
* @see RequestProcessor
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestProcessing {
/**
* The dispatching URI path patterns of a request.
*
* <p>
* Semantics of these values adapting to the URL patterns (<url-pattern/>) configures in web application
* descriptor (web.xml) of a servlet. Ant-style path pattern and regular expression pattern are also supported.
* </p>
*
* @return values
*/
String[] value() default {};
/**
* The URI patterns mode.
*
* @return URI patterns mode
*/
URIPatternMode uriPatternsMode() default URIPatternMode.ANT_PATH;
/**
* The HTTP request methods the annotated method should process.
*
* @return HTTP request methods
*/
HTTPRequestMethod[] method() default {HTTPRequestMethod.GET};
/**
* User customized data convert class.
*
* @return convert class
*/
Class<? extends ConvertSupport> convertClass() default ConvertSupport.class;
}
| 31.8 | 116 | 0.673854 |
5db3050fc74ba972dd6bc6ea31b9d45f3f8fe0ac | 5,353 | package cn.openwatch.internal.communication.os.google.china;
import android.os.Binder;
import android.os.Handler;
import java.util.List;
import cn.openwatch.communication.service.OpenWatchListenerService;
import cn.openwatch.internal.communication.IServiceBinder;
import cn.openwatch.internal.communication.event.ServiceEventHandler;
import cn.openwatch.internal.google.china.android.gms.common.GooglePlayServicesUtil;
import cn.openwatch.internal.google.china.android.gms.common.data.DataHolder;
import cn.openwatch.internal.google.china.android.gms.wearable.DataEventBuffer;
import cn.openwatch.internal.google.china.android.gms.wearable.internal.AmsEntityUpdateParcelable;
import cn.openwatch.internal.google.china.android.gms.wearable.internal.AncsNotificationParcelable;
import cn.openwatch.internal.google.china.android.gms.wearable.internal.CapabilityInfoParcelable;
import cn.openwatch.internal.google.china.android.gms.wearable.internal.ChannelEventParcelable;
import cn.openwatch.internal.google.china.android.gms.wearable.internal.MessageEventParcelable;
import cn.openwatch.internal.google.china.android.gms.wearable.internal.NodeParcelable;
import cn.openwatch.internal.google.china.android.gms.wearable.internal.zzav;
public final class AwServiceBinder extends zzav.zza implements IServiceBinder {
private OpenWatchListenerService service;
private volatile int uid = -1;
private Handler handler;
private boolean isDestory;
private ServiceEventHandler eventHandler;
private AwEventDataParser dataParser;
// for反射
public AwServiceBinder() {
}
public void setService(OpenWatchListenerService service) {
this.service = service;
}
@Override
public void onServiceBind() {
// TODO Auto-generated method stub
handler = new Handler();
eventHandler = new ServiceEventHandler();
eventHandler.setUserService(service);
dataParser = new AwEventDataParser();
}
@Override
public void onServiceDestory() {
// TODO Auto-generated method stub
synchronized (AwServiceBinder.class) {
isDestory = true;
}
}
private void checkSecurity() throws SecurityException {
int i = Binder.getCallingUid();
if (i == uid) {
return;
}
if (GooglePlayServicesUtil.zza(service, i)) {
uid = i;
return;
}
throw new SecurityException("Caller is not GooglePlayServices");
}
@Override
public void zza(final DataHolder paramDataHolder) {
checkSecurity();
synchronized (AwServiceBinder.class) {
if (isDestory) {
paramDataHolder.close();
return;
}
handler.post(new Runnable() {
public void run() {
DataEventBuffer localDataEventBuffer = new DataEventBuffer(paramDataHolder);
try {
// 数据统计和取消操作的行为要保证数据必达 需要用dataAPI
dataParser.dispatchDataChanged(service, localDataEventBuffer, eventHandler);
} finally {
localDataEventBuffer.release();
}
}
});
}
}
@Override
public void zza(final MessageEventParcelable paramMessageEventParcelable) {
checkSecurity();
synchronized (AwServiceBinder.class) {
if (isDestory) {
return;
}
handler.post(new Runnable() {
public void run() {
String path = paramMessageEventParcelable.getPath();
byte[] rawData = paramMessageEventParcelable.getData();
eventHandler.handleMessageReceived(path, rawData);
}
});
}
}
@Override
public void zza(final NodeParcelable paramNodeParcelable) {
checkSecurity();
synchronized (AwServiceBinder.class) {
if (isDestory) {
return;
}
handler.post(new Runnable() {
public void run() {
eventHandler.handlePeerConnected(paramNodeParcelable.getDisplayName(), paramNodeParcelable.getId());
}
});
}
}
@Override
public void zzb(final NodeParcelable paramNodeParcelable) {
checkSecurity();
synchronized (AwServiceBinder.class) {
if (isDestory) {
return;
}
handler.post(new Runnable() {
public void run() {
eventHandler.handlePeerDisconnected(paramNodeParcelable.getDisplayName(),
paramNodeParcelable.getId());
}
});
}
}
@Override
public void onConnectedNodes(final List<NodeParcelable> connectedNodes) {
}
@Override
public void zza(final CapabilityInfoParcelable paramCapabilityInfoParcelable) {
}
@Override
public void zza(final AncsNotificationParcelable paramAncsNotificationParcelable) {
}
@Override
public void zza(final AmsEntityUpdateParcelable paramAmsEntityUpdateParcelable) {
}
@Override
public void zza(final ChannelEventParcelable paramChannelEventParcelable) {
}
}
| 31.304094 | 120 | 0.639268 |
b0339ff5173c5780e05c15ba75332487d8829fde | 2,737 | /*
* Copyright (c) 2014-2015 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2019 Eclipse Krazo committers and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.eclipse.krazo.test.csrf.methods;
import jakarta.mvc.Controller;
import jakarta.mvc.UriRef;
import jakarta.mvc.View;
import jakarta.mvc.security.CsrfProtected;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
@Path("csrf-methods")
@Controller
public class CsrfHiddenMethodController {
@GET
@Path("exception-delete")
public String getExceptionDeleteForm() {
return "csrf-exception-delete.jsp";
}
@GET
@Path("exception-patch")
public String getExceptionPatchForm() {
return "csrf-exception-patch.jsp";
}
@GET
@Path("exception-post")
public String getExceptionPostForm() {
return "csrf-exception-post.jsp";
}
@GET
@Path("exception-put")
public String getExceptionPutForm() {
return "csrf-exception-put.jsp";
}
@GET
@Path("ok-delete")
public String getOkDeleteForm() {
return "csrf-ok-delete.jsp";
}
@GET
@Path("ok-patch")
public String getOkPatchForm() {
return "csrf-ok-patch.jsp";
}
@GET
@Path("ok-post")
public String getOkPostForm() {
return "csrf-ok-post.jsp";
}
@GET
@Path("ok-put")
public String getOkPutForm() {
return "csrf-ok-put.jsp";
}
@GET
@Path("ok")
@View("ok.jsp")
public void getOk() {
}
@POST
@CsrfProtected
@UriRef("doPost")
public String doPost() {
return "redirect:/csrf-methods/ok";
}
@PUT
@CsrfProtected
@UriRef("doPut")
public String doPut() {
return "redirect:/csrf-methods/ok";
}
@PATCH
@CsrfProtected
@UriRef("doPatch")
public String doPatch() {
return "redirect:/csrf-methods/ok";
}
@DELETE
@CsrfProtected
@UriRef("doDelete")
public String doDelete() {
return "redirect:/csrf-methods/ok";
}
}
| 23.194915 | 77 | 0.649251 |
8110a5ced0af4ce9555ab70ec7ae82fc993506ba | 1,895 | /*
* Copyright 2014 Frakbot (Francesco Pontillo, Sebastiano Poggi)
*
* 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 net.frakbot.android.location.common;
import android.os.Bundle;
/**
* Created by Francesco on 16/02/14.
*/
public interface ConnectionCallbacks {
/**
* After calling connect(), this method will be invoked asynchronously when the connect request
* has successfully completed.
* After this callback, the application can make requests on other methods provided by the
* client and expect that no user intervention is required to call methods that use account and
* scopes provided to the client constructor.
*
* @param connectionHint Bundle of data provided to clients. May be null if no content is
* provided by the service.
*/
public abstract void onConnected(Bundle connectionHint);
/**
* Called when the client is disconnected.
* This can happen if there is a problem with the remote service (e.g. a crash or resource
* problem causes it to be killed by the system). When called, all requests have been canceled
* and no outstanding listeners will be executed. Applications should disable UI components
* that require the service, and wait for a call to onConnected(Bundle) to re-enable them.
*/
public abstract void onDisconnected();
}
| 40.319149 | 99 | 0.719789 |
7ee0efb2cf0b212a59e4238b78ccd7532f7ac7b2 | 605 | package ml.northwestwind.moreboots.init.item.boots;
import ml.northwestwind.moreboots.handler.MoreBootsPacketHandler;
import ml.northwestwind.moreboots.handler.packet.CShootDragonBallPacket;
import ml.northwestwind.moreboots.init.ItemInit;
import ml.northwestwind.moreboots.init.item.BootsItem;
public class EnderDragonBootsItem extends BootsItem {
public EnderDragonBootsItem() {
super(ItemInit.ModArmorMaterial.DRAGON, "ender_dragon_boots");
}
@Override
public void activateBoots() {
MoreBootsPacketHandler.INSTANCE.sendToServer(new CShootDragonBallPacket());
}
}
| 33.611111 | 83 | 0.795041 |
081238d7ecf2b9d77c018ae9588764987b5800dd | 13,329 | package com.simplicity.maged.mccobjectdetection.components.contextManager;
import java.math.BigInteger;
import java.util.List;
import java.util.UUID;
import com.simplicity.maged.mccobjectdetection.R;
import com.simplicity.maged.mccobjectdetection.components.logger.SimplicityLogger;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
public class ContextEngine {
static NetworkStatus mNS;
static Providers providers;
static double userUpBw;
static double userDownBw;
static double upBW;
static double downBW;
public static void setUpBW(double upBW) {
ContextEngine.upBW = upBW;
}
public static void setDownBW(double downBW) {
ContextEngine.downBW = downBW;
}
static double getUserUpBw() {
return userUpBw;
}
public static void setUserUpBw(double userUpBw) {
ContextEngine.userUpBw = userUpBw;
}
static double getUserDownBw() {
return userDownBw;
}
public static void setUserDownBw(double userDownBw) {
ContextEngine.userDownBw = userDownBw;
}
public static Boolean getInternetConnected() {
return mNS.connected;
}
public static Boolean getCloudConnected() {
return mNS.cloudConnected;
}
public static Boolean getMobileInternet() {
return mNS.mobileInternet;
}
public static Boolean getWifi() {
return mNS.wifi;
}
public static int getSignal_strength() {
return mNS.signal_strength;
}
public static int getWifi_quality() {
return mNS.wifi_quality;
}
public static int getWifi_quality_percent() {
return mNS.wifi_quality_percent;
}
public static double getWifiLinkSpeed() {
return mNS.wifi_link_speed;
}
public static double getUpBw() {
if (ContextEngine.upBW == 0 && mNS.upBw > 0) {
return mNS.upBw;
}
return ContextEngine.upBW;
}
public static double getDownBw() {
if (ContextEngine.downBW == 0 && mNS.downBw > 0) {
return mNS.downBw;
}
return ContextEngine.downBW;
}
public static LocalResources GetLocalResources(Context context) {
LocalResources lcl = new LocalResources(context);
return lcl;
}
public static void UpdateNetworkStatus(Context context, String downUrl,
String upUrl) {
if (mNS == null) {
mNS = NetworkStatus.getInstance();
}
mNS.UpdateNetworkStatus(context, downUrl, upUrl);
}
public static void InitializeProvidersList(Context context) {
if (providers == null) {
providers = Providers.getInstance();
Provider provider = new Provider();
String s2 = context.getString(R.string.cloudProviderUUID).replace(
"-", "");
UUID uuid = new UUID(
new BigInteger(s2.substring(0, 16), 16).longValue(),
new BigInteger(s2.substring(16), 16).longValue());
provider.id = uuid;
provider.url = context.getString(R.string.serverURL);
provider.permanentFlag = true;
providers.addCloudProvider(provider);
}
}
public static LocalContext getLocalContext(Context context) {
LocalContext lContext = new LocalContext();
Cursor c = context.getContentResolver().query(
ContextManagerContentProvider.DEV_SPECS_CONTENT_URI,
ContextManagerContentProvider.DEV_SPECS_COLUMNS, null, null,
null);
// equivalent to select * from table.
if (c.moveToFirst()) {
lContext.computeSpeed = c
.getInt(c
.getColumnIndex(ContextManagerContentProvider.DEV_SPECS_CPU));
}
c.close();
lContext.upBW1 = getUserUpBw() > 0 ? getUserUpBw() : getWifiLinkSpeed();
lContext.upBW2 = getUpBw();
lContext.downBW1 = getUserDownBw() > 0 ? getUserDownBw()
: getWifiLinkSpeed();
lContext.downBW2 = getDownBw();
LocalResources lcl = GetLocalResources(context);
/*
* voltage of 3.8 volts * 1900 mAh == 7220 mA-volt-hours == 7220
* milliwatt-hours == 7.22 watt-hours == 7.22 watt * 60 min * 60 sec ==
* 25992 watt-seconds or Joules
*/
lContext.energyAvail = (lcl.batt_volt * 1900 / 1000.0) * 3600;
lContext.battLevel = lcl.batt_level;
lContext.memoryAvail = lcl.avial_memory;
lContext.pCompute = 0.4445;
lContext.pIdeal = 0.1887;
lContext.pTransmit = 0.2103;
Log.i("simplicity", "ContextEngine.getLocalContext: upBW1: "
+ lContext.upBW1);
Log.i("simplicity", "ContextEngine.getLocalContext: downBW1: "
+ lContext.downBW1);
Log.i("simplicity", "ContextEngine.getLocalContext: upBW2: "
+ lContext.upBW2);
Log.i("simplicity", "ContextEngine.getLocalContext: downBW2: "
+ lContext.downBW2);
return lContext;
}
public static EnvironmentContext[] getEnvironmentContext(Context context) {
int length = Providers.getProviders() != null ? Providers
.getProviders().size() : 0;
EnvironmentContext[] eContext = new EnvironmentContext[length];
for (int i = 0; i < length; i++) {
Provider provider = Providers.getProviders().get(i);
if (provider.permanentFlag == true) {
// main cloud provider
EnvironmentContext eC = new EnvironmentContext();
Cursor c = context
.getContentResolver()
.query(ContextManagerContentProvider.SERVICE_DISCOVERY_CONTENT_URI,
ContextManagerContentProvider.SERVICE_DISCOVERY_COLUMNS,
ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_UUID
+ " = ?",
new String[] { provider.id.toString() }, null);
if (c.moveToFirst()) {
eC.upBW3 = getUpBw();
eC.upBW4 = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_UPBW4));
eC.upBW5 = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_UPBW5));
eC.downBW3 = getDownBw();
eC.downBW4 = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_DOWNBW4));
eC.downBW5 = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_DOWNBW5));
eC.computeSpeed = c
.getLong(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_COMPUTESPEED));
eC.memoryAvail = c
.getLong(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_AVAILMEMORY));
}
c.close();
eC.energyAvail = 100; // cloud is 100 % powered
eC.providerUUID = provider.id;
eContext[i] = eC;
}
else {
// mobile service provider
EnvironmentContext eC = new EnvironmentContext();
Cursor c = context
.getContentResolver()
.query(ContextManagerContentProvider.SERVICE_DISCOVERY_CONTENT_URI,
ContextManagerContentProvider.SERVICE_DISCOVERY_COLUMNS,
ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_UUID
+ " = ?",
new String[] { provider.id.toString() }, null);
if (c.moveToFirst()) {
eC.computeSpeed = c
.getLong(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_COMPUTESPEED));
eC.upBW3 = getUserUpBw() > 0 ? getUserUpBw()
: getWifiLinkSpeed();
eC.upBW4 = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_UPBW4));
eC.upBW5 = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_UPBW5));
eC.downBW3 = getUserDownBw() > 0 ? getUserDownBw()
: getWifiLinkSpeed();
eC.downBW4 = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_DOWNBW4));
eC.downBW5 = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_DOWNBW5));
eC.energyAvail = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_AVAILENERGY));
eC.memoryAvail = c
.getDouble(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_PROVIDER_AVAILMEMORY));
}
c.close();
eC.providerUUID = provider.id;
eContext[i] = eC;
}
Log.i("simplicity", "ContextEngine.getEnvironmentContext: upBW3: "
+ eContext[i].upBW3);
Log.i("simplicity",
"ContextEngine.getEnvironmentContext: downBW3: "
+ eContext[i].downBW3);
Log.i("simplicity", "ContextEngine.getEnvironmentContext: upBW4: "
+ eContext[i].upBW4);
Log.i("simplicity",
"ContextEngine.getEnvironmentContext: downBW4: "
+ eContext[i].downBW4);
Log.i("simplicity", "ContextEngine.getEnvironmentContext: upBW5: "
+ eContext[i].upBW5);
Log.i("simplicity",
"ContextEngine.getEnvironmentContext: downBW5: "
+ eContext[i].downBW5);
SimplicityLogger
.appendLine(","
+ eContext[i].upBW3);
SimplicityLogger
.appendLine(","
+ eContext[i].downBW3);
}
return eContext;
}
public static void UpdateDeviceSpecs(Context context) {
long sysBootTime = System.currentTimeMillis()
- SystemClock.elapsedRealtime();
long dbSysBootTime = 0;
Cursor c = context.getContentResolver().query(
ContextManagerContentProvider.DEV_SPECS_CONTENT_URI,
ContextManagerContentProvider.DEV_SPECS_COLUMNS, null, null,
null);
// equivalent to select * from table.
if (c.moveToFirst()) {
dbSysBootTime = c
.getLong(c
.getColumnIndex(ContextManagerContentProvider.DEV_SPECS_LAST_BOOT));
}
c.close();
if (!(dbSysBootTime - 2 <= sysBootTime && sysBootTime <= dbSysBootTime + 2)) {
// disp_size_x // disp_size_y // cpu // ram // sdk // mob_internet
// wifi // last_boot
// Reboot has occured
long cpu = DeviceInfo.getCPUMaxFreqKHz() * 1000; // KHz * 1000 = Hz
Log.d("simplicity","cpu: " + String.valueOf(cpu));
long ram = DeviceInfo.getTotalMemory(context);
Log.d("simplicity","ram: " + String.valueOf(ram));
int sdk = android.os.Build.VERSION.SDK_INT;
Log.d("simplicity", String.valueOf(sdk));
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int disp_size_x = size.x;
int disp_size_y = size.y;
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo m3G = connManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
int wifi = mWifi != null ? 1 : 0;
int mob_internet = m3G != null ? 1 : 0;
// Sensors type name
SensorManager mgr = (SensorManager) context
.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = mgr.getSensorList(Sensor.TYPE_ALL);
// ================
context.getContentResolver().delete(
ContextManagerContentProvider.DEV_SPECS_CONTENT_URI, null,
null); // delete * from table
ContentValues values = new ContentValues();
values.put(ContextManagerContentProvider.DEV_SPECS_3G, mob_internet);
values.put(ContextManagerContentProvider.DEV_SPECS_CPU, cpu);
values.put(ContextManagerContentProvider.DEV_SPECS_DISP_SIZE_X,
disp_size_x);
values.put(ContextManagerContentProvider.DEV_SPECS_DISP_SIZE_Y,
disp_size_y);
values.put(ContextManagerContentProvider.DEV_SPECS_LAST_BOOT,
sysBootTime);
values.put(ContextManagerContentProvider.DEV_SPECS_RAM, ram);
values.put(ContextManagerContentProvider.DEV_SPECS_SDK, sdk);
values.put(ContextManagerContentProvider.DEV_SPECS_WIFI, wifi);
Uri result = context
.getApplicationContext()
.getContentResolver()
.insert(ContextManagerContentProvider.DEV_SPECS_CONTENT_URI,
values);
// ====================
context.getContentResolver().delete(
ContextManagerContentProvider.DEV_SENSORS_CONTENT_URI,
null, null); // delete * from table
for (Sensor sensor : sensors) {
values.clear();
values.put(ContextManagerContentProvider.DEV_SENSORS_LAST_BOOT,
sysBootTime);
values.put(ContextManagerContentProvider.DEV_SENSORS_NAME,
sensor.getName());
values.put(ContextManagerContentProvider.DEV_SENSORS_TYPE,
sensor.getType());
result = context
.getApplicationContext()
.getContentResolver()
.insert(ContextManagerContentProvider.DEV_SENSORS_CONTENT_URI,
values);
}
}
}
public static void UpdateAvailableResources(Context context,
String discoverServiceUrl, Boolean forceUpdate) {
long sysBootTime = System.currentTimeMillis()
- SystemClock.elapsedRealtime();
long dbSysBootTime = 0;
Cursor c = context.getContentResolver().query(
ContextManagerContentProvider.SERVICE_DISCOVERY_CONTENT_URI,
ContextManagerContentProvider.SERVICE_DISCOVERY_COLUMNS, null,
null, null);
// equivalent to select * from table.
if (c.moveToFirst()) {
dbSysBootTime = c
.getLong(c
.getColumnIndex(ContextManagerContentProvider.SERVICE_DISCOVERY_LAST_BOOT));
}
c.close();
if (forceUpdate
|| !(dbSysBootTime - 2 <= sysBootTime && sysBootTime <= dbSysBootTime + 2)) {
ResourceDiscovery rs = ResourceDiscovery.getInstance();
rs.DoServiceDiscovery(context, discoverServiceUrl, sysBootTime);
}
}
}
| 33.3225 | 97 | 0.718509 |
808bd4fc1698d18bc0a6d7acfdfd3af0ab8a2b57 | 186 | package com.wangsong.system.service;
import com.wangsong.common.service.BaseService;
import com.wangsong.system.model.Dict;
public interface DictService extends BaseService<Dict>{
}
| 20.666667 | 55 | 0.817204 |
7e1ba61049e1d86421bfb845494bfbfa247eaa12 | 182 |
package com.doublechain.flowable.formaction;
import com.doublechain.flowable.BaseCandidateEntity;
public class CandidateFormAction extends BaseCandidateEntity<FormAction>{
}
| 16.545455 | 73 | 0.835165 |
ee4b98ea8dc6452b5e13a9830b64de539dbbc6ea | 597 | package com.intellij.boot.modules.authentication.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.intellij.boot.entity.SysPlatform;
/**
* @author tian
* @description 针对表【sys_platform】的数据库操作Service
* @createDate 2021-12-24 10:31:57
*/
public interface SysPlatformService extends IService<SysPlatform> {
/**
* 根据 key 查询客户端类型
*
* @return 客户端类型
*/
SysPlatform loadPlatform();
/**
* 根据 key 查询客户端类型
*
* @param key 客户端类型 key
* @return 客户端类型
*/
public SysPlatform loadPlatformByPlatformKey(String key);
}
| 21.321429 | 67 | 0.683417 |
db1917908f2474cb9dfe6cb31ea3b8339abee3a2 | 2,239 | package com.example.android.gbooksearch;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.GradientDrawable;
import android.media.MediaPlayer;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import static android.R.attr.name;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
/**
* Created by pasha on 30/08/2017.
*/
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Activity context, ArrayList<Book> bookObject)
{
super(context, 0, bookObject);
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
final Book currentBook = getItem(position);
//Title TextView
TextView _title = (TextView) listItemView.findViewById(R.id.title);
_title.setText(currentBook.getTitle());
//Author TextView
TextView _author = (TextView) listItemView.findViewById(R.id.author);
_author.setText("Author(s): " + currentBook.getAuthors());
//Description TextView
TextView _description = (TextView) listItemView.findViewById(R.id.description);
_description.setText(currentBook.getDescription());
//Book cover ImageView
ImageView _imgage = (ImageView) listItemView.findViewById(R.id.img);
String temp_url = currentBook.getThumbnailLink();
Picasso.with(this.getContext()).load(temp_url).into(_imgage); //This will auto fetch image from the given url
return listItemView;
}
}
| 31.097222 | 117 | 0.72845 |
a844097a72074a6ee5a9712e1bbe805eed59e4cd | 4,349 | package ng.prk.prkngandroid.ui.dialog;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import org.adw.library.widgets.discreteseekbar.DiscreteSeekBar;
import ng.prk.prkngandroid.Const;
import ng.prk.prkngandroid.R;
public class DurationDialog extends DialogFragment {
private static final String TAG = "DurationDialog ";
private OnDurationChangedListener listener;
public static DurationDialog newInstance(float duration) {
final DurationDialog dialog = new DurationDialog();
final Bundle bundle = new Bundle();
bundle.putInt(Const.BundleKeys.CURRENT_INDEX, (int) Math.floor(duration));
dialog.setArguments(bundle);
return dialog;
}
@Override
public void onCreate(Bundle savedInstanceState) {
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (OnDurationChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnDurationChangedListener");
}
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final LayoutInflater inflater = LayoutInflater.from(getActivity());
final View view = inflater.inflate(R.layout.dialog_duration_discreet_seekbar, null);
final TextView vTitle = (TextView) view.findViewById(R.id.dialog_title);
final TextView vLegend = (TextView) view.findViewById(R.id.dialog_legend);
final DiscreteSeekBar seekBar = (DiscreteSeekBar) view.findViewById(R.id.seekbar_duration);
int currentDuration = getArguments().getInt(Const.BundleKeys.CURRENT_INDEX, 0);
seekBar.setProgress(currentDuration);
vTitle.setText(getDurationTitle(currentDuration));
vLegend.setText(getDurationLegend(currentDuration));
seekBar.setOnProgressChangeListener(new DiscreteSeekBar.OnProgressChangeListener() {
@Override
public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) {
vTitle.setText(getDurationTitle(value));
vLegend.setText(getDurationLegend(value));
}
@Override
public void onStartTrackingTouch(DiscreteSeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
}
});
return new android.app.AlertDialog.Builder(getActivity(), R.style.PrkngDialogStyle)
.setView(view)
.setPositiveButton(R.string.btn_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
listener.onDurationChanged(getTimeFilter(seekBar));
}
}
)
.setNegativeButton(R.string.btn_cancel, null)
.create();
}
@Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance()) {
getDialog().setDismissMessage(null);
}
super.onDestroyView();
}
private String getDurationTitle(int progress) {
if (progress == 0) {
return getResources().getString(R.string.quantity_half);
} else {
return String.valueOf(progress);
}
}
private String getDurationLegend(int progress) {
return getResources().getQuantityString(
R.plurals.duration_legend_hours,
progress == 0 ? 1 : progress);
}
private float getTimeFilter(DiscreteSeekBar seekBar) {
final int progress = seekBar.getProgress();
return progress == 0 ? 0.5f : progress;
}
public interface OnDurationChangedListener {
void onDurationChanged(float duration);
}
} | 33.453846 | 99 | 0.645666 |
ffd5a4439e0c4a2c65e803a928847ba56d8b83e9 | 2,781 | package com.google.cloud.training.flights;
import java.text.DecimalFormat;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.api.services.bigquery.model.TableRow;
import com.google.cloud.training.flights.AddRealtimePrediction.MyOptions;
@SuppressWarnings("serial")
public class BatchInputOutput extends InputOutput {
private static final Logger LOG = LoggerFactory.getLogger(InputOutput.class);
private static String getOutput(MyOptions opts) {
return "gs://BUCKET/flights/chapter10/output/".replace("BUCKET", opts.getBucket());
}
@Override
public PCollection<Flight> readFlights(Pipeline p, MyOptions options) {
String query = "SELECT EVENT_DATA FROM flights.simevents WHERE ";
query += " STRING(FL_DATE) = '2015-01-04' AND ";
query += " (EVENT = 'wheelsoff' OR EVENT = 'arrived') ";
LOG.info(query);
PCollection<Flight> allFlights = p //
.apply("ReadLines", BigQueryIO.read().fromQuery(query)) //
.apply("ParseFlights", ParDo.of(new DoFn<TableRow, Flight>() {
@ProcessElement
public void processElement(ProcessContext c) throws Exception {
TableRow row = c.element();
String line = (String) row.getOrDefault("EVENT_DATA", "");
Flight f = Flight.fromCsv(line);
if (f != null) {
c.outputWithTimestamp(f, f.getEventTimestamp());
}
}
}));
return allFlights;
}
@Override
public void writeFlights(PCollection<Flight> outFlights, MyOptions options) {
// PCollection<String> lines = addPredictionOneByOne(outFlights);
try {
PCollection<FlightPred> prds = addPredictionInBatches(outFlights);
PCollection<String> lines = predToCsv(prds);
lines.apply("Write", TextIO.write().to(getOutput(options) + "flightPreds").withSuffix(".csv"));
} catch (Throwable t) {
LOG.warn("Inference failed", t);
}
}
private PCollection<String> predToCsv(PCollection<FlightPred> preds) {
return preds.apply("pred->csv", ParDo.of(new DoFn<FlightPred, String>() {
@ProcessElement
public void processElement(ProcessContext c) throws Exception {
FlightPred pred = c.element();
String csv = String.join(",", pred.flight.getFields());
if (pred.ontime >= 0) {
csv = csv + "," + new DecimalFormat("0.00").format(pred.ontime);
} else {
csv = csv + ","; // empty string -> null
}
c.output(csv);
}})) //
;
}
}
| 36.592105 | 101 | 0.665948 |
e9b01757e8e66b1946b95f6725871a455a8a64f0 | 1,670 | package com.nik.base;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
/**
*
* @author Nikhil Nandyala
*
*/
public class ConfigReader {
private Properties properties;
private final String propertyFilePath = "src//test//resources//configs//Configuration.properties";
/**
*
*/
public ConfigReader() {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(propertyFilePath));
properties = new Properties();
try {
properties.load(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Configuration.properties not found at " + propertyFilePath);
}
}
/**
*
* @return
*/
public String getDriverPath() {
String driverPath = properties.getProperty("driverPath");
if (driverPath != null)
return driverPath;
else
throw new RuntimeException("driverPath not specified in the Configuration.properties file.");
}
/**
*
* @return
*/
public long getImplicitlyWait() {
String implicitlyWait = properties.getProperty("implicitlyWait");
if (implicitlyWait != null)
return Long.parseLong(implicitlyWait);
else
throw new RuntimeException("implicitlyWait not specified in the Configuration.properties file.");
}
/**
*
* @return
*/
public String getApplicationUrl() {
String url = properties.getProperty("url");
if (url != null)
return url;
else
throw new RuntimeException("url not specified in the Configuration.properties file.");
}
}
| 21.973684 | 100 | 0.702994 |
b3a20180cc45a210910c52372b7bf360c7109b38 | 3,514 | package cn.edu.hust.controller;
import cn.edu.hust.domain.Product;
import cn.edu.hust.domain.ShoppingItem;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
@WebServlet(name = "shoppingCartServlet",urlPatterns = {"/showProducts","/addProducts","/showCart"})
public class ShoppingCartServlet extends HttpServlet {
private List<Product> products=new ArrayList<Product>();
private final String SHOPPING_CART="ShoppingCart";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri=req.getRequestURI();
if(uri.endsWith("/showProducts"))
showProducts(req,resp);
else if(uri.endsWith("/addProducts"))
addProducts(req,resp);
else if(uri.endsWith("/showCart"))
showCart(req,resp);
}
private void showCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session=req.getSession();
HashMap<Integer,ShoppingItem> itemHashMap= (HashMap<Integer, ShoppingItem>) session.getAttribute(SHOPPING_CART);
if(itemHashMap==null)
itemHashMap=new HashMap<Integer,ShoppingItem>();
Collection<ShoppingItem> shoppingItems= itemHashMap.values();
req.setAttribute("shoppingItems",shoppingItems);
req.getRequestDispatcher("/cartDetail.jsp").forward(req,resp);
}
private void addProducts(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session=req.getSession();
int id=Integer.valueOf(req.getParameter("id"));
//从session中取出购物车
HashMap<Integer,ShoppingItem> cart=(HashMap<Integer, ShoppingItem>) session.getAttribute(SHOPPING_CART);
if(cart==null)
cart=new HashMap<>();
if(cart.get(id)==null){
Product product=products.get(id-1);
cart.put(id,new ShoppingItem(product,1));
}
else
{
ShoppingItem shoppingItem=cart.get(id);
shoppingItem.setQuantity(shoppingItem.getQuantity()+1);
cart.put(id,shoppingItem);
}
//将购物车放入到session中去
session.setAttribute(SHOPPING_CART,cart);
session.setMaxInactiveInterval(30*60);
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
private void showProducts(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("products",products);
req.getRequestDispatcher("/productList.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
@Override
public void init() throws ServletException {
products.add(new Product(1,"iphoneX","iphone首款全面屏手机",5988));
products.add(new Product(2,"iMac","苹果公司的台式电脑",58999));
products.add(new Product(3,"MacBookPro","苹果公司的高端系列笔记本",12888));
products.add(new Product(4,"联想小新系列","联想公司适合青年的笔记本电脑",5899));
products.add(new Product(5,"小米Mix3","小米公司出品的高端手机",3499));
products.add(new Product(6,"魅族16","魅族公司的高端系列手机",2899));
}
}
| 41.833333 | 120 | 0.695788 |
f8934cf3003009e599215085bed81902c5dfac60 | 7,399 | package Controller.GameRelated;
import Controller.AccountRelated.AccountController;
import Controller.MainController;
import Model.AccountRelated.Account;
import Model.AccountRelated.Admin;
import Model.AccountRelated.Gamer;
import Model.GameRelated.BattleSea.BattleSea;
import Model.GameRelated.Game;
import Model.GameRelated.Reversi.Reversi;
import View.GameRelated.GameView;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.stream.Collectors;
public class GameController {
private static GameController gameController;
private Game currentGameInSession = null;
// based on which menu _11GameMenu.getGameName() shows go to GameplayBattleSeaMenu or GameplayReversiMenu
public void runGame (String username2, String gameName) throws MainController.InvalidFormatException, AccountController.NoAccountExistsWithUsernameException, CantPlayWithAdminException, CantPlayWithYourselfException {
if (!username2.matches("[!-~]+"))
throw new MainController.InvalidFormatException("Second player's username");
if (!Account.accountExists(username2))
throw new AccountController.NoAccountExistsWithUsernameException();
if (username2.equals(Admin.getAdmin().getUsername()))
throw new CantPlayWithAdminException();
if (AccountController.getInstance().getCurrentAccLoggedIn().getUsername().equals(username2))
throw new CantPlayWithYourselfException();
Gamer player2 = (Gamer) Account.getAccount(username2);
Gamer finalPlayer2 = player2;
ArrayList<Gamer> players = new ArrayList<>() {{
add(((Gamer) AccountController.getInstance().getCurrentAccLoggedIn()));
add(finalPlayer2);
}};
Game game = null;
switch (gameName.toLowerCase()) {
case "battlesea" -> game = new BattleSea(players);
case "reversi" -> {
game = new Reversi(players);
((Reversi) game).emptyBoard();
}
}
Game.startGame(game);
setCurrentGameInSession(game);
}
public void addFaveGame (String gameName) {
Gamer gamer = (Gamer) AccountController.getInstance().getCurrentAccLoggedIn();
gamer.addToFaveGames(gameName);
}
public void displayGameHowToPlay () {
// GameView.getClient().displayGameHowToPlay(
// ((_11GameMenu) Menu.getMenuIn()).getGameName().equals(BattleSea.class.getSimpleName()) ? BattleSea.getBattleseaDetails() : Reversi.getReversiDetails()
// );
}
public void displayTurn () {
GameView.getInstance().displayTurn(
"Reversi",
GameController.getInstance().getCurrentGameInSession().gameEnded(),
gameController.getCurrentGameInSession().getTurnGamer().getUsername()
);
}
public Game getCurrentGameInSession () {
return currentGameInSession;
}
public void setCurrentGameInSession (Game currentGameInSession) {
getInstance().currentGameInSession = currentGameInSession;
}
public static GameController getInstance () {
if (gameController == null)
gameController = new GameController();
return gameController;
}
public void displayGameConclusion (Game game) {
String conclusion;
switch (game.getConclusion()) {
case DRAW -> conclusion = "D";
case PLAYER1_WIN -> conclusion = "1W";
case PLAYER2_WIN -> conclusion = "2W";
case IN_SESSION -> conclusion = "IS";
default -> conclusion = "";
}
Gamer player1Gamer = game.getListOfPlayers().get(0).getGamer(),
player2Gamer = game.getListOfPlayers().get(1).getGamer();
GameView.getInstance().displayGameConclusion(
conclusion,
player1Gamer.getUsername(),
player2Gamer.getUsername(),
game.getInGameScore(1),
game.getInGameScore(2)
);
}
public void displayScoreboardOfGame () {
// LinkedList<String> scoreBoard = getScoreboard(((_11GameMenu) Menu.getMenuIn()).getGameName());
// GameView.getClient().displayScoreboardOfGame(((_11GameMenu) Menu.getMenuIn()).getGameName(), scoreBoard);
}
public void editDetails (String gameName) {
String details = "";
while (true)
try {
// Menu.printAskingForInput(gameName + "'s Details[/c to cancel] -> ");
// details = Menu.getInputLine();
if (details.trim().equalsIgnoreCase("/c")) return;
else if (details.trim().equals(""))
throw new EmptyDetailsException();
break;
} catch (EmptyDetailsException e) {
// Menu.printErrorMessage(e.getMessage());
}
if (gameName.trim().equalsIgnoreCase("battlesea"))
BattleSea.setDetailsForBattlesea(details);
else
Reversi.setDetailsForReversi(details);
// Menu.printSuccessfulOperation("Details of " + gameName + " changed successfully.");
}
public void displayPrevGamesAndChooseToContinue () {
LinkedList<Game> unfinishedGames = new LinkedList<>();
// switch (((_11GameMenu) Menu.getMenuIn()).getGameName().toLowerCase()) {
// case "reversi" -> unfinishedGames = new LinkedList<>(Reversi.getAllReversiGames());
// case "battlesea" -> unfinishedGames = new LinkedList<>(BattleSea.getAllBattleSeaGames());
// }
unfinishedGames = unfinishedGames.stream()
.filter(game ->
!game.gameHasEnded() &&
game.getListOfPlayers().stream()
.anyMatch(player -> player.getUsername()
.equals(AccountController.getInstance().getCurrentAccLoggedIn().getUsername()))
)
.collect(Collectors.toCollection(LinkedList::new));
LinkedList<Game> finalUnfinishedGames = unfinishedGames;
GameView.getInstance().displayPrevGamesAndChooseToContinue(new LinkedList<>() {{
for (Game unfinishedGame : finalUnfinishedGames) {
String yourUsername = AccountController.getInstance().getCurrentAccLoggedIn().getUsername(),
opponentUsername = unfinishedGame.getOpponentOf(unfinishedGame.getPlayer((Gamer) Account.getAccount(yourUsername))).getUsername();
add("%s %s %d %d %s".formatted(
opponentUsername,
unfinishedGame.getListOfPlayers().get(0).getUsername(), // player1
unfinishedGame.getInGameScore(1), // score1
unfinishedGame.getInGameScore(2), // score2
unfinishedGame.getListOfPlayers().get(1).getUsername() //player2
));
}
}});
if (unfinishedGames.size() == 0) return;
int gameChoice;
while (true)
try {
// Menu.printAskingForInput("Which game to continue:[/c to cancel] ");
String choice = "";
// choice = Menu.getInputLine();
if (choice.trim().equalsIgnoreCase("/c")) return;
if (!choice.matches("[0-9]+"))
throw new MainController.InvalidInputException();
gameChoice = Integer.parseInt(choice);
if (gameChoice < 1 || gameChoice > unfinishedGames.size())
throw new MainController.InvalidInputException();
break;
} catch (MainController.InvalidInputException e) {
// Menu.printErrorMessage(e.getMessage());
}
currentGameInSession = unfinishedGames.get(gameChoice - 1);
}
public void removeFaveGame (String gameName) {
Gamer gamer = (Gamer) AccountController.getInstance().getCurrentAccLoggedIn();
gamer.removeFaveGame(gameName);
}
public static class CantPlayWithYourselfException extends Exception {
public CantPlayWithYourselfException () {
super("You should select another gamer's username than yourself to play with");
}
}
public static class CantPlayWithAdminException extends Exception {
public CantPlayWithAdminException () {
super("You can't play with Admin");
}
}
private static class EmptyDetailsException extends Exception {
public EmptyDetailsException () {
super("You can't set the game details to empty.");
}
}
}
| 32.738938 | 218 | 0.728071 |
89feabe5d22ba0de195e93844f0c830a3bae7287 | 711 | package com.navercorp.pinpoint.collector.dao.hbase.statistics;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MapLinkConfiguration {
private final boolean enableAvg;
private final boolean enableMax;
public MapLinkConfiguration(@Value("${collector.map-link.avg.enable:true}") boolean enableAvg,
@Value("${collector.map-link.max.enable:true}") boolean enableMax) {
this.enableAvg = enableAvg;
this.enableMax = enableMax;
}
public boolean isEnableAvg() {
return enableAvg;
}
public boolean isEnableMax() {
return enableMax;
}
}
| 28.44 | 100 | 0.691983 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.