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
|
---|---|---|---|---|---|
ad397c52a4f3663dc82b35e80db50f2a0d671a52 | 1,622 | package uk.gov.dwp.queue.triage.core.jms;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import uk.gov.dwp.queue.triage.core.domain.FailedMessage;
import uk.gov.dwp.queue.triage.id.FailedMessageId;
import javax.jms.JMSException;
import javax.jms.TextMessage;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class FailedMessageTransformerTest {
private static final FailedMessageId FAILED_MESSAGE_ID = FailedMessageId.newFailedMessageId();
private final FailedMessage failedMessage = mock(FailedMessage.class);
private final TextMessage textMessage = mock(TextMessage.class);
private final FailedMessageTransformer underTest = new FailedMessageTransformer();
@Test
public void processingContinuesObjectPropertyCannotBeWritten() throws JMSException {
when(failedMessage.getContent()).thenReturn("content");
when(failedMessage.getProperties()).thenReturn(ImmutableMap.of("foo", "bar", "ham", "eggs"));
when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID);
doThrow(new JMSException("Arrrghhhhh")).when(textMessage).setObjectProperty("foo", "bar");
underTest.transform(textMessage, failedMessage);
verify(textMessage).setText("content");
verify(textMessage).setObjectProperty("foo", "bar");
verify(textMessage).setObjectProperty("ham", "eggs");
verify(textMessage).setStringProperty(FailedMessageId.FAILED_MESSAGE_ID, FAILED_MESSAGE_ID.toString());
}
} | 41.589744 | 111 | 0.767571 |
bac5ca1fd5fc2642bf41d7436a288a9b9792bea4 | 518 | package cn.xueden.system.dao;
import cn.xueden.common.core.web.domain.SysLog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/*import com.baomidou.mybatisplus.mapper.BaseMapper;*/
import java.util.List;
import java.util.Map;
/**功能描述:系统日志 Mapper 接口
* @Auther:http://www.xueden.cn
* @Date:2020/3/6
* @Description:cn.xueden.modules.system.dao
* @version:1.0
*/
public interface LogDao extends BaseMapper<SysLog> {
List<Map> selectSelfMonthData();
List<Map> selectSelfMonthDataByProvince();
}
| 21.583333 | 55 | 0.747104 |
fc62fe61b1159fdf474b850b419436163c12826b | 6,027 | /*
* Copyright 2018. AppDynamics LLC and its affiliates.
* All Rights Reserved.
* This is unpublished proprietary source code of AppDynamics LLC and its affiliates.
* The copyright notice above does not evidence any actual or intended publication of such source code.
*
*/
package com.appdynamics.extensions.siteminder.metrics;
import com.appdynamics.extensions.yml.YmlReader;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.singularity.ee.agent.systemagent.api.MetricWriter;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MetricPropertiesBuilderTest {
MetricPropertiesBuilder builder = new MetricPropertiesBuilder();
@Test
public void whenNoComponentConfig_thenReturnEmptyMap(){
Map<String,MetricProperties> propsMap = builder.build(null);
Assert.assertTrue(propsMap.size() == 0);
}
@Test
public void whenEmptyComponentConfig_thenReturnEmptyMap(){
Map<String,MetricProperties> propsMap = builder.build(Maps.newHashMap());
Assert.assertTrue(propsMap.size() == 0);
}
@Test
public void whenConfigWithGlobalPropsNoLocalOverrides_thenSetProps(){
Map configMap = YmlReader.readFromFileAsMap(new File(this.getClass().getResource("/conf/config_with_global_props.yml").getFile()));
Map instance = (Map)((List)configMap.get("instances")).get(0);
List<Map> componentConfigs = (List<Map>)instance.get("metrics");
Map<String,MetricProperties> propsMap = builder.build(componentConfigs.get(0));
MetricProperties props = propsMap.get("1.3.6.1.4.1.2552.200.300.1.3.1.17");
Assert.assertTrue(props.getAggregationType().equals("SUM"));
Assert.assertTrue(props.getTimeRollupType().equals("SUM"));
Assert.assertTrue(props.getClusterRollupType().equals("INDIVIDUAL"));
Assert.assertTrue(props.getKeyPrefix().equals("policyServer"));
Assert.assertTrue(props.getMultiplier() == 10);
Assert.assertTrue(props.isDelta());
Assert.assertTrue(props.getMetricName().equals("policyServerMaxSockets"));
}
@Test
public void whenConfigWithLocalOverridesNoGlobalProps_thenSetProps(){
Map configMap = YmlReader.readFromFileAsMap(new File(this.getClass().getResource("/conf/config_with_local_overrides.yml").getFile()));
Map instance = (Map)((List)configMap.get("instances")).get(0);
List<Map> componentConfigs = (List<Map>)instance.get("metrics");
Map<String,MetricProperties> propsMap = builder.build(componentConfigs.get(0));
MetricProperties props = propsMap.get("1.3.6.1.4.1.2552.200.300.1.3.1.5");
Assert.assertTrue(props.getAggregationType().equals("AVERAGE"));
Assert.assertTrue(props.getTimeRollupType().equals("AVERAGE"));
Assert.assertTrue(props.getClusterRollupType().equals("INDIVIDUAL"));
Assert.assertTrue(props.getKeyPrefix().equals("policyServer"));
Assert.assertTrue(props.isDelta());
Assert.assertTrue(props.getMetricName().equals("policyServerStatus"));
Assert.assertTrue(props.getConversionValues().get("$default").equals("0"));
}
@Test
public void whenConfigWithGlobalPropsAndLocalOverrides_thenSetProps(){
Map configMap = YmlReader.readFromFileAsMap(new File(this.getClass().getResource("/conf/config_with_global_and_local_overrides.yml").getFile()));
Map instance = (Map)((List)configMap.get("instances")).get(0);
List<Map> componentConfigs = (List<Map>)instance.get("metrics");
Map<String,MetricProperties> propsMap = builder.build(componentConfigs.get(0));
MetricProperties props = propsMap.get("1.3.6.1.4.1.2552.200.300.1.3.1.17");
Assert.assertTrue(props.getAggregationType().equals("SUM"));
Assert.assertTrue(props.getTimeRollupType().equals("SUM"));
Assert.assertTrue(props.getClusterRollupType().equals("INDIVIDUAL"));
Assert.assertTrue(props.getKeyPrefix().equals("policyServer"));
Assert.assertTrue(props.getMultiplier() == 10);
Assert.assertTrue(props.isDelta());
Assert.assertTrue(props.getMetricName().equals("policyServerMaxSockets"));
MetricProperties props1 = propsMap.get("1.3.6.1.4.1.2552.200.300.1.3.1.22");
Assert.assertTrue(props1.getAggregationType().equals("AVERAGE"));
Assert.assertTrue(props1.getTimeRollupType().equals("AVERAGE"));
Assert.assertTrue(props1.getClusterRollupType().equals("COLLECTIVE"));
Assert.assertTrue(props1.getKeyPrefix().equals("policyServer"));
Assert.assertFalse(props1.isDelta());
Assert.assertTrue(props1.getMetricName().equals("policyServerAzRejectCount"));
Assert.assertTrue(props1.getMultiplier() == 10);
Assert.assertTrue(props1.getConversionValues() == null);
}
@Test
public void whenConfigWithNoGlobalPropsAndNoLocalOverrides_thenSetProps(){
Map configMap = YmlReader.readFromFileAsMap(new File(this.getClass().getResource("/conf/config_with_no_global_props_no_local_overrides.yml").getFile()));
Map instance = (Map)((List)configMap.get("instances")).get(0);
List<Map> componentConfigs = (List<Map>)instance.get("metrics");
Map<String,MetricProperties> propsMap = builder.build(componentConfigs.get(0));
MetricProperties props = propsMap.get("1.3.6.1.4.1.2552.200.300.1.3.1.17");
Assert.assertTrue(props.getAggregationType().equals("AVERAGE"));
Assert.assertTrue(props.getTimeRollupType().equals("AVERAGE"));
Assert.assertTrue(props.getClusterRollupType().equals("INDIVIDUAL"));
Assert.assertTrue(props.getKeyPrefix().equals("policyServer"));
Assert.assertTrue(props.getMultiplier() == 1);
Assert.assertFalse(props.isDelta());
Assert.assertFalse(props.isAggregation());
Assert.assertTrue(props.getMetricName().equals("policyServerMaxSockets"));
}
}
| 53.336283 | 161 | 0.714452 |
aef83393b4b3e8fb7c2f0ab8ecbbd2bc0dd7ba43 | 5,269 | package com.app.staysafefinal;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.app.staysafefinal.fragment.BrotherscrollFragment;
import com.app.staysafefinal.fragment.FatherscrollFragment;
import com.app.staysafefinal.fragment.GmfatherscrollFragment;
import com.app.staysafefinal.fragment.MotherscrollFragment;
import com.app.staysafefinal.fragment.SisterscrollFragment;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.doubleclick.PublisherInterstitialAd;
import java.util.ArrayList;
import java.util.List;
public class fatherActivity extends AppCompatActivity {
private ViewPager familypager;
private String familyMember ="fathercard";
private int pagerNumber;
private ProfilePage admob;
private AdView mAdView;
private PublisherInterstitialAd mPublisherInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_father);
familypager = findViewById(R.id.familypager);
Intent intent = getIntent();
String fatherValue = intent.getExtras().getString("fathercard");
String motherValue = intent.getExtras().getString("mothercard");
String sisterValue = intent.getExtras().getString("sistercard");
String broValue = intent.getExtras().getString("brothercard");
String gmfatherValue = intent.getExtras().getString("gmfathercard");
initAdmob();
if ( fatherValue!=null) {
if (fatherValue.equals("fathercard")) {
Log.i("yarab", intent.getExtras().getString("fathercard"));
setupViewPager(familypager);
familypager.setCurrentItem(0);
}
}
if(motherValue!=null){
if (motherValue.equals("mothercard")) {
Log.i("yarab", intent.getExtras().getString("mothercard"));
setupViewPager(familypager);
familypager.setCurrentItem(1);
}
}
if(sisterValue!=null){
if (sisterValue.equals("sistercard")) {
Log.i("yarab", intent.getExtras().getString("sistercard"));
setupViewPager(familypager);
familypager.setCurrentItem(2);
}
}
if(broValue!=null){
if (broValue.equals("brothercard")) {
Log.i("yarab", intent.getExtras().getString("brothercard"));
setupViewPager(familypager);
familypager.setCurrentItem(3);
}
}
if(gmfatherValue!=null){
if (gmfatherValue.equals("gmfathercard")) {
Log.i("yarab", intent.getExtras().getString("gmfathercard"));
setupViewPager(familypager);
familypager.setCurrentItem(4);
}
}
//setupViewPager(familypager);
// Log.i("yarab",intent.getExtras().getString("fathercard"));
}
private void setupViewPager(ViewPager viewPager) {
fatherActivity.ViewPagerAdapter adapter = new fatherActivity.ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FatherscrollFragment());
adapter.addFragment(new MotherscrollFragment());
adapter.addFragment(new SisterscrollFragment());
adapter.addFragment(new BrotherscrollFragment());
adapter.addFragment(new GmfatherscrollFragment());
viewPager.setAdapter(adapter);
//viewPager.setOffscreenPageLimit(3);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
// mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void initAdmob() {
mPublisherInterstitialAd = new PublisherInterstitialAd(this);
mPublisherInterstitialAd.setAdUnitId("ca-app-pub-6198897372919858/4521011709");
//AdView adView = new AdView(this);
mAdView = findViewById(R.id.adViewFather);
//mAdView.setAdSize(AdSize.BANNER);
//mAdView.setAdUnitId("ca-app-pub-6198897372919858/2861565235");
AdRequest adRequest = new AdRequest.Builder().build();
//mAdView.setAdSize(AdSize.INVALID);
mAdView.loadAd(adRequest);
}
}
| 27.731579 | 115 | 0.654773 |
83375a19c003238bbdc32259d9ec1e26b20d8638 | 3,537 | // RobotBuilder Version: 3.1
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package frc.robot;
import edu.wpi.first.wpilibj.SerialPort;
import edu.wpi.first.wpilibj.kinematics.DifferentialDriveKinematics;
import edu.wpi.first.wpilibj.util.Units;
/**
* The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean
* constants. This class should not be used for any other purpose. All constants should be
* declared globally (i.e. public static). Do not put anything functional in this class.
*
* <p>It is advised to statically import this class (or one of its inner classes) wherever the
* constants are needed, to reduce verbosity.
*/
public class Constants {
public static final class DriveConstants {
public static final int kLeft = 0;
public static final int kRight = 1;
public static final SerialPort.Port kAHRS = SerialPort.Port.kUSB;
//By index: Enc A, Enc B, Absolute
public static final int[] kEncoderLeft = {0,1,2};
public static final int[] kEncoderRight = {6,7,8};
//Characterization Values for the individual sides.
//Right
public static final double kSR = 1.63;
public static final double kVR = 2.85;
public static final double kAR = 0.0046;
//Left
public static final double kSL = 1.9;
public static final double kVL = 2.76;
public static final double kAL = 0.00317;
//The hexbore encoder has 2048 cycles per revolution, since it is quadrature, it has 8192 pulses.
//https://www.revrobotics.com/content/docs/REV-11-1271-DS.pdf
public static final double kDistancePerPulse = (Units.inchesToMeters(6)*Math.PI)/(2048);
public static final boolean bLeftInverted = false;
public static final boolean bRightInverted = false;
public static final double kAcceleration = 1;
public static double kPL = 3.48; //TODO find correct kPL and kPR
public static double kPR = 3.64;
// TODO: get combined values
public static double kSC = 1.97;
public static double kVC = 2.89;
public static double kAC = 0.00176;
//TrackWidth: The horizontal distance between wheels.
//As defined by WPILIB, the distance between the left and right wheels.
//https://docs.wpilib.org/en/stable/docs/software/examples-tutorials/trajectory-tutorial/entering-constants.html#differentialdrivekinematics
public static final double kTrackWidth = Units.inchesToMeters(21.5);
public static DifferentialDriveKinematics kKinematics = new DifferentialDriveKinematics(kTrackWidth);
}
public static final class IntakeConstants {
public static final int kIntake = 2;
}
public static final class AutoConstants {
public static final double kRamseteB = 2;
public static final double kRamseteZeta = 0.7;
// pathfinding constants
//Meters Per Second Squared
public static final double kMaxAcceleration = 1;
//Meters Per Second
public static final double kMaxSpeed = 1.5;
}
}
| 38.868132 | 148 | 0.702856 |
da1e44a1c27581b006639bc8ebdf510d671e1714 | 8,076 | package br.com.fernando.chapter08_enterpriseJavaBeans.part02_statelessSessionBeans;
import static br.com.fernando.Util.APP_FILE_TARGET;
import static br.com.fernando.Util.EMBEDDED_JEE_TEST_APP_NAME;
import static br.com.fernando.Util.HTTP_PORT;
import static br.com.fernando.Util.downVariables;
import static br.com.fernando.Util.startVariables;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
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 org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.myembedded.jeecontainer.MyEmbeddedJeeContainer;
import org.myembedded.pack.EmbeddedEar;
import org.myembedded.pack.EmbeddedEjb;
import org.myembedded.pack.EmbeddedResource;
import org.myembedded.pack.EmbeddedWar;
import org.myembedded.pack.JeeVersion;
public class StatelessSessionBeans01 {
// ==================================================================================================================================================================
// A stateless session bean does not contain any conversational state for a specific client.
// All instances of a stateless bean are equivalent, so the container can choose to delegate a client-invoked method to any available instance.
//
// Since stateless session beans do not contain any state, they don't need to be passivated.
//
// This is a POJO marked with the @Stateless annotation. That's all it takes to convert a POJO to a stateless session bean.
// All public methods of the bean may be invoked by a client.
//
// This style of bean declaration is called as a no-interface view. Such a bean is only locally accessible to clients packaged in the same archive.
@Stateless
public static class AccountSessionBean {
private float amount = 0;
// As stateless beans do not store any state, the container can pool the instances, and all of them are treated equally from a client's perspective.
// Any instance of the bean can be used to service the client's request.
// The PostConstruct and PreDestroy lifecycle callback methods are available for stateless session beans.
//
// The PostConstruct callback method is invoked after the no-args constructor is invoked
// and all the dependencies have been injected, and before the first business method is invoked on the bean.
// This method is typically where all the resources required for the bean are initialized.
@PostConstruct
public void postConstruct() {
System.out.println("PostConstruct!");
}
// The PreDestroy life-cycle callback is called before the instance is removed by the container.
// This method is where all the resources acquired during PostConstruct are released.
@PreDestroy
public void preDestroy() {
System.out.println("PreDestroy!");
}
public String withdraw(float amount) {
this.amount -= amount;
return "Withdrawn: " + amount;
}
public String deposit(float amount) {
this.amount += amount;
return "Deposited: " + amount;
}
public float getAmount() {
return this.amount;
}
}
@Stateless
public static class AccountSessionBeanWithInterface implements Account {
@Override
public String withdraw(float amount) {
return "Withdrawn: " + amount;
}
@Override
public String deposit(float amount) {
return "Deposited: " + amount;
}
}
// If the bean needs to be remotely accessible, it must define a separate business interface annotated with @Remote:
@Remote
public static interface Account {
public String withdraw(float amount);
public String deposit(float amount);
}
// ==================================================================================================================================================================
@WebServlet(urlPatterns = { "/TestServletWithInterface" })
public static class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private Account accountBean;
@EJB
private AccountSessionBean accountSessionBean;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Stateless Bean (with Interface)</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Stateless Bean (with Interface)</h1>");
out.println("<h2>Withdraw and Deposit</h2>");
out.println(accountBean.deposit((float) 5.0));
out.println(accountSessionBean.withdraw((float) 5.0));
out.println("</body>");
out.println("</html>");
}
}
// ==================================================================================================================================================================
public static void main(String[] args) throws Exception {
startVariables();
try (final MyEmbeddedJeeContainer embeddedJeeServer = new MyEmbeddedJeeContainer();) {
final EmbeddedWar war = new EmbeddedWar(EMBEDDED_JEE_TEST_APP_NAME);
war.addWebInfFiles(EmbeddedResource.add("beans.xml", "src/main/resources/chapter14_jms/beans.xml"));
war.addClasses(TestServlet.class);
final EmbeddedEjb ejb = new EmbeddedEjb(EMBEDDED_JEE_TEST_APP_NAME);
ejb.addMetaInfFiles(EmbeddedResource.add("beans.xml", "src/main/resources/beans.xml"));
ejb.addMetaInfFiles(EmbeddedResource.add("glassfish-ejb-jar.xml", "src/main/resources/chapter08_enterpriseJavaBeans/glassfish-ejb-jar.xml"));
ejb.addClasses(Account.class, AccountSessionBeanWithInterface.class, AccountSessionBean.class);
final EmbeddedEar ear = new EmbeddedEar(EMBEDDED_JEE_TEST_APP_NAME, JeeVersion.JEE_7);
ear.addModules(war);
ear.addModules(ejb);
final File earFile = ear.exportToFile(APP_FILE_TARGET);
embeddedJeeServer.start(HTTP_PORT);
embeddedJeeServer.deploy(EMBEDDED_JEE_TEST_APP_NAME, earFile.getAbsolutePath());
final HttpClient httpClient = HttpClientBuilder.create().build();
final HttpResponse response = httpClient.execute(new HttpGet("http://localhost:" + HTTP_PORT + "/" + EMBEDDED_JEE_TEST_APP_NAME + "/ServletPrincipal"));
System.out.println(response);
final Context context = new InitialContext();
// Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
// service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
final Account sut = (Account) context.lookup("java:global/embeddedJeeContainerTest/embeddedJeeContainerTestejb/AccountSessionBeanWithInterface");
// must be empty, because it's another session
System.out.println(sut.withdraw(5.0F));
} catch (final Exception ex) {
System.out.println(ex);
}
downVariables();
}
}
| 42.730159 | 169 | 0.644626 |
b8c9dbe299c5e765eecd2ac406ed6142d5e1bf2d | 5,268 | package de.adito.ojcms.utils;
import org.jetbrains.annotations.*;
import java.util.*;
import java.util.function.*;
/**
* An index based iterator implementation.
* Supports custom start and end indices and might be supplied with a remover function.
*
* @param <ELEMENT> the elements provided by the iterator
* @author Simon Danner, 28.02.2018
*/
public final class IndexBasedIterator<ELEMENT> implements Iterator<ELEMENT>
{
private final IntFunction<ELEMENT> elementProvider;
private final IntSupplier sizeSupplier;
@Nullable
private final IntConsumer remover;
private int index;
private int lastIndex = -1;
private int endIndexExclusive;
private int expectedSize;
/**
* Creates a builder to create the index based iterator.
*
* @param pElementProvider a function providing an element for a given index
* @param pSizeProvider provider for the size of the collection to iterate
* @param <ELEMENT> the elements provided by the iterator
* @return a builder for the iterator. Use {@link Builder#createIterator()} to create it finally.
*/
public static <ELEMENT> Builder<ELEMENT> buildIterator(IntFunction<ELEMENT> pElementProvider, IntSupplier pSizeProvider)
{
return new Builder<>(pElementProvider, pSizeProvider);
}
/**
* Creates a new index based iterator.
*
* @param pElementProvider a function providing an element for a given index
* @param pSizeSupplier a elementProvider for the current size of the data structure to iterate
* @param pStartIndex the start index
* @param pEndIndexExclusive the end index (exclusive)
* @param pRemover an optional action to remove an element at a given index
*/
private IndexBasedIterator(IntFunction<ELEMENT> pElementProvider, IntSupplier pSizeSupplier, int pStartIndex, int pEndIndexExclusive,
@Nullable IntConsumer pRemover)
{
index = pStartIndex;
endIndexExclusive = pEndIndexExclusive;
elementProvider = Objects.requireNonNull(pElementProvider);
sizeSupplier = Objects.requireNonNull(pSizeSupplier);
expectedSize = sizeSupplier.getAsInt();
remover = pRemover;
}
@Override
public boolean hasNext()
{
return index < endIndexExclusive;
}
@Override
public ELEMENT next()
{
if (!hasNext())
throw new NoSuchElementException();
if (expectedSize != sizeSupplier.getAsInt())
throw new ConcurrentModificationException();
lastIndex = index;
return elementProvider.apply(index++);
}
@Override
public void remove()
{
if (remover == null)
throw new UnsupportedOperationException();
if (lastIndex < 0)
throw new IllegalStateException();
if (expectedSize != sizeSupplier.getAsInt())
throw new ConcurrentModificationException();
remover.accept(lastIndex);
index = lastIndex;
lastIndex = -1;
endIndexExclusive--;
expectedSize--;
}
/**
* Builds the index based iterator.
*
* @param <ELEMENT> the elements provided by the iterator
*/
public static class Builder<ELEMENT>
{
private final IntFunction<ELEMENT> elementProvider;
private final IntSupplier sizeSupplier;
private int start = -1;
private int end = -1;
@Nullable
private IntConsumer remover;
/**
* Creates the builder initially with least required parameters
*
* @param pElementProvider a function providing an element for a given index
* @param pSizeSupplier a function providing an element for a given index
*/
public Builder(IntFunction<ELEMENT> pElementProvider, IntSupplier pSizeSupplier)
{
elementProvider = pElementProvider;
sizeSupplier = pSizeSupplier;
}
/**
* Sets a certain start index for the iterator.
*
* @param pStartIndex the index to start the iteration from
* @return the builder to enable a pipelining mechanism
*/
public Builder<ELEMENT> startAtIndex(int pStartIndex)
{
start = pStartIndex;
return this;
}
/**
* Sets a certain end index for the iterator.
* The index is considered as exclusive.
*
* @param pEndIndexExclusive the index to end the iteration before from (exclusive)
* @return the builder to enable a pipelining mechanism
*/
public Builder<ELEMENT> endBeforeIndex(int pEndIndexExclusive)
{
end = pEndIndexExclusive;
return this;
}
/**
* Adds a remover action to the iterator which enables {@link Iterator#remove()} to be supported.
*
* @param pRemover an action to remove an element at a given index
* @return the builder to enable a pipelining mechanism
*/
public Builder<ELEMENT> withRemover(@NotNull IntConsumer pRemover)
{
remover = Objects.requireNonNull(pRemover);
return this;
}
/**
* Creates the iterator finally.
*
* @return the newly created iterator based on this builder
*/
public Iterator<ELEMENT> createIterator()
{
final int startIndex = start == -1 ? 0 : start;
final int endIndex = end == -1 ? sizeSupplier.getAsInt() : end;
return new IndexBasedIterator<>(elementProvider, sizeSupplier, startIndex, endIndex, remover);
}
}
}
| 30.988235 | 135 | 0.691344 |
8097536a3557db5c14ce381f277d6156ab082784 | 1,483 | /*
* Copyright 2013-2021 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.sleuth.instrument.web.mvc;
import org.springframework.cloud.sleuth.docs.DocumentedSpan;
import org.springframework.cloud.sleuth.docs.TagKey;
enum SleuthMvcSpan implements DocumentedSpan {
/**
* Span around a HandlerInterceptor. Will continue the current span and tag it
*/
MVC_HANDLER_INTERCEPTOR_SPAN {
@Override
public String getName() {
return "%s";
}
@Override
public TagKey[] getTagKeys() {
return Tags.values();
}
};
enum Tags implements TagKey {
/**
* Class name where a method got annotated with @Scheduled.
*/
CLASS {
@Override
public String getKey() {
return "mvc.controller.class";
}
},
/**
* Method name that got annotated with @Scheduled.
*/
METHOD {
@Override
public String getKey() {
return "mvc.controller.method";
}
}
}
}
| 22.815385 | 79 | 0.703304 |
b3c917b5b3194aa6df6bb560e54e73b6f8689775 | 9,338 | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor.preferences;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Spinner;
import com.archimatetool.editor.diagram.sketch.ISketchEditor;
import com.archimatetool.model.ITextAlignment;
/**
* Diagram Appearance Preferences Tab panel
*
* @author Phillip Beauvoir
*/
public class DiagramAppearancePreferenceTab implements IPreferenceConstants {
private Combo fDefaultGradientCombo;
private String[] GRADIENT_STYLES = {
Messages.DiagramAppearancePreferenceTab_16,
Messages.DiagramAppearancePreferenceTab_17,
Messages.DiagramAppearancePreferenceTab_18,
Messages.DiagramAppearancePreferenceTab_19,
Messages.DiagramAppearancePreferenceTab_20
};
private Spinner fDefaultArchimateFigureWidthSpinner, fDefaultArchimateFigureHeightSpinner;
private Combo fWordWrapStyleCombo;
private String[] WORD_WRAP_STYLES = {
Messages.DiagramAppearancePreferenceTab_4,
Messages.DiagramAppearancePreferenceTab_5,
Messages.DiagramAppearancePreferenceTab_6
};
private Combo fDefaultSketchBackgroundCombo;
private Combo fDefaultTextAlignmentCombo, fDefaultTextPositionCombo;
private String[] TEXT_ALIGNMENTS = {
Messages.DiagramAppearancePreferenceTab_8,
Messages.DiagramAppearancePreferenceTab_9,
Messages.DiagramAppearancePreferenceTab_10
};
private int[] TEXT_ALIGNMENT_VALUES = {
ITextAlignment.TEXT_ALIGNMENT_LEFT,
ITextAlignment.TEXT_ALIGNMENT_CENTER,
ITextAlignment.TEXT_ALIGNMENT_RIGHT
};
private String[] TEXT_POSITIONS = {
Messages.DiagramAppearancePreferenceTab_11,
Messages.DiagramAppearancePreferenceTab_12,
Messages.DiagramAppearancePreferenceTab_13
};
public Composite createContents(Composite parent) {
Composite client = new Composite(parent, SWT.NULL);
client.setLayout(new GridLayout());
// -------------- Global ----------------------------
Group globalGroup = new Group(client, SWT.NULL);
globalGroup.setText(Messages.DiagramAppearancePreferenceTab_0);
globalGroup.setLayout(new GridLayout(2, false));
globalGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Word wrap style
Label label = new Label(globalGroup, SWT.NULL);
label.setText(Messages.DiagramAppearancePreferenceTab_7);
fWordWrapStyleCombo = new Combo(globalGroup, SWT.READ_ONLY);
fWordWrapStyleCombo.setItems(WORD_WRAP_STYLES);
fWordWrapStyleCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// -------------- Defaults ----------------------------
Group defaultsGroup = new Group(client, SWT.NULL);
defaultsGroup.setText(Messages.DiagramAppearancePreferenceTab_1);
defaultsGroup.setLayout(new GridLayout(2, false));
defaultsGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Sizes
label = new Label(defaultsGroup, SWT.NULL);
label.setText(Messages.DiagramAppearancePreferenceTab_2);
fDefaultArchimateFigureWidthSpinner = new Spinner(defaultsGroup, SWT.BORDER);
fDefaultArchimateFigureWidthSpinner.setMinimum(30);
fDefaultArchimateFigureWidthSpinner.setMaximum(300);
label = new Label(defaultsGroup, SWT.NULL);
label.setText(Messages.DiagramAppearancePreferenceTab_3);
fDefaultArchimateFigureHeightSpinner = new Spinner(defaultsGroup, SWT.BORDER);
fDefaultArchimateFigureHeightSpinner.setMinimum(30);
fDefaultArchimateFigureHeightSpinner.setMaximum(300);
// Default Text Alignment
label = new Label(defaultsGroup, SWT.NULL);
label.setText(Messages.DiagramAppearancePreferenceTab_14);
fDefaultTextAlignmentCombo = new Combo(defaultsGroup, SWT.READ_ONLY);
fDefaultTextAlignmentCombo.setItems(TEXT_ALIGNMENTS);
fDefaultTextAlignmentCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Default Text Position
label = new Label(defaultsGroup, SWT.NULL);
label.setText(Messages.DiagramAppearancePreferenceTab_15);
fDefaultTextPositionCombo = new Combo(defaultsGroup, SWT.READ_ONLY);
fDefaultTextPositionCombo.setItems(TEXT_POSITIONS);
fDefaultTextPositionCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Default Gradient
label = new Label(defaultsGroup, SWT.NULL);
label.setText(Messages.DiagramFiguresPreferencePage_9);
fDefaultGradientCombo = new Combo(defaultsGroup, SWT.READ_ONLY);
fDefaultGradientCombo.setItems(GRADIENT_STYLES);
fDefaultGradientCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// -------------- Sketch ----------------------------
Group sketchGroup = new Group(client, SWT.NULL);
sketchGroup.setLayout(new GridLayout(2, false));
sketchGroup.setText(Messages.DiagramPreferencePage_19);
sketchGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Default Sketch background
label = new Label(sketchGroup, SWT.NULL);
label.setText(Messages.DiagramPreferencePage_20);
fDefaultSketchBackgroundCombo = new Combo(sketchGroup, SWT.READ_ONLY);
fDefaultSketchBackgroundCombo.setItems(ISketchEditor.BACKGROUNDS);
fDefaultSketchBackgroundCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
setValues();
return client;
}
private void setValues() {
fDefaultGradientCombo.select(getPreferenceStore().getInt(DEFAULT_GRADIENT) + 1); // Starts at -1
fWordWrapStyleCombo.select(getPreferenceStore().getInt(ARCHIMATE_FIGURE_WORD_WRAP_STYLE));
fDefaultArchimateFigureWidthSpinner.setSelection(getPreferenceStore().getInt(DEFAULT_ARCHIMATE_FIGURE_WIDTH));
fDefaultArchimateFigureHeightSpinner.setSelection(getPreferenceStore().getInt(DEFAULT_ARCHIMATE_FIGURE_HEIGHT));
// The values of these are 1, 2 and 4
fDefaultTextAlignmentCombo.select(getPreferenceStore().getInt(DEFAULT_ARCHIMATE_FIGURE_TEXT_ALIGNMENT) / 2);
// The values of these are 0, 1 and 2
fDefaultTextPositionCombo.select(getPreferenceStore().getInt(DEFAULT_ARCHIMATE_FIGURE_TEXT_POSITION));
fDefaultSketchBackgroundCombo.select(getPreferenceStore().getInt(SKETCH_DEFAULT_BACKGROUND));
}
private IPreferenceStore getPreferenceStore() {
return Preferences.STORE;
}
public boolean performOk() {
getPreferenceStore().setValue(DEFAULT_GRADIENT, fDefaultGradientCombo.getSelectionIndex() - 1); // Starts at -1
getPreferenceStore().setValue(ARCHIMATE_FIGURE_WORD_WRAP_STYLE, fWordWrapStyleCombo.getSelectionIndex());
getPreferenceStore().setValue(DEFAULT_ARCHIMATE_FIGURE_WIDTH, fDefaultArchimateFigureWidthSpinner.getSelection());
getPreferenceStore().setValue(DEFAULT_ARCHIMATE_FIGURE_HEIGHT, fDefaultArchimateFigureHeightSpinner.getSelection());
getPreferenceStore().setValue(DEFAULT_ARCHIMATE_FIGURE_TEXT_ALIGNMENT, TEXT_ALIGNMENT_VALUES[fDefaultTextAlignmentCombo.getSelectionIndex()]);
getPreferenceStore().setValue(DEFAULT_ARCHIMATE_FIGURE_TEXT_POSITION, fDefaultTextPositionCombo.getSelectionIndex());
getPreferenceStore().setValue(SKETCH_DEFAULT_BACKGROUND, fDefaultSketchBackgroundCombo.getSelectionIndex());
return true;
}
protected void performDefaults() {
fDefaultGradientCombo.select(getPreferenceStore().getDefaultInt(DEFAULT_GRADIENT) + 1); // Starts at -1
fWordWrapStyleCombo.select(getPreferenceStore().getDefaultInt(ARCHIMATE_FIGURE_WORD_WRAP_STYLE));
fDefaultArchimateFigureWidthSpinner.setSelection(getPreferenceStore().getDefaultInt(DEFAULT_ARCHIMATE_FIGURE_WIDTH));
fDefaultArchimateFigureHeightSpinner.setSelection(getPreferenceStore().getDefaultInt(DEFAULT_ARCHIMATE_FIGURE_HEIGHT));
fDefaultTextAlignmentCombo.select(getPreferenceStore().getDefaultInt(DEFAULT_ARCHIMATE_FIGURE_TEXT_ALIGNMENT) / 2); // Value = 2
fDefaultTextPositionCombo.select(getPreferenceStore().getDefaultInt(DEFAULT_ARCHIMATE_FIGURE_TEXT_POSITION));
fDefaultSketchBackgroundCombo.select(getPreferenceStore().getDefaultInt(SKETCH_DEFAULT_BACKGROUND));
}
} | 47.161616 | 151 | 0.708824 |
ef76d1d347805c2b35c687eed8d57b45680072fb | 688 | package org.sistcoop.persona.admin.client.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.sistcoop.persona.representations.idm.AccionistaRepresentation;
/**
* @author [email protected]
*/
public interface AccionistaResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public AccionistaRepresentation toRepresentation();
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public void update(AccionistaRepresentation rep);
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response remove();
} | 22.193548 | 73 | 0.797965 |
07c4042e6743dd7da7461db07bf042ec40b17d5d | 3,845 | /*
* 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.httprpc.xml;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Set;
/**
* {@link Map} adapter for XML elements.
*/
public class ElementAdapter extends AbstractMap<String, Object> {
private static class NodeListAdapter extends AbstractList<ElementAdapter> {
NodeList nodeList;
NodeListAdapter(NodeList nodeList) {
this.nodeList = nodeList;
}
@Override
public ElementAdapter get(int i) {
return new ElementAdapter((Element)nodeList.item(i));
}
@Override
public int size() {
return nodeList.getLength();
}
}
private Element element;
private static final String ATTRIBUTE_PREFIX = "@";
private static final String LIST_SUFFIX = "*";
/**
* Constructs a new element adapter.
*
* @param element
* The source element.
*/
public ElementAdapter(Element element) {
if (element == null) {
throw new IllegalArgumentException();
}
this.element = element;
}
@Override
public Object get(Object key) {
if (key == null) {
throw new IllegalArgumentException();
}
String name = key.toString();
Object value;
if (isAttribute(name)) {
name = getAttributeName(name);
if (element.hasAttribute(name)) {
value = element.getAttribute(name);
} else {
value = null;
}
} else {
if (isList(name)) {
value = new NodeListAdapter(element.getElementsByTagName(getListTagName(name)));
} else {
NodeList nodeList = element.getElementsByTagName(name);
if (nodeList.getLength() > 0) {
value = new ElementAdapter((Element)nodeList.item(0));
} else {
value = null;
}
}
}
return value;
}
@Override
public boolean containsKey(Object key) {
if (key == null) {
throw new IllegalArgumentException();
}
String name = key.toString();
if (isAttribute(name)) {
return element.hasAttribute(getAttributeName(name));
} else {
if (isList(name)) {
return true;
} else {
return element.getElementsByTagName(name).getLength() > 0;
}
}
}
@Override
public Set<Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return element.getTextContent();
}
private static boolean isAttribute(String name) {
return name.startsWith(ATTRIBUTE_PREFIX);
}
private static String getAttributeName(String name) {
return name.substring(ATTRIBUTE_PREFIX.length());
}
private static boolean isList(String name) {
return name.endsWith(LIST_SUFFIX);
}
private static String getListTagName(String name) {
return name.substring(0, name.length() - LIST_SUFFIX.length());
}
}
| 26.517241 | 96 | 0.592978 |
b8a807e2c622cce93de3353254adb689714df23a | 1,116 | package com.mirkocaserta.bruce.key;
import com.mirkocaserta.bruce.BruceException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.Test;
import java.security.Security;
import static com.mirkocaserta.bruce.Bruce.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RsaKeyPairWithCustomProviderTest {
static {
Security.addProvider(new BouncyCastleProvider());
}
private static final byte[] MESSAGE = "Hello".getBytes(UTF_8);
@Test
void generateAndUse() {
var keyPair = keyPair("RSA", "BC", 4096);
var signer = signer(keyPair.getPrivate(), "RIPEMD160withRSA/ISO9796-2");
var verifier = verifier(keyPair.getPublic(), "RIPEMD160withRSA/ISO9796-2");
var signature = signer.sign(MESSAGE);
assertTrue(verifier.verify(MESSAGE, signature));
}
@Test
void noSuchProvider() {
assertThrows(BruceException.class, () -> keyPair("RSA", "sgiao belo", 2048));
}
}
| 30.162162 | 85 | 0.718638 |
f56a7f63712e641e50c011ccd26a122e1bb1f0fe | 441 | package dexter.ir.list;
import dexter.ir.Expr;
import dexter.ir.Visitor;
import dexter.ir.bool.CallExpr;
import java.util.Arrays;
/**
* Created by Maaz Ahmad on 6/25/19.
*/
public class LengthExpr extends CallExpr
{
public LengthExpr (Expr list)
{
super("len", Arrays.asList(list));
}
public Expr list() { return args.get(0); }
@Override public <T> T accept(Visitor<T> p) { return p.visit(this); }
} | 20.045455 | 72 | 0.653061 |
c1c3abf2abd1f6e5e7def40388f651bbaf574ab7 | 1,314 | /*
Copyright 2016 Goldman Sachs.
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.gs.fw.common.mithra.util;
public class PerformanceDataPerOperation
{
private int totalOperations;
private int totalObjects;
private int totalTime;
public void addTime(int objectsFound, long time)
{
totalOperations++;
totalObjects += objectsFound;
totalTime += time;
}
public int getTotalOperations()
{
return totalOperations;
}
public int getTotalObjects()
{
return totalObjects;
}
public int getTotalTime()
{
return totalTime;
}
public void clear()
{
this.totalObjects = 0;
this.totalOperations = 0;
this.totalTime = 0;
}
}
| 23.890909 | 66 | 0.653729 |
a762b7cac60e0cd4fd47f1fc908ef511a00c4240 | 2,567 | /**
* Copyright 2015-2016 Debmalya Jash
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hr;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author debmalyajash
*
*/
public class Lighthouse {
/**
* @param args
*/
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
int n = Integer.parseInt(in.nextLine());
int[] radius = new int[n];
int maxLength = 0;
int radiusRow = 0;
char[][] board = new char[n][n];
for (int i = 0; i < n; i++) {
char[] each = in.nextLine().toCharArray();
board[i] = each;
}
if (maxLength < 3) {
// Not possible
System.out.println("0");
} else {
//
int proposedRadius = radius[radiusRow] / 2;
// Get the starting point of radius.
// Get the end point of radius.
int start = -1;
int end = n;
for (int i = 0; i < n; i++) {
if (start == -1 && board[radiusRow][i] == '.') {
start = i;
} else if (start != -1 && end == n && board[radiusRow][i] != '.') {
end = i - 1;
}
}
System.out.println(proposedRadius + " starts at " + start + " ends at " + end);
}
}
}
/**
* Find the radius of the biggest circle.
*
* @param board
* containing empty space '.' or blocking '*'.
* @return radius of the biggest circle.
*/
public static int getRadius(char[][] board) {
int[] rowWiseEmptySpaces = new int[board.length];
int[] colWiseEmptySpaces = new int[board.length];
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board.length; col++) {
// Continuous '.'
if (board[row][col] == '.') {
if (col > -1 && col < board.length - 2 && board[row][col + 1] == '.') {
rowWiseEmptySpaces[row]++;
} else if (col == board.length - 1 && board[row][col - 1] == '.'){
rowWiseEmptySpaces[row]++;
}
colWiseEmptySpaces[col]++;
}
}
}
System.out.println(Arrays.toString(rowWiseEmptySpaces));
System.out.println(Arrays.toString(colWiseEmptySpaces));
return 0;
}
}
| 27.021053 | 83 | 0.597585 |
a5a8e307349e19be523e781bf30a160eff1f712c | 6,183 | /**
* Copyright Intellectual Reserve, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.familysearch.api.client.gens;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import org.familysearch.api.client.FamilySearchCollectionState;
import org.familysearch.api.client.FamilySearchReferenceEnvironment;
import org.gedcomx.Gedcomx;
import org.gedcomx.conclusion.Identifier;
import org.gedcomx.conclusion.Person;
import org.gedcomx.links.Link;
import org.gedcomx.records.Collection;
import org.gedcomx.rs.client.PersonState;
import org.gedcomx.rs.client.SourceDescriptionsState;
import org.gedcomx.rs.client.StateTransitionOption;
import org.gedcomx.source.SourceDescription;
import org.gedcomx.types.ResourceType;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MultivaluedMap;
import java.net.URI;
import java.util.List;
public class GenealogiesTreeState extends FamilySearchCollectionState {
public GenealogiesTreeState() {
super();
}
public GenealogiesTreeState(FamilySearchReferenceEnvironment env) {
super(env);
}
public GenealogiesTreeState(URI uri) {
super(uri);
}
public GenealogiesTreeState(ClientRequest request, ClientResponse client, String accessToken, GenealogiesStateFactory stateFactory) {
super(request, client, accessToken, stateFactory);
}
@Override
protected GenealogiesTreeState clone(ClientRequest request, ClientResponse response) {
return new GenealogiesTreeState(request, response, this.accessToken, (GenealogiesStateFactory) this.stateFactory);
}
@Override
public GenealogiesTreeState ifSuccessful() {
return (GenealogiesTreeState) super.ifSuccessful();
}
@Override
public GenealogiesTreeState head(StateTransitionOption... options) {
return (GenealogiesTreeState) super.head(options);
}
@Override
public GenealogiesTreeState get(StateTransitionOption... options) {
return (GenealogiesTreeState) super.get(options);
}
@Override
public GenealogiesTreeState delete(StateTransitionOption... options) {
return (GenealogiesTreeState) super.delete(options);
}
@Override
public GenealogiesTreeState put(Gedcomx e, StateTransitionOption... options) {
return (GenealogiesTreeState) super.put(e, options);
}
@Override
public GenealogiesTreeState post(Gedcomx entity, StateTransitionOption... options) {
return (GenealogiesTreeState) super.post(entity, options);
}
@Override
public GenealogiesTreeState authenticateViaOAuth2Password(String username, String password, String clientId) {
return (GenealogiesTreeState) super.authenticateViaOAuth2Password(username, password, clientId);
}
@Override
public GenealogiesTreeState authenticateViaOAuth2Password(String username, String password, String clientId, String clientSecret) {
return (GenealogiesTreeState) super.authenticateViaOAuth2Password(username, password, clientId, clientSecret);
}
@Override
public GenealogiesTreeState authenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId, String clientSecret) {
return (GenealogiesTreeState) super.authenticateViaOAuth2AuthCode(authCode, redirect, clientId, clientSecret);
}
@Override
public GenealogiesTreeState authenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId) {
return (GenealogiesTreeState) super.authenticateViaOAuth2AuthCode(authCode, redirect, clientId);
}
@Override
public GenealogiesTreeState authenticateViaOAuth2ClientCredentials(String clientId, String clientSecret) {
return (GenealogiesTreeState) super.authenticateViaOAuth2ClientCredentials(clientId, clientSecret);
}
@Override
public GenealogiesTreeState authenticateViaOAuth2(MultivaluedMap<String, String> formData, StateTransitionOption... options) {
return (GenealogiesTreeState) super.authenticateViaOAuth2(formData, options);
}
@Override
public FamilySearchCollectionState addCollection(Collection collection, StateTransitionOption... options) {
throw new UnsupportedOperationException("Can't add a collection to a tree");
}
@Override
public FamilySearchCollectionState addCollection(Collection collection, SourceDescription sourceDescription, StateTransitionOption... options) {
throw new UnsupportedOperationException("Can't add a collection to a tree");
}
@Override
public GenealogiesPersonState addPerson(Person person, StateTransitionOption... options) {
Gedcomx entity = new Gedcomx();
entity.addPerson(person);
return addPerson(entity, options);
}
@Override
public GenealogiesPersonState addPerson(Gedcomx gx, StateTransitionOption... options) {
return (GenealogiesPersonState) super.addPerson(gx, options);
}
@Override
public GenealogiesPersonState readPerson(Person person, StateTransitionOption... options) {
return (GenealogiesPersonState) super.readPerson(person, options);
}
public SourceDescriptionsState readPersonsByExternalIds(List<Identifier> identifiers, StateTransitionOption... options) {
Link link = getLink("persons-by-external-ids");
if (link == null || link.getHref() == null) {
return null;
}
Gedcomx query = new Gedcomx();
for (Identifier identifier : identifiers) {
query = query.sourceDescription(new SourceDescription().resourceType(ResourceType.Person).identifier(identifier));
}
ClientRequest request = createAuthenticatedGedcomxRequest().entity(query).build(link.getHref().toURI(), HttpMethod.POST);
return ((GenealogiesStateFactory)this.stateFactory).newSourceDescriptionsState(request, invoke(request, options), this.accessToken);
}
}
| 37.932515 | 146 | 0.784894 |
471f57ecd0eeb2cc8f5dc8a43b1b22dffe9bcfcf | 2,921 | package com.oracle.cloud.compute.jenkins.model;
import java.util.Objects;
public class SSHKey {
// Modified from swagger-codegen -l jaxrs-cxf-client
// - renamed from SSHKeyResponse to SSHKey
private Boolean enabled = null;
private String key = null;
private String name = null;
private String uri = null;
public SSHKey enabled(Boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Indicates whether the key is enabled (<code>true</code>) or disabled.
* @return enabled
**/
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public SSHKey key(String key) {
this.key = key;
return this;
}
/**
* <p>The SSH public key value.
* @return key
**/
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public SSHKey name(String name) {
this.name = name;
return this;
}
/**
* <p>The three-part name of the object
* @return name
**/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SSHKey uri(String uri) {
this.uri = uri;
return this;
}
/**
* Uniform Resource Identifier
* @return uri
**/
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SSHKey ssHKeyResponse = (SSHKey) o;
return Objects.equals(this.enabled, ssHKeyResponse.enabled) &&
Objects.equals(this.key, ssHKeyResponse.key) &&
Objects.equals(this.name, ssHKeyResponse.name) &&
Objects.equals(this.uri, ssHKeyResponse.uri);
}
@Override
public int hashCode() {
return Objects.hash(enabled, key, name, uri);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SSHKey {\n");
sb.append(" enabled: ").append(toIndentedString(enabled)).append("\n");
sb.append(" key: ").append(toIndentedString(key)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" uri: ").append(toIndentedString(uri)).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 ");
}
}
| 22.820313 | 80 | 0.572749 |
6c84c3468717263c4f61152aee852348370c5f89 | 11,865 | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 ohos.devtools.views.trace.util;
import ohos.devtools.views.trace.DField;
import ohos.devtools.views.trace.Sql;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Database operation class class
*
* @since 2021/04/22 12:25
*/
public final class Db {
private static boolean isLocal;
private static volatile Db db = new Db();
private static String dbName = "trace.db";
private final String[] units = new String[] {"", "K", "M", "G", "T", "E"};
private LinkedBlockingQueue<Connection> pool = new LinkedBlockingQueue();
private Db() {
}
/**
* Gets the value of dbName .
*
* @return the value of java.lang.String
*/
public static String getDbName() {
return dbName;
}
/**
* Sets the dbName .
* <p>You can use getDbName() to get the value of dbName</p>
*
* @param dbName dbName
*/
public static void setDbName(final String dbName) {
Db.dbName = dbName;
}
/**
* Load the database file according to the file location variable
*
* @param isLocal isLocal
*/
public static void load(final boolean isLocal) {
Db.isLocal = isLocal;
final int maxConnNum = 10;
try {
Class.forName("org.sqlite.JDBC");
for (Connection connection : db.pool) {
connection.close();
}
db.pool.clear();
for (int size = 0; size < maxConnNum; size++) {
db.newConn().ifPresent(connection -> {
try {
db.pool.put(connection);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
});
}
db.newConn().ifPresent(connection -> {
try {
Statement statement = connection.createStatement();
String views = getSql("Views");
String[] split = views.split(";");
for (String str : split) {
statement.execute(str);
}
statement.close();
connection.close();
} catch (SQLException exception) {
exception.printStackTrace();
}
});
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException classNotFoundException) {
classNotFoundException.printStackTrace();
}
}
/**
* Get the current current db object
*
* @return Db db
*/
public static Db getInstance() {
if (db == null) {
db = new Db();
}
return db;
}
/**
* Read the sql directory under resource
*
* @param sqlName sqlName
* @return String sql
*/
public static String getSql(String sqlName) {
String tmp = Final.IS_RESOURCE_SQL ? "-self/" : "/";
String path = "sql" + tmp + sqlName + ".sql";
try (InputStream STREAM = DataUtils.class.getClassLoader().getResourceAsStream(path)) {
String sqlFile = IOUtils.toString(STREAM, Charset.forName("UTF-8"));
if (sqlFile.startsWith("/*")) {
return sqlFile.trim().substring(sqlFile.indexOf("*/") + 2);
} else {
return IOUtils.toString(STREAM, Charset.forName("UTF-8"));
}
} catch (UnsupportedEncodingException exception) {
exception.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
return "";
}
/**
* Get database connection
*
* @return Connection
*/
public Connection getConn() {
Connection connection = null;
try {
connection = pool.take();
} catch (InterruptedException exception) {
exception.printStackTrace();
}
return connection;
}
/**
* Return the connection to the database connection pool after use
*
* @param conn conn
*/
public void free(final Connection conn) {
try {
pool.put(conn);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
private Optional<Connection> newConn() {
URL path = URLClassLoader.getSystemClassLoader().getResource(dbName);
Connection conn = null;
try {
if (isLocal) {
conn = DriverManager.getConnection("jdbc:sqlite:" + dbName);
} else {
conn = DriverManager.getConnection("jdbc:sqlite::resource:" + path);
}
} catch (SQLException exception) {
exception.printStackTrace();
}
return Optional.ofNullable(conn);
}
/**
* Read the sql directory under resource
*
* @param em em
* @param res res
* @param args args
* @param <T> return type
*/
public <T> void query(Sql em, List<T> res, Object... args) {
String sql = String.format(Locale.ENGLISH, getSql(em.getName()), args);
query(sql, res);
}
/**
* query sql count
*
* @param em em
* @param args args
* @return int int
*/
public int queryCount(Sql em, Object... args) {
String sql = String.format(Locale.ENGLISH, getSql(em.getName()), args);
return queryCount(sql);
}
/**
* query count from sql
*
* @param sql sql
* @return int int
*/
public int queryCount(String sql) {
Statement stat = null;
ResultSet rs = null;
int count = 0;
Connection conn = getConn();
if (Objects.isNull(conn)) {
return 0;
}
try {
stat = conn.createStatement();
String tSql = sql.trim();
if (sql.trim().endsWith(";")) {
tSql = sql.trim().substring(0, sql.trim().length() - 1);
}
rs = stat.executeQuery("select count(1) as count from (" + tSql + ");");
while (rs.next()) {
count = rs.getInt("count");
}
} catch (SQLException exception) {
exception.printStackTrace();
} finally {
release(rs, stat, conn);
}
return count;
}
/**
* Read the sql directory under resource
*
* @param res res
* @param sql sql
* @param <T> return type
*/
public <T> void query(String sql, List<T> res) {
Statement stat = null;
ResultSet rs = null;
Connection conn = getConn();
if (Objects.isNull(conn)) {
return;
}
Type argument = getType(res);
try {
Class<T> aClass = (Class<T>) Class.forName(argument.getTypeName());
stat = conn.createStatement();
rs = stat.executeQuery(sql);
ArrayList<String> columnList = new ArrayList<>();
ResultSetMetaData rsMeta = rs.getMetaData();
int columnCount = rsMeta.getColumnCount();
for (int index = 1; index <= columnCount; index++) {
columnList.add(rsMeta.getColumnName(index));
}
while (rs.next()) {
T data = aClass.getConstructor().newInstance();
for (Field declaredField : aClass.getDeclaredFields()) {
declaredField.setAccessible(true);
DField annotation = declaredField.getAnnotation(DField.class);
if (Objects.nonNull(annotation) && columnList.contains(annotation.name())) {
setData(declaredField, data, rs, annotation);
}
}
res.add(data);
}
} catch (ClassNotFoundException | SQLException exception) {
exception.printStackTrace();
} catch (InstantiationException exception) {
exception.printStackTrace();
} catch (IllegalAccessException exception) {
exception.printStackTrace();
} catch (InvocationTargetException exception) {
exception.printStackTrace();
} catch (NoSuchMethodException exception) {
exception.printStackTrace();
} finally {
release(rs, stat, conn);
}
}
private <T> void setData(Field declaredField, T data, ResultSet rs, DField annotation)
throws SQLException, IllegalAccessException {
if (declaredField.getType() == Long.class || declaredField.getType() == long.class) {
declaredField.set(data, rs.getLong(annotation.name()));
} else if (declaredField.getType() == Integer.class || declaredField.getType() == int.class) {
declaredField.set(data, rs.getInt(annotation.name()));
} else if (declaredField.getType() == Double.class || declaredField.getType() == double.class) {
declaredField.set(data, rs.getDouble(annotation.name()));
} else if (declaredField.getType() == Float.class || declaredField.getType() == float.class) {
declaredField.set(data, rs.getFloat(annotation.name()));
} else if (declaredField.getType() == Boolean.class
|| declaredField.getType() == boolean.class) {
declaredField.set(data, rs.getBoolean(annotation.name()));
} else if (declaredField.getType() == Blob.class) {
declaredField.set(data, rs.getBlob(annotation.name()));
} else {
declaredField.set(data, rs.getObject(annotation.name()));
}
}
private <T> Type getType(List<T> res) {
Type clazz = res.getClass().getGenericSuperclass();
ParameterizedType pt = null;
if (clazz instanceof ParameterizedType) {
pt = (ParameterizedType) clazz;
}
if (pt == null) {
return clazz;
}
Type argument = pt.getActualTypeArguments()[0];
return argument;
}
private void release(ResultSet rs, Statement stat, Connection conn) {
try {
if (Objects.nonNull(rs)) {
rs.close();
}
if (Objects.nonNull(stat)) {
stat.close();
}
if (Objects.nonNull(conn)) {
free(conn);
}
} catch (SQLException exception) {
exception.printStackTrace();
}
}
}
| 32.958333 | 104 | 0.564939 |
f5bdb5d371994f114f7f1e90d8b8215a7ee15b52 | 6,216 | package com.distkv.server.service;
import com.distkv.common.utils.FutureUtils;
import com.distkv.rpc.protobuf.generated.CommonProtocol;
import com.distkv.rpc.protobuf.generated.DictProtocol;
import com.distkv.rpc.protobuf.generated.DictProtocol.DictGetItemResponse;
import com.distkv.rpc.protobuf.generated.DictProtocol.DictGetResponse;
import com.distkv.rpc.protobuf.generated.DictProtocol.DictPopItemResponse;
import com.distkv.rpc.protobuf.generated.DistkvProtocol.DistkvRequest;
import com.distkv.rpc.protobuf.generated.DistkvProtocol.DistkvResponse;
import com.distkv.rpc.protobuf.generated.DistkvProtocol.RequestType;
import com.distkv.rpc.service.DistkvService;
import com.distkv.supplier.BaseTestSupplier;
import com.distkv.supplier.ProxyOnClient;
import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
/*
* If you want to put a dict,you need new a map. Like this:
* Map<String,String> localDict = new HashMap<>();
* and the kv to the request Builder
* for (Map.Entry<String,String> entry : localDict.entrySet()) {
* DistKVDictBuilder.addKeys(entry.getKey());
* DistKVDictBuilder.addDict(entry.getValue());
* }
* and build the Builder
*
* if you want to get a dict, you just need dictGetResponse.getDict() method.
*/
public class DictRpcTest extends BaseTestSupplier {
@Test
public void testDictRpcCall() throws InvalidProtocolBufferException {
try (ProxyOnClient<DistkvService> setProxy = new ProxyOnClient<>(
DistkvService.class, KVSTORE_PORT)) {
DistkvService dictService = setProxy.getService();
// Test dict put.
DictProtocol.DictPutRequest.Builder dictPutRequestBuilder =
DictProtocol.DictPutRequest.newBuilder();
final Map<String, String> localDict = new HashMap<>();
localDict.put("k1", "v1");
localDict.put("k2", "v2");
localDict.put("k3", "v3");
DictProtocol.DistKVDict.Builder distKVDictBuilder = DictProtocol.DistKVDict.newBuilder();
for (Map.Entry<String, String> entry : localDict.entrySet()) {
distKVDictBuilder.addKeys(entry.getKey());
distKVDictBuilder.addValues(entry.getValue());
}
dictPutRequestBuilder.setDict(distKVDictBuilder.build());
DistkvRequest putRequest = DistkvRequest.newBuilder()
.setKey("m1")
.setRequestType(RequestType.DICT_PUT)
.setRequest(Any.pack(dictPutRequestBuilder.build()))
.build();
DistkvResponse setPutResponse = FutureUtils.get(
dictService.call(putRequest));
Assert.assertEquals(CommonProtocol.Status.OK, setPutResponse.getStatus());
// Test putItem
DictProtocol.DictPutItemRequest.Builder putBuilder =
DictProtocol.DictPutItemRequest.newBuilder();
putBuilder.setItemKey("k4");
putBuilder.setItemValue("v4");
DistkvRequest putItemRequest = DistkvRequest.newBuilder()
.setKey("m1")
.setRequestType(RequestType.DICT_PUT_ITEM)
.setRequest(Any.pack(putBuilder.build()))
.build();
DistkvResponse putItemResponse = FutureUtils.get(
dictService.call(putItemRequest));
Assert.assertEquals(CommonProtocol.Status.OK, putItemResponse.getStatus());
// Test getItemValue
DictProtocol.DictGetItemRequest.Builder getItemValueBuilder =
DictProtocol.DictGetItemRequest.newBuilder();
getItemValueBuilder.setItemKey("k3");
DistkvRequest getItemRequest = DistkvRequest.newBuilder()
.setKey("m1")
.setRequestType(RequestType.DICT_GET_ITEM)
.setRequest(Any.pack(getItemValueBuilder.build()))
.build();
DistkvResponse getItemValueResponse = FutureUtils.get(
dictService.call(getItemRequest));
Assert.assertEquals(CommonProtocol.Status.OK, getItemValueResponse.getStatus());
Assert.assertEquals(getItemValueResponse.getResponse()
.unpack(DictGetItemResponse.class).getItemValue(), "v3");
// Test popItem
DictProtocol.DictPopItemRequest.Builder popItemBuilder =
DictProtocol.DictPopItemRequest.newBuilder();
popItemBuilder.setItemKey("k3");
DistkvRequest popItemRequest = DistkvRequest.newBuilder()
.setKey("m1")
.setRequestType(RequestType.DICT_POP_ITEM)
.setRequest(Any.pack(popItemBuilder.build()))
.build();
DistkvResponse popItemResponse = FutureUtils.get(
dictService.call(popItemRequest));
Assert.assertEquals(CommonProtocol.Status.OK, popItemResponse.getStatus());
Assert.assertEquals(popItemResponse.getResponse()
.unpack(DictPopItemResponse.class).getItemValue(), "v3");
// Test delItem
DictProtocol.DictRemoveItemRequest.Builder delItemBuilder =
DictProtocol.DictRemoveItemRequest.newBuilder();
delItemBuilder.setItemKey("k2");
DistkvRequest delItemRequest = DistkvRequest.newBuilder()
.setKey("m1")
.setRequestType(RequestType.DICT_REMOVE_ITEM)
.setRequest(Any.pack(delItemBuilder.build()))
.build();
DistkvResponse delItemResponse = FutureUtils.get(
dictService.call(delItemRequest));
Assert.assertEquals(CommonProtocol.Status.OK, delItemResponse.getStatus());
// Test dict get.
DistkvRequest getRequest = DistkvRequest.newBuilder()
.setKey("m1")
.setRequestType(RequestType.DICT_GET)
.build();
DistkvResponse dictGetResponse = FutureUtils.get(
dictService.call(getRequest));
final Map<String, String> judgeDict = new HashMap<>();
judgeDict.put("k1", "v1");
judgeDict.put("k4", "v4");
DictProtocol.DistKVDict values = dictGetResponse.getResponse()
.unpack(DictGetResponse.class).getDict();
Map<String, String> results = new HashMap<>();
for (int i = 0; i < values.getKeysCount(); i++) {
results.put(values.getKeys(i), values.getValues(i));
}
Assert.assertEquals(CommonProtocol.Status.OK, dictGetResponse.getStatus());
Assert.assertEquals(results, judgeDict);
}
}
}
| 44.4 | 95 | 0.710264 |
660312e03587a120b8cc566eec7c02a767d0eb73 | 5,773 | package andres_sjsu.imagesearch.activities;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import andres_sjsu.imagesearch.adapters.EndlessScroll;
import andres_sjsu.imagesearch.adapters.ImageResultsAdapter;
import andres_sjsu.imagesearch.models.ImageResult;
import andres_sjsu.imagesearch.R;
import andres_sjsu.imagesearch.models.Settings;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 1;
private EditText etQuery;
private GridView gridView;
private ArrayList<ImageResult> imageResults;
private ImageResultsAdapter aImagesResults;
private Settings settings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
if (netInfo != null && netInfo.isConnected()) {
setupViews();
//Creates data source
imageResults= new ArrayList<ImageResult>();
//Attaches the data source to an adapter
aImagesResults = new ImageResultsAdapter(this,imageResults);
gridView.setAdapter(aImagesResults);
Toast.makeText(this, "Internet Connected" , Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Internet NOT Connected, please turn on your Internet" , Toast.LENGTH_SHORT).show();
}
}
private void setupViews() {
etQuery = (EditText) findViewById(R.id.etQuery);
gridView = (GridView)findViewById(R.id.gridView);
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(MainActivity.this, ImageDisplayActivity.class);
ImageResult result = imageResults.get(position);
i.putExtra("result", result);
startActivity(i);
}
});
gridView.setOnScrollListener(new EndlessScroll() {
@Override
public void onLoadMore(int page, int totalItemsCount) {
loadMore(totalItemsCount);
}
});
}
private void loadMore(int startOffset) {
String query = etQuery.getText().toString();
AsyncHttpClient client = new AsyncHttpClient();
String searchUrl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + query +
"&rsz=8" ;
client.get(searchUrl, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
Log.d("DEBUG", response.toString());
try {
JSONArray imageResultsJson = response.getJSONObject("responseData").getJSONArray("results");
aImagesResults.addAll(ImageResult.fromJSONArray(imageResultsJson));
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("INFO", "foo");
}
});
}
public void onImageSearch(View v)
{
aImagesResults.clear();
etQuery.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etQuery.getWindowToken(), 0);
loadMore(0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
//showSettingsAction
public void showSettingsAction(MenuItem mi) {
// handle click here
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
i.putExtra("settings", settings);
//i.putExtra("url", result.fullUrl);
startActivityForResult(i, REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
settings = (Settings) data.getSerializableExtra("settings");
}}
}
| 32.432584 | 117 | 0.653906 |
1c30c92916ed88cda46fcc8b4af8fd178193ff4c | 1,424 | package com.rafaelfiume.salume.web.model;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.rafaelfiume.salume.domain.MoneyDealer;
import com.rafaelfiume.salume.domain.Product;
import java.util.ArrayList;
import java.util.List;
@JacksonXmlRootElement(localName = "product-advisor")
public class ProductAdviserMobileResponseModel {
@JacksonXmlElementWrapper(useWrapping = false)
private final List<ProductResponseModel> products = new ArrayList<>();
public static ProductAdviserMobileResponseModel of(List<Product> products, MoneyDealer moneyDealer) {
final ProductAdviserMobileResponseModel advisorView = new ProductAdviserMobileResponseModel();
for (Product p : products) {
advisorView.add(new ProductResponseModel(p, moneyDealer));
}
return advisorView;
}
private ProductAdviserMobileResponseModel() {
// Use the method factory #of instead
}
@JacksonXmlElementWrapper(localName = "products")
@JacksonXmlProperty(localName = "product")
@SuppressWarnings("unused")
public List<ProductResponseModel> getProducts() {
return products;
}
private void add(ProductResponseModel pv) {
products.add(pv);
}
}
| 33.904762 | 105 | 0.755618 |
2ee3b5c5be156fea40e052c129975abcbb5a1ae3 | 3,279 | package com.wya1.iproperty.controller;
import org.springframework.stereotype.Controller;
import com.wya1.iproperty.controller.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.mybatisplus.plugins.Page;
import com.wya1.iproperty.entity.UserInf;
import com.wya1.iproperty.service.IUserInfService;
/**
* 用户控制类
*
* @author wya1
* @since 2018-08-28
*/
@Controller
@RequestMapping("user/userInf")
public class UserInfController extends BaseController {
@Autowired
public IUserInfService userInfService;
@ModelAttribute
public UserInf get(@RequestParam(required = false) String id) {
UserInf entity = null;
if (id != null && !id.equals("")) {
entity = userInfService.selectById(id);
}
if (entity == null) {
entity = new UserInf();
}
return entity;
}
@RequiresPermissions("user:userInf:view")
@RequestMapping(value = { "list", "" })
public String list(Model model,Integer pageNo,UserInf userInf) {
if (pageNo == null || pageNo < 1) {
pageNo=1;
}
Page<UserInf> page = userInfService.selectPage(pageNo,userInf);
model.addAttribute("page", page);
return "modules/user/userInfList";
}
@RequiresPermissions("user:userInf:view")
@RequestMapping(value = { "list2"})
@ResponseBody
public Page<UserInf> list2(Integer page,String q) {
if (page == null || page < 1) {
page=1;
}
UserInf userInf=new UserInf();
// userInf.setIdCard(q);
userInf.setName(q);
// userInf.setRemarks(q);
// userInf.setTel(q);
Page<UserInf> pages = userInfService.selectPage(page,userInf);
// pages.getPages()
// model.addAttribute("page", page);
// return "modules/user/userInfList";
// return "{\"total\":4,\"param\":\"" + q + "\",\"page\":" + page + ",\"items\":" +
// "[{\"id\":\"itag1\",\"text\":\"tag1\"},{\"id\":\"itag2\",\"text\":\"tag2\"}," +
// "{\"id\":\"itag3\",\"text\":\"tag3\"},{\"id\":\"itag4\",\"text\":\"tag4\"}]}";
return pages;
}
@RequiresPermissions("user:userInf:view")
@RequestMapping(value = "form")
public String form(UserInf userInf, Model model) {
model.addAttribute("userInf", userInf);
return "modules/user/userInfForm";
}
@RequiresPermissions("user:userInf:edit")
@RequestMapping(value = "save")
public String save(UserInf userInf, Model model) {
userInfService.save(userInf);
return "redirect:/user/userInf";
}
@ResponseBody
@RequiresPermissions("user:userInf:edit")
@RequestMapping(value = "save2")
public String save2(UserInf userInf) {
userInfService.save(userInf);
return String.valueOf(userInf.getId());
}
@RequiresPermissions("user:userInf:delete")
@RequestMapping(value = "delete")
@ResponseBody
public String delete(UserInf userInf) {
userInfService.deleteById(userInf);
return "";
}
} | 31.228571 | 90 | 0.671241 |
a24bcb0edd454bb76df5eed3416ed2246cdc340a | 3,625 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
@WebServlet("/chart")
public class ChartServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Sets up datastore.
Query query = new Query("Task");
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
PreparedQuery results = datastore.prepare(query);
// Represents strings in datastore as HashMap.
Map<String, Integer> ageData = new HashMap<>();
String ageRange;
int currentVotes;
for (Entity entity : results.asIterable()) {
ageRange = (String) entity.getProperty("range");
currentVotes = ageData.containsKey(ageRange) ? ageData.get(ageRange) : 0;
ageData.put(ageRange, currentVotes + 1);
}
// Writes output as json.
response.setContentType("application/json");
Gson gson = new Gson();
String json = gson.toJson(ageData);
response.getWriter().println(json);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Convert request to a string representing an age range.
int age= -1;
String ageString = request.getParameter("age");
try {
age = Integer.parseInt(ageString);
} catch (NumberFormatException e) {
System.err.println("Could not convert to int: " + ageString);
}
// Convert to ageRange and store if input is proper.
String ageRange = convertToRange(age);
if (ageRange != "Invalid Age") {
storeData(ageRange);
}
else {
System.err.println("Improper value entered: " + ageString);
}
response.sendRedirect("/chart.html");
}
/** Stores age range string in datastore. */
private void storeData(String range) {
Entity taskEntity = new Entity("Task");
taskEntity.setProperty("range", range);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(taskEntity);
}
/** Converts age number to range string.*/
private String convertToRange(int age) {
String range = "Invalid Age";
String[] ageRanges = {"0-9", "10-19", "20-29", "30-39", "40-49", "50+"};
if (age >= 0) {
age = age / 10;
if (age <= 5) {
range = ageRanges[age];
}
else {
range = ageRanges[5];
}
}
return range;
}
}
| 33.564815 | 99 | 0.706207 |
32323f50928efce975aee6316ed370b1e1b28bd7 | 22,850 | package cn.lovepet.shops.view.ui.activity.content;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import cn.lovepet.shops.R;
import cn.lovepet.shops.base.BaseActivity;
import cn.lovepet.shops.base.Constants;
import cn.lovepet.shops.bean.PetDogGoodsListBean;
import cn.lovepet.shops.helper.basequickadapter.BaseQuickAdapter;
import cn.lovepet.shops.helper.basequickadapter.BaseViewHolder;
import cn.lovepet.shops.helper.imageview.RecycleViewDivider;
import cn.lovepet.shops.helper.popupwindow.SlideFirstAllFilterPopupWindow;
import cn.lovepet.shops.helper.popupwindow.SlideFirstFilterListPopupWindow;
import cn.lovepet.shops.helper.popupwindow.SlideSecondFilterPopupWindow;
import cn.lovepet.shops.util.FileUtils;
import cn.lovepet.shops.util.ToastsUtils;
import cn.lovepet.shops.util.ViewUtils;
import cn.lovepet.shops.view.ui.activity.home.tab.SearchQueryActivity;
import razerdp.basepopup.BasePopupWindow;
/**
* @author JSYL-DCL
* @date 2018/11/21 14:33
* @des 宠物消息
*/
public class PetGoodsActivity extends BaseActivity {
private Context mContext;
@BindView(R.id.goodsRecyclerView)
RecyclerView mGoodsRecyclerView;
@BindView(R.id.llGoodsRoot)
LinearLayout mLlGoodsRoot;
@BindView(R.id.brandArrow)
ImageView mBrandArrow;
@BindView(R.id.ivAgeArrow)
ImageView mIvAgeArrow;
@BindView(R.id.ivBodyArrow)
ImageView mIvBodyArrow;
@BindView(R.id.ivKelisizeArrow)
ImageView mIvKelisizeArrow;
@BindView(R.id.llFirstFilter)
LinearLayout mLlFirstFilter;
@BindView(R.id.llSecondFilter)
LinearLayout mLlSecondFilter;
@BindView(R.id.llBrand)
LinearLayout mLlBrand;
@BindView(R.id.llAge)
LinearLayout mLlAge;
@BindView(R.id.llShape)
LinearLayout mLlShape;
@BindView(R.id.llGrainSize)
LinearLayout mLlGrainSize;
//第一层排序
@BindView(R.id.tvDefaultSort)
TextView mTvDefaultSort;
@BindView(R.id.ivDefaultSort)
ImageView mIvDefaultSort;
@BindView(R.id.tvSoldNums)
TextView mTvSoldNums;
@BindView(R.id.ivAllFilterSelect)
ImageView mIvAllFilterSelect;
@BindView(R.id.tvAllFilterSelect)
TextView mTvAllFilterSelect;
@BindView(R.id.tvFSLine)
TextView tvFSLine;
private RotateAnimation showArrowAnima;
private RotateAnimation dismissArrowAnima;
private SlideSecondFilterPopupWindow mSlideFromTopPopup;
// private SlideFirstAllFilterPopupWindow mSlideFirstAllFilterPopupWindow;
private Map<Integer,String> checkedMap;
private BaseQuickAdapter mGoodsAdaper;
private List<PetDogGoodsListBean.Goodslist> goodsModelList;
public static void getInstance(Context context){
context.startActivity(new Intent(context,PetGoodsActivity.class));
}
@Override
protected int getLayoutId() {
return R.layout.activity_pet_goods;
}
@Override
protected void init() {
if (goodsModelList != null)goodsModelList.clear();
else goodsModelList = new ArrayList<>();
}
@Override
protected void initView(Bundle savedInstanceState) {
mContext = PetGoodsActivity.this;
checkedMap = new HashMap<>();
buildShowArrowAnima();
buildDismissArrowAnima();
getFilterGoodsAllData();
setBottomGoodsDetail();
}
/**
* 设置底部列表默认数据
*/
private void setBottomGoodsDetail() {
LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
int color = getResources().getColor(R.color.common_divider_narrow);
RecycleViewDivider divider = new RecycleViewDivider(mContext,LinearLayoutManager.VERTICAL,1,color);
mGoodsRecyclerView.removeItemDecoration(divider);
mGoodsRecyclerView.addItemDecoration(divider);
mGoodsRecyclerView.setLayoutManager(layoutManager);
mGoodsRecyclerView.setHasFixedSize(true);
mGoodsRecyclerView.setItemViewCacheSize(5);
mGoodsAdaper = new GoodsAdaper(R.layout.item_goods_t1, goodsModelList);
mGoodsRecyclerView.setAdapter(mGoodsAdaper);
getGoods();
}
private void getGoods() {
if (goodsModelList != null)goodsModelList.clear();
else goodsModelList = new ArrayList<>();
goodsModelList.addAll(goodslist);
mGoodsAdaper.notifyDataSetChanged();
}
private class GoodsAdaper extends BaseQuickAdapter<PetDogGoodsListBean.Goodslist, BaseViewHolder> {
public GoodsAdaper(int layoutResId, List<PetDogGoodsListBean.Goodslist> data) {
super(layoutResId, data);
}
public GoodsAdaper(List<PetDogGoodsListBean.Goodslist> data) {
super(data);
}
@Override
protected void convert(BaseViewHolder helper, PetDogGoodsListBean.Goodslist item, int position) {
ImageView jxImageIcon = (ImageView) helper.getView(R.id.jxImageIcon);
// TextView tvJxTitle = (TextView) holder.getView(R.id.tvJxTitle);
ImageView ivJxIconSold = (ImageView) helper.getView(R.id.ivJxIconSold);
TextView tvJxCurerntPrice = (TextView) helper.getView(R.id.tvJxCurerntPrice);
TextView tvJxOldPrice = (TextView) helper.getView(R.id.tvJxOldPrice);
TextView tvHuDong = (TextView) helper.getView(R.id.tvHuDong);
TextView tvSoldNum = (TextView) helper.getView(R.id.tvSoldNum);
ImageView ivShopcart = (ImageView) helper.getView(R.id.ivShopcart);
helper.setText(R.id.tvJxTitle,item.getSubject() == null ? "" : item.getSubject());
helper.setText(R.id.tvJxCurerntPrice,item.getSale_price() == null ? "" : "¥"+item.getSale_price());
helper.setText(R.id.tvJxOldPrice,item.getMarket_price() == null ? "" : item.getMarket_price());
helper.setText(R.id.tvHuDong,item.getComments() == null ? "" : item.getComments());
helper.setText(R.id.tvSoldNum,item.getSold() == null ? "" : item.getSold());
ViewUtils.setPriceLine(tvJxOldPrice,0);
Glide.with(mContext)
.load(item.getPhoto())
.asBitmap()
.skipMemoryCache(false)
.priority(Priority.HIGH)
.dontTransform()
.placeholder(R.mipmap.pet_image_loadding)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(jxImageIcon);
List<PetDogGoodsListBean.Goodslist.ActivityLabels> activityLabels = item.getActivityLabels();
if (activityLabels != null && activityLabels.size() > 0){
ivJxIconSold.setVisibility(View.VISIBLE);
Glide.with(mContext)
.load(activityLabels.get(0).getImage())
.asBitmap()
.skipMemoryCache(false)
.priority(Priority.HIGH)
.dontTransform()
.placeholder(R.mipmap.pet_image_loadding)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(ivJxIconSold);
}else {
ivJxIconSold.setVisibility(View.GONE);
}
ivShopcart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ToastsUtils.showShort("加入购物车");
}
});
}
};
@Override
protected void initData() {
}
@Override
protected void initListener() {
}
@OnClick({
R.id.ivBack
,R.id.goodsSearch
,R.id.llDefaultSort
,R.id.tvSoldNums
,R.id.llPrice
,R.id.llFilterSelect
,R.id.llBrand
,R.id.llAge
,R.id.llShape
,R.id.llGrainSize
})
public void bindViewClick(View view){
switch (view.getId()){
case R.id.ivBack:
finish();
break;
case R.id.goodsSearch:
SearchQueryActivity.getInstance(mContext);
break;
case R.id.llDefaultSort://默认排序
if (sortRankModelList != null && sortRankModelList.size() > 0) {
SlideFirstFilterListPopupWindow.Builder builder = new SlideFirstFilterListPopupWindow.Builder(this,sortRankModelList);
SlideFirstFilterListPopupWindow build = builder.build();
build.setOnSimpleListPopupItemClickListener(new SlideFirstFilterListPopupWindow.OnSimpleListPopupItemClickListener() {
@Override
public void onItemClick(int what, String text) {
Constants.POPUP_DEFAULT_SORT = text;
if (text.contains("默认")) {
mTvDefaultSort.setText("默认");
}else {
mTvDefaultSort.setText(text);
}
mTvSoldNums.setTextColor(getResources().getColor(R.color.material_grey_500));
mTvDefaultSort.setTextColor(getResources().getColor(R.color.red));
mIvDefaultSort.setImageResource(R.drawable.ico_arrow_down_select);
}
});
build.setOnDismissListener(onDismissListener);
build.showPopupWindow(tvFSLine);
}else {
ToastsUtils.showShort("暂无筛选项");
}
break;
case R.id.tvSoldNums://销量
mTvSoldNums.setTextColor(getResources().getColor(R.color.red));
accordingFilterInit();
// mTvSoldNums.setText(text);
break;
case R.id.llPrice://价格
ToastsUtils.showShort("价格");
break;
case R.id.llFilterSelect://筛选
initAllFilterPopUp(filterItemList,tvFSLine,mIvAllFilterSelect,mTvAllFilterSelect);
break;
case R.id.llBrand://品牌
initPopUp(brandModel,0,mBrandArrow,mLlSecondFilter,mLlBrand);
Constants.POPUP_CURRENT_CLICK = 10;
break;
case R.id.llAge://年龄
initPopUp(ageModel,1,mIvAgeArrow,mLlSecondFilter,mLlAge);
Constants.POPUP_CURRENT_CLICK = 11;
break;
case R.id.llShape://体型
initPopUp(bodyModel,2,mIvBodyArrow,mLlSecondFilter,mLlShape);
Constants.POPUP_CURRENT_CLICK = 12;
break;
case R.id.llGrainSize://颗粒大小
initPopUp(keliSizeModel,3,mIvKelisizeArrow,mLlSecondFilter,mLlGrainSize);
Constants.POPUP_CURRENT_CLICK = 13;
break;
}
}
/**
* 一级筛选按钮展开弹窗
* @param modelList
* @param anchorView 相对view
* @param tvBtn 按钮view
*/
private void initAllFilterPopUp(List<PetDogGoodsListBean.FilterBoxData> modelList, View anchorView, View ico, View tvBtn) {
if (modelList != null) {
SlideFirstAllFilterPopupWindow.Builder builder = new SlideFirstAllFilterPopupWindow.Builder(this,modelList);
SlideFirstAllFilterPopupWindow build = builder.build();
build.setOnAllFilterPopupItemClickListener(new SlideFirstAllFilterPopupWindow.OnAllFilterPopupItemClickListener() {
@Override
public void onItemClick(int what, String text) {
ToastsUtils.showShort(text);
// mTvSoldNums.setTextColor(getResources().getColor(R.color.material_grey_500));
// mTvDefaultSort.setTextColor(getResources().getColor(R.color.red));
// mIvDefaultSort.setImageResource(R.drawable.ico_arrow_down_select);
}
});
build.setOnDismissListener(onAllFilterDismissListener);
// build.setOffsetX(0);
// build.setOffsetY(-150);
build.showPopupWindow(anchorView);
// PopupWindow popupWindow = build.getPopupWindow();
// popupWindow.showAtLocation(anchorView, Gravity.BOTTOM,0,150);
if (build.isShowing() && ico instanceof ImageView) {
ico.setBackground(getResources().getDrawable(R.drawable.ico_select_filter_checked));
((TextView)tvBtn).setTextColor(getResources().getColor(R.color.red));
mTvSoldNums.setTextColor(getResources().getColor(R.color.material_grey_500));
mTvDefaultSort.setTextColor(getResources().getColor(R.color.material_grey_500));
mIvDefaultSort.setImageResource(R.drawable.ico_arrow_down_unselect);
}
}else {
ToastsUtils.showShort("暂无筛选项");
}
}
/**
* 一级筛选初始化未操作项
*/
private void accordingFilterInit() {
mTvDefaultSort.setTextColor(getResources().getColor(R.color.material_grey_500));
if (sortRankModelList != null && sortRankModelList.size() > 0) {
String item = sortRankModelList.get(0).getItem();
if (item.contains("默认")) {
mTvDefaultSort.setText("默认");
}else {
mTvDefaultSort.setText(item);
}
}else {
mTvDefaultSort.setText("");
}
mIvDefaultSort.setImageResource(R.drawable.ico_arrow_down_unselect);
}
/**
* 二级筛选初始化弹窗
* @param model
* @param i
* @param ivarrow
* @param mLlSecondFilter achorView 基于此view展开
* @param mButton 展开按钮
*/
private void initPopUp(PetDogGoodsListBean.FilterBoxData model, int i, ImageView ivarrow, LinearLayout mLlSecondFilter, LinearLayout mButton) {
if (mSlideFromTopPopup != null && mSlideFromTopPopup.isShowing()){
}else {
mSlideFromTopPopup = new SlideSecondFilterPopupWindow(mContext,model,i);
mSlideFromTopPopup.setOnDismissListener(onDismissListener);
mSlideFromTopPopup.setOnListPopupItemClickListener(onPopupSelectListener);
if (!mSlideFromTopPopup.isShowing()) startShowArrowAnima(ivarrow);
mSlideFromTopPopup.showPopupWindow(mLlSecondFilter);
mButton.setBackground(getResources().getDrawable(R.drawable.shape_goods_button_bg_clicked));
}
}
@Override
protected void getBundleExtras(Bundle extras) {
}
@Override
protected void getBundleExtras(Intent intent) {
}
@Override
protected int setImmersiveStatusBarColor() {
return 0;
}
/**
* 创建箭头开始动画
*/
private void buildShowArrowAnima() {
if (showArrowAnima != null) return;
showArrowAnima = new RotateAnimation(0, 180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
showArrowAnima.setDuration(200);
showArrowAnima.setInterpolator(new AccelerateDecelerateInterpolator());
showArrowAnima.setFillAfter(true);
}
/**
* 创建箭头在弹窗消失时动画
*/
private void buildDismissArrowAnima() {
if (dismissArrowAnima != null) return;
dismissArrowAnima = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
dismissArrowAnima.setDuration(200);
dismissArrowAnima.setInterpolator(new AccelerateDecelerateInterpolator());
dismissArrowAnima.setFillAfter(true);
}
/**
* 开始箭头动画
* @param mArraw
*/
private void startShowArrowAnima(View mArraw) {
if (mArraw == null) return;
if (mArraw instanceof ImageView) {
mArraw.clearAnimation();
mArraw.startAnimation(showArrowAnima);
}
}
/**
* 结束箭头动画
* @param mArraw
*/
private void startDismissArrowAnima(View mArraw) {
if (mArraw == null) return;
if (mArraw instanceof ImageView) {
mArraw.clearAnimation();
mArraw.startAnimation(dismissArrowAnima);
}
}
/**
* 获取物品列表数据
*/
PetDogGoodsListBean.FilterBoxData brandModel;
PetDogGoodsListBean.FilterBoxData ageModel;
PetDogGoodsListBean.FilterBoxData bodyModel;
PetDogGoodsListBean.FilterBoxData keliSizeModel;
List<PetDogGoodsListBean.Goodslist> goodslist;
List<String> normalSortList;
List<PetDogGoodsListBean.Sort_rank.Sort_rank_list> sortRankModelList;
List<PetDogGoodsListBean.FilterBoxData> filterItemList;
private void getFilterGoodsAllData() {
if (normalSortList != null)normalSortList.clear();
else normalSortList = new ArrayList<>();
if (sortRankModelList != null)sortRankModelList.clear();
else sortRankModelList = new ArrayList<>();
String json = FileUtils.getJson(mContext, "pet_goods_filter.json");
Gson gson = new Gson();
Type type = new TypeToken<PetDogGoodsListBean>() {}.getType();
PetDogGoodsListBean petDogGoodsListBean = gson.fromJson(json, type);
filterItemList = petDogGoodsListBean.getFilterBoxData();
List<PetDogGoodsListBean.Sort_rank> sort_rank = petDogGoodsListBean.getSort_rank();
//底部列表商品
goodslist = petDogGoodsListBean.getGoodslist();
List<PetDogGoodsListBean.Sort_rank.Sort_rank_list> sort_rank_list = sort_rank.get(0).getSort_rank_list();
//品牌
brandModel = filterItemList.get(0);
//年龄
ageModel = filterItemList.get(1);
//体型
bodyModel = filterItemList.get(2);
//颗粒大小
keliSizeModel = filterItemList.get(3);
//默认排序
if (sort_rank_list != null && sort_rank_list.size() > 0){
for (PetDogGoodsListBean.Sort_rank.Sort_rank_list a : sort_rank_list) {
normalSortList.add(a.getItem());
}
String item = sort_rank_list.get(0).getItem();
sortRankModelList.addAll(sort_rank_list);
mTvDefaultSort.setTextColor(getResources().getColor(R.color.red));
mIvDefaultSort.setImageResource(R.drawable.ico_arrow_down_select);
if (TextUtils.isEmpty(Constants.POPUP_DEFAULT_SORT)){
if (item.contains("默认")){
mTvDefaultSort.setText("默认");
}else {
mTvDefaultSort.setText(item);
}
Constants.POPUP_DEFAULT_SORT = item;
}else {
if (Constants.POPUP_DEFAULT_SORT.contains("默认")){
mTvDefaultSort.setText("默认");
}else {
mTvDefaultSort.setText(Constants.POPUP_DEFAULT_SORT);
}
}
}else {
if (normalSortList != null) normalSortList.clear();
if (sortRankModelList != null) sortRankModelList.clear();
}
}
/**
* 二级筛选的弹窗消失动画
*/
private BasePopupWindow.OnDismissListener onDismissListener = new BasePopupWindow.OnDismissListener() {
@Override
public boolean onBeforeDismiss() {
if (Constants.POPUP_CURRENT_CLICK == 10){//品牌
startDismissArrowAnima(mBrandArrow);
}else if (Constants.POPUP_CURRENT_CLICK == 11){//年龄
startDismissArrowAnima(mIvAgeArrow);
}else if (Constants.POPUP_CURRENT_CLICK == 12){//体型
startDismissArrowAnima(mIvBodyArrow);
}else if (Constants.POPUP_CURRENT_CLICK == 13){//颗粒大小
startDismissArrowAnima(mIvKelisizeArrow);
}
return super.onBeforeDismiss();
}
@Override
public void onDismiss() {
if (Constants.POPUP_CURRENT_CLICK == 10){//品牌
mLlBrand.setBackground(getResources().getDrawable(R.drawable.shape_goods_button_bg));
}else if (Constants.POPUP_CURRENT_CLICK == 11){//年龄
mLlAge.setBackground(getResources().getDrawable(R.drawable.shape_goods_button_bg));
}else if (Constants.POPUP_CURRENT_CLICK == 12){//体型
mLlShape.setBackground(getResources().getDrawable(R.drawable.shape_goods_button_bg));
}else if (Constants.POPUP_CURRENT_CLICK == 13){//颗粒大小
mLlGrainSize.setBackground(getResources().getDrawable(R.drawable.shape_goods_button_bg));
}
}
};
/**
* 二级筛选选中条目监听
*/
private SlideSecondFilterPopupWindow.OnListPopupItemClickListener onPopupSelectListener = new SlideSecondFilterPopupWindow.OnListPopupItemClickListener() {
@Override
public void onItemClick(int what, String text, int filterType) {
ToastsUtils.showShort("选择:"+text+":"+what);
if (filterType == 0){//品牌
Constants.POPUP_BRAND_SELECTED = text;
}else if (filterType == 1){//年龄
Constants.POPUP_AGE_SELECTED = text;
}else if (filterType == 2){//体型
Constants.POPUP_BODY_SELECTED = text;
}else if (filterType == 3){//颗粒大小
Constants.POPUP_KELISIZE_SELECTED = text;
}
}
};
/**
* 筛选的弹窗消失监听
*/
private BasePopupWindow.OnDismissListener onAllFilterDismissListener = new BasePopupWindow.OnDismissListener() {
@Override
public boolean onBeforeDismiss() {
return super.onBeforeDismiss();
}
@Override
public void onDismiss() {
mIvAllFilterSelect.setBackground(getResources().getDrawable(R.drawable.ico_select_filter_none));
mTvAllFilterSelect.setTextColor(getResources().getColor(R.color.material_grey_500));
mTvDefaultSort.setTextColor(getResources().getColor(R.color.red));
mIvDefaultSort.setImageResource(R.drawable.ico_arrow_down_select);
}
};
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
} | 39.328744 | 159 | 0.635624 |
d1826bc6ba178cde7be195bd81b4384ef6dcf0c5 | 2,415 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.java.sip.communicator.impl.protocol.jabber.extensions.caps;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.provider.*;
import org.xmlpull.v1.*;
/**
* The provider that parses <tt>c</tt> packet extensions into {@link
* CapsPacketExtension} instances.
*
* This work is based on Jonas Adahl's smack fork.
*
* @author Emil Ivov
*/
public class CapsProvider implements PacketExtensionProvider
{
/**
* Parses and returns an Entity Capabilities.
*
* @param parser the pull parser positioned at the caps element.
*
* @return the newly created {@link CapsPacketExtension}.
*
* @throws Exception in case there's anything wrong with the xml.
*/
public PacketExtension parseExtension(XmlPullParser parser)
throws Exception
{
boolean done = false;
String ext = null;
String hash = null;
String version = null;
String node = null;
while(!done)
{
if(parser.getEventType() == XmlPullParser.START_TAG
&& parser.getName().equalsIgnoreCase("c"))
{
ext = parser.getAttributeValue(null, "ext");
hash = parser.getAttributeValue(null, "hash");
version = parser.getAttributeValue(null, "ver");
node = parser.getAttributeValue(null, "node");
}
if( parser.getEventType()==XmlPullParser.END_TAG
&& parser.getName().equalsIgnoreCase("c"))
{
done=true;
}
else
{
parser.next();
}
}
return new CapsPacketExtension(ext, node, hash, version);
}
}
| 31.363636 | 75 | 0.624017 |
8aef410d1e93ce9b817bdba1398ce07a6510e421 | 693 | package com.chaoxing.gsd.modules.entity;
/**
* 对应表user_file_main
* @author winsl
*
*/
public class UserFileMain {
private String userid;
private Integer fileid;
private String extend;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid == null ? null : userid.trim();
}
public Integer getFileid() {
return fileid;
}
public void setFileid(Integer fileid) {
this.fileid = fileid;
}
public String getExtend() {
return extend;
}
public void setExtend(String extend) {
this.extend = extend == null ? null : extend.trim();
}
} | 18.72973 | 60 | 0.607504 |
76a7878cabb3a4a6c718391a6f28a576bc07fd1a | 3,816 | /*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.gwtproject.i18n.shared.cldr;
/**
* A tag interface that serves as the root of a family of types used in static
* internationalization. Using <code>GWT.create(<i>class</i>)</code> to
* instantiate a type that directly extends or implements
* <code>Localizable</code> invites locale-sensitive type substitution.
*
* <h3>Locale-sensitive Type Substitution</h3>
* If a type <code>Type</code> directly extends or implements
* <code>Localizable</code> (as opposed to
* {@link org.gwtproject.i18n.client.Constants} or
* {@link org.gwtproject.i18n.client.Messages}) and the following code is used
* to create an object from <code>Type</code> as follows:
*
* <pre class="code">Type localized = (Type)GWT.create(Type.class);</pre>
*
* then <code>localized</code> will be assigned an instance of a localized
* subclass, selected based on the value of the <code>locale</code> client
* property. The choice of subclass is determined by the following naming
* pattern:
*
* <table>
*
* <tr>
* <th align='left'>If <code>locale</code> is...    </th>
* <th align='left'>The substitute class for <code>Type</code> is...</th>
* </tr>
*
* <tr>
* <td><i>unspecified</i></td>
* <td><code>Type</code> itself, or <code>Type_</code> if <code>Type</code>
* is an interface</td>
* </tr>
*
* <tr>
* <td><code>x</code></td>
* <td>Class <code>Type_x</code> if it exists, otherwise treated as if
* <code>locale</code> were <i>unspecified</i></td>
* </tr>
*
* <tr>
* <td><code>x_Y</code></td>
* <td>Class <code>Type_x_Y</code> if it exists, otherwise treated as if
* <code>locale</code> were <code>x</code></td>
* </tr>
*
* </table>
*
* where in the table above <code>x</code> is a <a
* href="http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt">ISO language
* code</a> and <code>Y</code> is a two-letter <a
* href="http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html">ISO
* country code</a>.
*
* <h3>Specifying Locale</h3>
* The locale of a module is specified using the <code>locale</code> client
* property, which can be specified using either a meta tag or as part of the
* query string in the host page's URL. If both are specified, the query string
* takes precedence.
*
* <p>
* To specify the <code>locale</code> client property using a meta tag in the
* host HTML, use <code>gwt:property</code> as follows:
*
* <pre><meta name="gwt:property" content="locale.new=x_Y"></pre>
*
* For example, the following host HTML page sets the locale to "ja_JP":
*
* {@gwt.include com/google/gwt/examples/i18n/ColorNameLookupExample_ja_JP.html}
* </p>
*
* <p>
* To specify the <code>locale</code> client property using a query string,
* specify a value for the name <code>locale</code>. For example,
*
* <pre>http://www.example.org/myapp.html?locale=fr_CA</pre>
*
* </p>
*
* <h3>For More Information</h3>
* See the GWT Developer Guide for an introduction to internationalization.
*
* @see org.gwtproject.i18n.client.Constants
* @see org.gwtproject.i18n.client.ConstantsWithLookup
* @see org.gwtproject.i18n.client.Messages
* @see org.gwtproject.i18n.client.Dictionary
*/
public interface Localizable {
}
| 36 | 80 | 0.690514 |
60d7277985f96de1591eda1a0a14739cb673950b | 5,683 | /*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
* </p>
*/
package com.dangdang.ddframe.job.internal.server;
import com.dangdang.ddframe.job.api.config.JobConfiguration;
import com.dangdang.ddframe.job.internal.env.LocalHostService;
import com.dangdang.ddframe.job.internal.storage.JobNodeStorage;
import com.dangdang.ddframe.reg.base.CoordinatorRegistryCenter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 作业服务器节点服务.
*
* @author zhangliang
* @author caohao
*/
public class ServerService {
private final JobNodeStorage jobNodeStorage;
private final LocalHostService localHostService = new LocalHostService();
public ServerService(final CoordinatorRegistryCenter coordinatorRegistryCenter, final JobConfiguration jobConfiguration) {
jobNodeStorage = new JobNodeStorage(coordinatorRegistryCenter, jobConfiguration);
}
/**
* 每次作业启动前清理上次运行状态.
*/
public void clearPreviousServerStatus() {
jobNodeStorage.removeJobNodeIfExisted(ServerNode.getStatusNode(localHostService.getIp()));
jobNodeStorage.removeJobNodeIfExisted(ServerNode.getShutdownNode(localHostService.getIp()));
}
/**
* 持久化作业服务器上线相关信息.
*/
public void persistServerOnline() {
jobNodeStorage.fillJobNodeIfNullOrOverwrite(ServerNode.getHostNameNode(localHostService.getIp()), localHostService.getHostName());
persistDisabled();
jobNodeStorage.fillEphemeralJobNode(ServerNode.getStatusNode(localHostService.getIp()), ServerStatus.READY);
jobNodeStorage.removeJobNodeIfExisted(ServerNode.getShutdownNode(localHostService.getIp()));
}
private void persistDisabled() {
if (!jobNodeStorage.getJobConfiguration().isOverwrite()) {
return;
}
if (jobNodeStorage.getJobConfiguration().isDisabled()) {
jobNodeStorage.fillJobNodeIfNullOrOverwrite(ServerNode.getDisabledNode(localHostService.getIp()), "");
} else {
jobNodeStorage.removeJobNodeIfExisted(ServerNode.getDisabledNode(localHostService.getIp()));
}
}
/**
* 清除暂停作业的标记.
*/
public void clearJobPausedStatus() {
jobNodeStorage.removeJobNodeIfExisted(ServerNode.getPausedNode(localHostService.getIp()));
}
/**
* 判断是否是手工暂停的作业.
*
* @return 是否是手工暂停的作业
*/
public boolean isJobPausedManually() {
return jobNodeStorage.isJobNodeExisted(ServerNode.getPausedNode(localHostService.getIp()));
}
/**
* 处理服务器关机的相关信息.
*/
public void processServerShutdown() {
jobNodeStorage.removeJobNodeIfExisted(ServerNode.getStatusNode(localHostService.getIp()));
}
/**
* 在开始或结束执行作业时更新服务器状态.
*
* @param status 服务器状态
*/
public void updateServerStatus(final ServerStatus status) {
jobNodeStorage.updateJobNode(ServerNode.getStatusNode(localHostService.getIp()), status);
}
/**
* 删除服务器状态.
*/
public void removeServerStatus() {
jobNodeStorage.removeJobNodeIfExisted(ServerNode.getStatusNode(localHostService.getIp()));
}
/**
* 获取所有的作业服务器列表.
*
* @return 所有的作业服务器列表
*/
public List<String> getAllServers() {
List<String> result = jobNodeStorage.getJobNodeChildrenKeys(ServerNode.ROOT);
Collections.sort(result);
return result;
}
/**
* 获取可用的作业服务器列表.
*
* @return 可用的作业服务器列表
*/
public List<String> getAvailableServers() {
List<String> servers = getAllServers();
List<String> result = new ArrayList<>(servers.size());
for (String each : servers) {
if (isAvailableServer(each)) {
result.add(each);
}
}
return result;
}
/**
* 判断作业服务器是否可用.
*
* @param ip 作业服务器IP地址.
* @return 作业服务器是否可用
*/
public boolean isAvailableServer(final String ip) {
return jobNodeStorage.isJobNodeExisted(ServerNode.getStatusNode(ip)) && !jobNodeStorage.isJobNodeExisted(ServerNode.getPausedNode(ip))
&& !jobNodeStorage.isJobNodeExisted(ServerNode.getDisabledNode(ip)) && !jobNodeStorage.isJobNodeExisted(ServerNode.getShutdownNode(ip));
}
/**
* 判断当前服务器是否是等待执行的状态.
*
* @return 当前服务器是否是等待执行的状态
*/
public boolean isLocalhostServerReady() {
String ip = localHostService.getIp();
return isAvailableServer(ip) && ServerStatus.READY.name().equals(jobNodeStorage.getJobNodeData(ServerNode.getStatusNode(ip)));
}
/**
* 持久化统计处理数据成功的数量的数据.
*/
public void persistProcessSuccessCount(final int processSuccessCount) {
jobNodeStorage.replaceJobNode(ServerNode.getProcessSuccessCountNode(localHostService.getIp()), processSuccessCount);
}
/**
* 持久化统计处理数据失败的数量的数据.
*/
public void persistProcessFailureCount(final int processFailureCount) {
jobNodeStorage.replaceJobNode(ServerNode.getProcessFailureCountNode(localHostService.getIp()), processFailureCount);
}
}
| 32.474286 | 152 | 0.683266 |
c22170e30da4619a6677317026ece48278060f29 | 1,687 | package org.wjw.java8;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
/**
* Created by SWGawain on 2017/5/12.
*/
public class LambdaTest {
@Test
public void BasicTest(){
Arrays.asList(1,2,3).forEach( e -> System.out.println(e));
}
@Test
public void LamTest2(){
Arrays.asList(1,2,3).forEach( e -> {
System.out.print(e+" ");
System.out.println(e+1+" ");
//1 2
//2 3
//3 4
});
}
@Test
public void LamTest3(){
int sault = 2 ;
Arrays.asList(1,2,3).forEach( e -> {
System.out.print(e+" ");
System.out.println(e+sault+" ");
//1 3
//2 4
//3 5
});
}
@Test
public void LamTest4(){
List<Integer> integers = Arrays.asList(1, 3, 2);
integers.sort( (e1,e2) -> e1.compareTo(e2));
integers.forEach( E -> System.out.print(E)); //123
for (Integer integer : integers) {
System.out.println(integer);
}
}
@Test
public void LamTest5(){
//匿名内部类
// ()表示无参数
new Thread(()->System.out.println("Hello")).start();
Runnable runnable = () ->{
//这其实是在编写run方法
System.out.println("简单了太多");
};
FuncInterface funcInterface = (bigDecimal)-> {
//这里在编写add方法
FuncInterface.bal.add(bigDecimal);
};
System.out.println(FuncInterface.sum(BigDecimal.ONE));
funcInterface.add(BigDecimal.ONE);
System.out.println(funcInterface.getBalance());
}
}
| 20.325301 | 66 | 0.509781 |
5085c14961608542e66df3e9beee27ab94306fa5 | 2,197 | /*
* Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved.
*
* This file is part of Aspose.Pdf. The source code in this file
* is only intended as a supplement to the documentation, and is provided
* "as is", without warranty of any kind, either expressed or implied.
*/
package programmersguide.workingwithasposepdffacades.workingwithimages.convertparticularpageregion.java;
import com.aspose.pdf.*;
public class ConvertParticularPageRegion
{
public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = "src/programmersguide/workingwithasposepdffacades/workingwithimages/convertparticularpageregion/data/";
// instantiate PdfPageEditor class to get particular page region
com.aspose.pdf.facades.PdfPageEditor editor = new com.aspose.pdf.facades.PdfPageEditor();
// bind the source PDF file
editor.bindPdf(dataDir+ "SampleInput.pdf");
// move the origin of PDF file to particular point
editor.movePosition(100, 200);
// create a memory stream object
java.io.FileOutputStream fout = new java.io.FileOutputStream(dataDir+ "input1.pdf");
// save the updated document to stream object
editor.save(fout);
//create PdfConverter object
com.aspose.pdf.facades.PdfConverter objConverter = new com.aspose.pdf.facades.PdfConverter();
//bind input pdf file
objConverter.bindPdf(new java.io.FileInputStream(dataDir+"input1.pdf"));
//set StartPage and EndPage properties to the page number to
//you want to convert images from
objConverter.setStartPage(1);
objConverter.setEndPage(1);
//Counter
int page = 1;
//initialize the converting process
objConverter.doConvert();
//check if pages exist and then convert to image one by one
while (objConverter.hasNextImage())
objConverter.getNextImage(dataDir+ "Specific_Region-Image"+ page++ +".jpeg");
//close the PdfConverter object
objConverter.close();
// close MemoryStream object holding the updated document
fout.close();
}
}
| 39.945455 | 128 | 0.694128 |
78b8f04dbfbb14bf1b3e6aecc5ba6c5fdc9208e6 | 1,193 | package com.twosheds.pi;
public class ChudnovskyActivity extends PiSeriesActivity {
private double multiplier;
private double factorial;
private double factorial3;
private double factorial6;
private double piInverse;
@Override
protected void init() {
multiplier = 12.0 / Math.pow(640320, 1.5);
factorial = 1.0;
factorial3 = 1.0;
factorial6 = 1.0;
piInit = 0;
piInverse = 0.0;
formulaView.setImageResource(R.drawable.chudnovsky);
}
@Override
protected double calculatePi(double oldPi) {
if (numSteps > 0) {
factorial *= numSteps;
for (int factor = (numSteps - 1) * 3 + 1; factor <= numSteps * 3; factor++) {
factorial3 *= factor;
}
for (int factor = (numSteps - 1) * 6 + 1; factor <= numSteps * 6; factor++) {
factorial6 *= factor;
}
}
double term = multiplier * factorial6 * (13591409 + 545140134 * numSteps) / (factorial3 * Math.pow(factorial, 3) * Math.pow(-640320, 3 * numSteps));
piInverse += term;
double pi = 1.0 / piInverse;
return pi;
}
}
| 29.097561 | 156 | 0.564962 |
7603aed9d17ce886a1a192c78323302193d5a94e | 665 | package io.github.vm.patlego.enc;
import javax.annotation.Nonnull;
public interface Security {
/**
* Decrypts a token using the requested encryption service within the system
* @param token Encrypted token, the token entered within the system must be encrypted using this or else decryption risks failing
* @return Plain text token
*/
public @Nonnull String decrypt(@Nonnull String token);
/**
* Encrypts a token using paramters placed within the implementation
* @param token - Plain text token to be encrypted
* @return Encrpyted token
*/
public @Nonnull String encrypt(@Nonnull String token);
}
| 30.227273 | 134 | 0.705263 |
4122587e8c3b76b187923384002b37bd36fb6e14 | 4,048 | /*
* Copyright 2021 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.streams.operator.internal.metrics;
import com.ibm.streams.operator.metrics.Metric;
import com.ibm.streams.operator.metrics.Metric.Kind;
import com.ibm.streams.operator.metrics.OperatorMetrics.InputPortMetric;
import com.ibm.streams.operator.metrics.OperatorMetrics.OutputPortMetric;
import com.ibm.streams.operator.metrics.OperatorMetrics.SystemMetric;
import com.ibm.streams.spl.messages.Message;
import com.ibm.streams.spl.messages.general.StreamsSPLJavaMessagesKey.Key;
public abstract class RuntimeMetricsFactory
implements OperatorMetricsFactory<CustomMetric, RuntimeMetric> {
@Override
public final CustomMetric newCustomMetric(String name, String description, Kind kind) {
return new CustomMetric(name, kind, description);
}
/**
* No predefined metrics so justr return null. Each operator maintains a cache of its own metrics.
*/
@Override
public final CustomMetric getCustomMetric(String name) {
return null;
}
/**
* Java runtime knows about all the custom metrics so return null to indicate no more are known
* about.
*/
@Override
public final String[] getCustomMetricNames(int currentCount) {
return null;
}
@Override
public RuntimeMetric getInputMetric(int port, InputPortMetric name) {
return newInputPortMetric(port, name, getMetricValue(port, name));
}
@Override
public RuntimeMetric getOutputMetric(int port, OutputPortMetric name) {
return newOutputPortMetric(port, name, getMetricValue(port, name));
}
public RuntimeMetric getOperatorMetric(SystemMetric name) {
return null;
}
protected abstract RuntimeMetric.MetricValue getMetricValue(int port, InputPortMetric name);
protected abstract RuntimeMetric.MetricValue getMetricValue(int port, OutputPortMetric name);
public static RuntimeMetric newInputPortMetric(
int port, InputPortMetric ipm, RuntimeMetric.MetricValue mv) {
final String name = ipm.name() + port;
final String description =
new Message(Key.SPL_RUNTIME_INPUT_PORT_METRIC_NAME, ipm.name(), port).getLocalizedMessage();
final Metric.Kind kind;
switch (ipm) {
case nFinalPunctsProcessed:
case nTuplesDropped:
case nTuplesProcessed:
case nWindowPunctsProcessed:
case nEnqueueWaits:
kind = Metric.Kind.COUNTER;
break;
case nFinalPunctsQueued:
case nTuplesQueued:
case nWindowPunctsQueued:
case queueSize:
case maxItemsQueued:
case recentMaxItemsQueued:
kind = Metric.Kind.GAUGE;
break;
case recentMaxItemsQueuedInterval:
kind = Metric.Kind.TIME;
break;
default:
throw new UnsupportedOperationException(ipm.name());
}
return new RuntimeMetric(mv, name, kind, description);
}
public static RuntimeMetric newOutputPortMetric(
int port, OutputPortMetric opm, RuntimeMetric.MetricValue mv) {
final String name = opm.name() + port;
final String description =
new Message(Key.SPL_RUNTIME_OUTPUT_PORT_METRIC_NAME, opm.name(), port)
.getLocalizedMessage();
final Metric.Kind kind;
switch (opm) {
case nFinalPunctsSubmitted:
case nTuplesSubmitted:
case nWindowPunctsSubmitted:
kind = Metric.Kind.COUNTER;
break;
default:
throw new UnsupportedOperationException(opm.name());
}
return new RuntimeMetric(mv, name, kind, description);
}
}
| 32.645161 | 100 | 0.72999 |
6b8f52044423c4a93768305375275dbe2c095b0e | 2,189 | package com.showka.service.validator.u05;
import java.math.BigDecimal;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.showka.common.PersistenceTestCase;
import com.showka.domain.builder.ShohinBuilder;
import com.showka.domain.builder.UriageMeisaiBuilder;
import com.showka.domain.u05.UriageMeisai;
import com.showka.domain.z00.Shohin;
import com.showka.service.validator.u05.UriageMeisaiValidatorImpl;
import com.showka.system.exception.validate.NotAllowedNumberException;
public class UriageMeisaiValidatorImplTest extends PersistenceTestCase {
@Autowired
private UriageMeisaiValidatorImpl service;
/**
* validate 正常系.
*
* <pre>
* 入力:売上明細domain <br>
* 条件:正常 <br>
* 結果:成功
*
* <pre>
*/
@Test
public void test01_validate() {
// 商品ドメインダミー
ShohinBuilder sh = new ShohinBuilder();
sh.withRecordId("shohin_record_id");
Shohin shohinDomain = sh.build();
// 売上明細主キー
String uriageId = "KK01-TEST001";
Integer meisaiNumber = 1;
String recordID = uriageId + "-" + meisaiNumber;
// 売上明細ドメイン
UriageMeisaiBuilder b = new UriageMeisaiBuilder();
b.withHanbaiNumber(10);
b.withHanbaiTanka(BigDecimal.valueOf(0));
b.withMeisaiNumber(meisaiNumber);
b.withRecordId(recordID);
b.withShohinDomain(shohinDomain);
b.withVersion(0);
UriageMeisai d = b.build();
// do
service.validate(d);
}
/**
* validate 異常系.
*
* <pre>
* 入力:売上明細domain <br>
* 条件:商品販売単価がマイナス <br>
* 結果:検証例外発生
*
* <pre>
*/
@Test(expected = NotAllowedNumberException.class)
public void test02_validate() {
// 商品ドメインダミー
ShohinBuilder sh = new ShohinBuilder();
sh.withRecordId("shohin_record_id");
Shohin shohinDomain = sh.build();
// 売上明細主キー
String uriageId = "KK01-TEST001";
Integer meisaiNumber = 1;
String recordID = uriageId + "-" + meisaiNumber;
// 売上明細ドメイン
UriageMeisaiBuilder b = new UriageMeisaiBuilder();
b.withHanbaiNumber(10);
b.withHanbaiTanka(BigDecimal.valueOf(-1));
b.withMeisaiNumber(meisaiNumber);
b.withRecordId(recordID);
b.withShohinDomain(shohinDomain);
b.withVersion(0);
UriageMeisai d = b.build();
// do
service.validate(d);
fail();
}
}
| 22.802083 | 72 | 0.723161 |
587eb561cbbf21861daa1ad503578367d64ed611 | 894 | package com.example.plugin;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import java.sql.Connection;
import java.util.Properties;
//v2-chapter5
@Intercepts({@Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class, Integer.class})})
public class MyPlugin implements Interceptor {
//HandlerInterceptor
Properties properties = null;
// 拦截方法逻辑
@Override
public Object intercept(Invocation invocation) throws Throwable {
System.out.println("插件拦截方法......");
return invocation.proceed();
}
// 生成MyBatis拦截器代理对象
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
// 设置插件属性
@Override
public void setProperties(Properties properties) {
this.properties = properties;
}
} | 24.162162 | 69 | 0.678971 |
30819593f71483415861db63b44e3b286cee9319 | 1,832 | package com.andersenlab.crm.utils;
import com.andersenlab.crm.rest.BaseResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
public class ResponseWriter<T> {
private final HttpServletResponse response;
private final BaseResponse<T> responseBody;
private final ObjectMapper objectMapper;
private ResponseWriter(HttpServletResponse response) {
this.response = response;
this.response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
this.responseBody = new BaseResponse<>();
this.objectMapper = new ObjectMapper();
rewriteBody();
}
public static <T> ResponseWriter<T> writer(HttpServletResponse response) {
return new ResponseWriter<>(response);
}
public ResponseWriter<T> addHeader(String name, String value) {
response.addHeader(name, value);
return this;
}
public ResponseWriter<T> setSuccess(boolean success) {
responseBody.setSuccess(success);
rewriteBody();
return this;
}
public ResponseWriter<T> setResponseCode(int responseCode) {
responseBody.setResponseCode(responseCode);
rewriteBody();
return this;
}
public ResponseWriter<T> setErrorMessage(String message) {
responseBody.setErrorMessage(message);
rewriteBody();
return this;
}
public ResponseWriter<T> setData(T data) {
responseBody.setData(data);
rewriteBody();
return this;
}
@SneakyThrows
private HttpServletResponse rewriteBody() {
response.resetBuffer();
response.getOutputStream().write(objectMapper.writeValueAsBytes(responseBody));
return response;
}
}
| 28.625 | 87 | 0.694869 |
2b00a8a538368b98e2ee34baf00304ebf61efeb1 | 161 | package io.eventuate.tram.viewsupport.rebuild;
import io.eventuate.tram.events.common.DomainEvent;
public class SnapshotOffsetEvent implements DomainEvent {
}
| 23 | 57 | 0.838509 |
e6c899ad6edb646b74b2f3c22fc3396595918fdc | 2,141 | package br.ufc.mdcc.mpos.util;
import java.util.regex.Pattern;
/**
* @author Philipp
*/
public final class Util {
private static Pattern patternIpAddress;
private static final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
static {
patternIpAddress = Pattern.compile(IPADDRESS_PATTERN);
}
private Util() {
}
/**
* Validate ip address with regular expression
*
* @param ip
* @return true valid ip address, false invalid ip address
*/
public static boolean validateIpAddress(final String ip) {
return patternIpAddress.matcher(ip).matches();
}
/**
* Esse metodo reconhece um padrão dentro de um array de bytes
*
* @param source
* array que gostaria de buscar o padrao
* @param target
* array alvo que gostaria detectar o padrao neste array
* @return verdade se achou ou falso se não achou
*/
public static boolean containsArrays(byte source[], byte target[]) {
return indexOfArrays(source, target, 0, target.length) > -1;
}
private static int indexOfArrays(byte target[], byte source[], int sourceOffset, int sourceCount) {
int targetOffset = 0, targetCount = target.length;
int fromIndex = 0;
if (fromIndex >= targetCount) {
return (sourceCount == 0 ? targetCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (sourceCount == 0) {
return fromIndex;
}
byte first = source[sourceOffset];
int max = targetOffset + (targetCount - sourceCount);
for (int i = targetOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (target[i] != first) {
while (++i <= max && target[i] != first)
;
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + sourceCount - 1;
for (int k = sourceOffset + 1; j < end && target[j] == source[k]; j++, k++)
;
if (j == end) {
/* Found whole string. */
return i - targetOffset;
}
}
}
return -1;
}
}
| 24.05618 | 100 | 0.596917 |
8aa94a3bbf3b2e26931072cb1d9fc3df5948c844 | 593 | package com.example.projectmanagement.SpringSecurity;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class StateResourceConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/bookpicture/**")
.addResourceLocations("file:F:\\idea2017.1.1代码\\images\\");
}
}
| 37.0625 | 81 | 0.797639 |
0dfd34dc7abe9b593e21ea680bc273a4609fe544 | 333 | package repetition.exercises.solution.inputoutputfilesystems;
import java.io.File;
import java.util.Date;
public class Exercise7 {
public static void main(String[] args) {
File file = new File("test.txt");
Date date = new Date(file.lastModified());
System.out.println("\nThe file was last modified on: " + date + "\n");
}
} | 27.75 | 72 | 0.717718 |
642989d54b4c93a87c95d907e9838cc4390344fe | 1,719 | /*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package goodman.javax.naming.directory;
import goodman.javax.naming.NamingException;
/**
* This class is thrown when an attempt is
* made to add to an attribute a value that conflicts with the attribute's
* schema definition. This could happen, for example, if attempting
* to add an attribute with no value when the attribute is required
* to have at least one value, or if attempting to add more than
* one value to a single valued-attribute, or if attempting to
* add a value that conflicts with the syntax of the attribute.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class InvalidAttributeValueException extends NamingException {
/**
* Constructs a new instance of InvalidAttributeValueException using
* an explanation. All other fields are set to null.
* @param explanation Additional detail about this exception. Can be null.
* @see Throwable#getMessage
*/
public InvalidAttributeValueException(String explanation) {
super(explanation);
}
/**
* Constructs a new instance of InvalidAttributeValueException.
* All fields are set to null.
*/
public InvalidAttributeValueException() {
super();
}
/**
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 8720050295499275011L;
}
| 24.211268 | 84 | 0.687027 |
cb2ab3b294177e967d587a828361cf2811b3e8d9 | 1,391 | package org.didelphis.genetics.alignment.operators.comparators;
import org.didelphis.genetics.alignment.operators.Comparator;
import org.didelphis.language.phonetic.segments.Segment;
import org.didelphis.language.phonetic.sequences.Sequence;
import org.didelphis.structures.contracts.Streamable;
import org.didelphis.structures.maps.SymmetricalTwoKeyMap;
import org.didelphis.structures.tuples.Triple;
import org.jetbrains.annotations.NotNull;
/**
* Class {@code MatrixComparator}
*
* @author Samantha Fiona McCabe
* @since 0.1.0 Date: 2017-07-04
*/
public class BrownEtAlComparator<T> implements Comparator<T> {
private final SymmetricalTwoKeyMap<Segment<T>, Double> map;
private final double max;
public BrownEtAlComparator(
Streamable<Triple<Segment<T>, Segment<T>, Double>> streamable
) {
this.map = new SymmetricalTwoKeyMap<>();
max = streamable.stream()
.map(Triple::getThirdElement)
.max(Double::compare)
.orElse(100.0);
streamable.stream().forEach(t -> this.map.put(
t.getFirstElement(),
t.getSecondElement(),
(max - t.getThirdElement()) / 10.0));
}
@Override
public double apply(@NotNull Sequence<T> left, @NotNull Sequence<T> right,
int i, int j) {
Segment<T> sL = left.get(i);
Segment<T> sR = right.get(j);
Double value = sL.equals(sR)
? 0.0
: (map.contains(sL, sR) ? map.get(sL, sR) : max);
return value;
}
}
| 29.595745 | 75 | 0.726815 |
ce940b6c687b812d7b2704b5673f48ab12c7f52f | 1,357 | /*
* 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 operadoresunarios;
/**
*
* @author rafae
*/
public class OperadoresUnarios {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Número = 5");
System.out.println(" ");
/* Primeiro */
int num1 = 5;
System.out.println("número++");
num1++;
System.out.println(num1);
System.out.println(" ");
/*Segundo*/
int num2 = 5;
System.out.println("5 + número++");
int valor = 5 + num2++;
System.out.println("Resultado = " + valor);
System.out.println("Valor do número = " + num2);
System.out.println(" ");
/* Terceiro */
int num3 = 5;
System.out.println("5 + ++número");
int valor1 = 5 + ++num3;
System.out.println("Resultado = " + valor1);
System.out.println("Valor do número = " + num3);
System.out.println(" ");
}
}
| 22.245902 | 79 | 0.493736 |
de32ffc494e7c0331bfd93f89f3d21c02b9a3dc8 | 2,067 | package mflix.api.daos;
import com.mongodb.ConnectionString;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import mflix.config.MongoDBConfiguration;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@SpringBootTest(classes = {CommentDao.class, MongoDBConfiguration.class})
@EnableConfigurationProperties
@EnableAutoConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class TimeoutsTest extends TicketTest {
@Autowired MongoClient mongoClient;
private String mongoUri;
@Value("${spring.mongodb.database}")
String databaseName;
private MovieDao movieDao;
@Before
public void setUp() throws IOException {
this.movieDao = new MovieDao(mongoClient, databaseName);
mongoUri = getProperty("spring.mongodb.uri");
mongoClient = MongoClients.create(mongoUri);
}
@Test
public void testConfiguredWtimeout() {
WriteConcern wc = this.movieDao.mongoClient.getDatabase("mflix").getWriteConcern();
Assert.assertNotNull(wc);
int actual = wc.getWTimeout(TimeUnit.MILLISECONDS);
int expected = 2500;
Assert.assertEquals("Configured `wtimeout` not set has expected", expected, actual);
}
@Test
public void testConfiguredConnectionTimeoutMs() {
ConnectionString connectionString = new ConnectionString(mongoUri);
int expected = 2000;
int actual = connectionString.getConnectTimeout();
Assert.assertEquals(
"Configured `connectionTimeoutMS` does not match expected", expected, actual);
}
}
| 32.809524 | 88 | 0.79342 |
bb32d5aa8db6234fce5ee831eb58a9b9d02480b9 | 11,039 | /*
* Copyright © 2017 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.hydrator.plugin;
import co.cask.cdap.api.annotation.Description;
import co.cask.cdap.api.annotation.Macro;
import co.cask.cdap.api.annotation.Name;
import co.cask.cdap.api.annotation.Plugin;
import co.cask.cdap.api.data.batch.Output;
import co.cask.cdap.api.data.batch.OutputFormatProvider;
import co.cask.cdap.api.data.format.StructuredRecord;
import co.cask.cdap.api.data.schema.Schema;
import co.cask.cdap.api.dataset.lib.KeyValue;
import co.cask.cdap.etl.api.Emitter;
import co.cask.cdap.etl.api.PipelineConfigurer;
import co.cask.cdap.etl.api.batch.BatchSink;
import co.cask.cdap.etl.api.batch.BatchSinkContext;
import co.cask.hydrator.common.ReferenceBatchSink;
import co.cask.hydrator.common.ReferencePluginConfig;
import co.cask.hydrator.plugin.utils.DynamoDBConstants;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import org.apache.hadoop.io.NullWritable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* A {@link BatchSink} that writes data to DynamoDB.
* This {@link BatchDynamoDBSink} takes a {@link StructuredRecord} in, converts it to Item, and writes it to the
* DynamoDB table.
*/
@Plugin(type = BatchSink.PLUGIN_TYPE)
@Name(BatchDynamoDBSink.PLUGIN_NAME)
@Description("CDAP Amazon DynamoDB Batch Sink takes the structured record from the input source and writes the data " +
"into Amazon DynamoDB.")
public class BatchDynamoDBSink extends ReferenceBatchSink<StructuredRecord, NullWritable, Item> {
public static final String PLUGIN_NAME = "DynamoDB";
private final DynamoDBConfig config;
public BatchDynamoDBSink(DynamoDBConfig config) {
super(config);
this.config = config;
}
@Override
public void configurePipeline(PipelineConfigurer pipelineConfigurer) {
config.validateTableName();
config.validatePrimaryKey(pipelineConfigurer.getStageConfigurer().getInputSchema());
}
@Override
public void prepareRun(BatchSinkContext context) {
context.addOutput(Output.of(config.referenceName, new DynamoDBOutputFormatProvider(config)));
}
@Override
public void transform(StructuredRecord input, Emitter<KeyValue<NullWritable, Item>> emitter) throws Exception {
Set<String> primaryKeyAttributes = Splitter.on(',').trimResults().withKeyValueSeparator(":")
.split(config.primaryKeyFields).keySet();
PrimaryKey primaryKey = new PrimaryKey();
Item item = new Item();
for (Schema.Field field : input.getSchema().getFields()) {
String fieldName = field.getName();
if (primaryKeyAttributes.contains(field.getName())) {
if (input.get(fieldName) == null || Strings.isNullOrEmpty(String.valueOf(input.get(fieldName)))) {
throw new IllegalArgumentException(String.format("Attribute values cannot be null or empty. Null value " +
"found for attribute %s.", fieldName));
}
primaryKey.addComponent(fieldName, input.get(fieldName));
} else {
item.with(fieldName, input.get(fieldName));
}
}
item.withPrimaryKey(primaryKey);
emitter.emit(new KeyValue<>(NullWritable.get(), item));
}
/**
* Config class for Batch DynamoDB Sink
*/
public static class DynamoDBConfig extends ReferencePluginConfig {
@Macro
@Description("The access Id provided by AWS required to access the DynamoDb tables. (Macro Enabled)")
private String accessKey;
@Macro
@Description("AWS access key secret having access to DynamoDb tables. (Macro Enabled)")
private String secretAccessKey;
@Nullable
@Description("The region for AWS Dynamo DB to connect to. Default is us-west-2 i.e. US West (Oregon).")
private String regionId;
@Description("The hostname and port for AWS DynamoDB instance to connect to, separated by a colon. If not " +
"provided, it will be constructed using regionId. Eg. dynamodb.us-east-1.amazonaws.com.")
@Nullable
private String endpointUrl;
@Description("The table to write the data to. If the specified table does not exists, it will be created using " +
"the primary key attributes and key schema and the read and write capacity units.")
private String tableName;
@Description("A comma-separated list of key-value pairs representing the primary key and its attribute type. " +
"The value can be of the following type: 'N'(number), 'S'(string) and 'B'(binary - the byte[] value received " +
"from the previous stage will be converted to binary when storing the data in DynamoDB). Eg. \"Id:N,Region:S\"")
private String primaryKeyFields;
@Description("A comma-separated list of key-value pairs representing the primary key and its attribute type.\n" +
"The key type can have the following values: 'HASH' or 'RANGE'. Eg. \"Id:HASH,Region:HASH\".")
private String primaryKeyTypes;
@Nullable
@Description("The maximum number of strongly consistent reads consumed per second before DynamoDB returns a " +
"ThrottlingException. This will be used when creating a new table if the table name specified by the user does " +
"not exists.")
private String readCapacityUnits;
@Nullable
@Description("The maximum number of writes consumed per second before DynamoDB returns a ThrottlingException. " +
"This will be used when creating a new table if the table name specified by the user does not exists.")
private String writeCapacityUnits;
public DynamoDBConfig(String referenceName, String accessKey, String secretAccessKey, @Nullable String endpointUrl,
@Nullable String regionId, String tableName, String primaryKeyFields,
String primaryKeyTypes, @Nullable String readCapacityUnits,
@Nullable String writeCapacityUnits) {
super(referenceName);
this.endpointUrl = endpointUrl;
this.regionId = regionId;
this.accessKey = accessKey;
this.secretAccessKey = secretAccessKey;
this.tableName = tableName;
this.primaryKeyFields = primaryKeyFields;
this.primaryKeyTypes = primaryKeyTypes;
this.readCapacityUnits = readCapacityUnits;
this.writeCapacityUnits = writeCapacityUnits;
}
/**
* Validates whether the table name follows the DynamoDB naming rules and conventions or not.
*/
private void validateTableName() {
int tableNameLength = tableName.length();
if (tableNameLength < 3 || tableNameLength > 255) {
throw new IllegalArgumentException(
String.format("Table name '%s' does not follow the DynamoDB naming rules. Table name must be between 3 and " +
"255 characters long.", tableName));
}
String pattern = "^[a-zA-Z0-9_.-]+$";
Pattern patternObj = Pattern.compile(pattern);
if (!Strings.isNullOrEmpty(tableName)) {
Matcher matcher = patternObj.matcher(tableName);
if (!matcher.find()) {
throw new IllegalArgumentException(
String.format("Table name '%s' does not follow the DynamoDB naming rules. Table names can contain only " +
"the following characters: 'a-z, A-Z, 0-9, underscore(_), dot(.) and dash(-)'.",
tableName));
}
}
}
/**
* Validates the partition and sort key provided by the user.
*/
private void validatePrimaryKey(Schema inputSchema) {
Set<String> primaryKeyAttributes = Splitter.on(',').trimResults().withKeyValueSeparator(":")
.split(primaryKeyFields).keySet();
Set<String> primaryKeySchema = Splitter.on(',').trimResults().withKeyValueSeparator(":")
.split(primaryKeyTypes).keySet();
if (primaryKeyAttributes.size() > 2 || primaryKeySchema.size() > 2) {
throw new IllegalArgumentException("Primary key can have only 2 values HASH and RANGE.");
}
if (primaryKeyAttributes.size() < 1 || primaryKeySchema.size() < 1) {
throw new IllegalArgumentException("Primary key should have at least one value.");
}
if (!primaryKeyAttributes.equals(primaryKeySchema)) {
throw new IllegalArgumentException(
String.format("Please specify attribute value and key types for the same primary keys. Key type for %s " +
"is not specified.",
com.google.common.collect.Sets.difference(primaryKeyAttributes, primaryKeySchema)));
}
for (String field : primaryKeyAttributes) {
if (inputSchema.getField(field).getSchema().isNullable() || inputSchema.getField(field).getSchema().getType() ==
Schema.Type.NULL) {
throw new IllegalArgumentException(String.format("Attribute values cannot be null. But attribute %s was " +
"found to be of nullable type schema.", field));
}
}
}
}
private static class DynamoDBOutputFormatProvider implements OutputFormatProvider {
private final Map<String, String> conf;
DynamoDBOutputFormatProvider(DynamoDBConfig config) {
this.conf = new HashMap<>();
conf.put(DynamoDBConstants.OUTPUT_TABLE_NAME, config.tableName);
conf.put(DynamoDBConstants.REGION_ID, config.regionId == null ? "" : config.regionId);
conf.put(DynamoDBConstants.ENDPOINT, config.endpointUrl == null ? "" : config.endpointUrl);
conf.put(DynamoDBConstants.DYNAMODB_ACCESS_KEY, config.accessKey);
conf.put(DynamoDBConstants.DYNAMODB_SECRET_KEY, config.secretAccessKey);
conf.put(DynamoDBConstants.PRIMARY_KEY_FIELDS, config.primaryKeyFields);
conf.put(DynamoDBConstants.PRIMARY_KEY_TYPES, config.primaryKeyTypes);
conf.put(DynamoDBConstants.READ_CAPACITY_UNITS, config.readCapacityUnits == null ? "" : config.readCapacityUnits);
conf.put(DynamoDBConstants.WRITE_CAPACITY_UNITS, config.writeCapacityUnits == null ? "" :
config.writeCapacityUnits);
}
@Override
public String getOutputFormatClassName() {
return DynamoDBOutputFormat.class.getName();
}
@Override
public Map<String, String> getOutputFormatConfiguration() {
return conf;
}
}
}
| 45.057143 | 120 | 0.703687 |
f130caa4aec0052e325219465e26c62df4ab86b0 | 263 | package com.thaiopensource.validate.auto;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import com.thaiopensource.validate.auto.SchemaFuture;
public interface SchemaReceiver {
SchemaFuture installHandlers(XMLReader xr) throws SAXException;
}
| 26.3 | 65 | 0.8327 |
e2dea0bcd946fbab50122419ad6778dfc18096cd | 701 | package txengine.systems.dungeon.generate;
import txengine.structures.Canvas;
import txengine.structures.CanvasNode;
import txengine.systems.dungeon.Dungeon;
import java.util.List;
import java.util.Map;
import java.util.Random;
public interface BranchPasser {
List<CanvasNode> pass(final List<CanvasNode> lastPass, final Canvas canvas, final Random rand, final Dungeon owner);
void configure(Map<String, Integer> args);
default void generate(int passes, final Canvas canvas, final Random rand, final Dungeon owner) {
List<CanvasNode> nodes = canvas.allNodes();
for (int i = 0; i < passes; i++) {
nodes = pass(nodes, canvas, rand, owner);
}
}
}
| 31.863636 | 120 | 0.713267 |
487a9b2749e60769c6c93463991b7ee1bd1cb03b | 443 | package org.recap.config;
import brave.sampler.Sampler;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.recap.BaseTestCaseUT;
import static org.junit.Assert.assertNotNull;
public class SamplerConfigUT extends BaseTestCaseUT {
@InjectMocks
SamplerConfig samplerConfig;
@Test
public void defaultSampler() {
Sampler sampler = samplerConfig.defaultSampler();
assertNotNull(sampler);
}
}
| 20.136364 | 57 | 0.747178 |
1c258cbb09cca8c882b4524aae786ba6e231b50e | 538 | package Strategy;
import Main.MainJFrame;
import java.awt.Image;
import javax.swing.ImageIcon;
public class PoliceLightBehaviour implements LightBehaviour {
@Override
public void lightUp(MainJFrame frame) {
Image img = new ImageIcon(getClass().getResource("/Images/Police.png")).getImage();
Image scaledImg = img.getScaledInstance(frame.getLights().getWidth(), frame.getLights().getHeight(),
Image.SCALE_SMOOTH);
frame.getLights().setIcon(new ImageIcon(scaledImg));
}
}
| 28.315789 | 112 | 0.693309 |
10b1dd841549028652a22abac8caddfeecc1e11d | 688 | package com.lee.tac.model;
import java.util.Date;
/**
* author zhaoli
*/
public class View {
private Integer id;
private String time;
private Integer pv;
private Integer uv;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Integer getPv() {
return pv;
}
public void setPv(Integer pv) {
this.pv = pv;
}
public Integer getUv() {
return uv;
}
public void setUv(Integer uv) {
this.uv = uv;
}
} | 14.333333 | 38 | 0.542151 |
fc42ef88707afb109a27d015009690fd6120fc55 | 2,173 | package githubbiostats;
import com.google.common.collect.ImmutableList;
import githubbiostats.biostat.BioStat;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.when;
public class GithubBioStatsTest {
@Mock BioStat<String> mockStat1;
@Mock BioStat<String> mockStat2;
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
String statOutput1 = "Test1";
String statOutput2 = "Test1";
@Before
public void setup() {
when(mockStat1.getBioStat()).thenReturn(statOutput1);
when(mockStat2.getBioStat()).thenReturn(statOutput2);
}
@Test
public void githubBioStatsNullStatsListTest() {
assertThrows(IllegalArgumentException.class, () -> new GithubBioStats(null));
}
@Test
public void githubBioStatsStatsListContainsNullTest() {
assertThrows(NullPointerException.class, () -> new GithubBioStats(
ImmutableList.of(mockStat1, null)
));
}
@Test
public void generateBioEmptyStatListTest() {
GithubBioStats stats = new GithubBioStats(ImmutableList.of());
assertEquals("", stats.generateBio());
}
@Test
public void generateBioSingleStatListTest() {
GithubBioStats stats = new GithubBioStats(ImmutableList.of(mockStat1));
assertEquals(statOutput1, stats.generateBio());
}
@Test
public void generateBioMultiStatListTest() {
GithubBioStats stats = new GithubBioStats(ImmutableList.of(mockStat1, mockStat2));
String expected = String.format("%s | %s", statOutput1, statOutput2);
assertEquals(expected, stats.generateBio());
}
@Test
public void generateBioNullStatOutputTest() {
when(mockStat2.getBioStat()).thenReturn(null);
GithubBioStats stats = new GithubBioStats(ImmutableList.of(mockStat1, mockStat2));
assertEquals(statOutput1, stats.generateBio());
}
}
| 30.180556 | 90 | 0.709158 |
e44c34b03e5426f5ea194d36fa13579dc096b7e1 | 2,386 | import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class insert_Produces {
public static void insert_Pro (String produces) throws SQLException {
String producesT = "INSERT INTO Produces (year_pro,quantity,fid,pid) " + "VALUES (?,?,?,?)";
String query = "SELECT F.fid\n" +
"FROM Farmer F\n" +
"JOIN Farmer_AZ ON Farmer_AZ.faddress = F.faddress\n" +
"JOIN Farmer_ZC ON Farmer_ZC.zipcode = Farmer_AZ.zipcode\n" +
"WHERE F.fname = ? AND F.last_name = ?";
String query2 = "SELECT P.pid\n" +
"FROM Product P\n" +
"WHERE P.pname = ?";
PreparedStatement psPro = main.db_CONN.prepareStatement(producesT,PreparedStatement.RETURN_GENERATED_KEYS);
PreparedStatement q = main.db_CONN.prepareStatement(query);
PreparedStatement q2 = main.db_CONN.prepareStatement(query2);
String[] list = produces.split(",");
int id = 0;
for(int i=0;i<list.length;i++) {
switch (i) {
case 0:
q.setString(1,list[i]);
break;
case 1:
q.setString(2,list[i]);
ResultSet rs = q.executeQuery();
int fid = 0;
while (rs.next()) {
fid = rs.getInt("fid");
}
psPro.setInt(3,fid);
break;
case 2:
q2.setString(1,list[i]);
int pid = 0;
ResultSet rs2 = q2.executeQuery();
while (rs2.next()) {
pid = rs2.getInt("pid");
}
psPro.setInt(4,pid);
break;
case 3:
int amount = Integer.parseInt(list[i]);
psPro.setInt(2,amount);
break;
case 4:
int year = Integer.parseInt(list[i]);
psPro.setInt(1,year);
break;
}
}
psPro.executeUpdate();
}
}
| 41.137931 | 119 | 0.432523 |
438a920e67819826f9e89273bb68243e9fd397f1 | 1,902 | package com.polydes.paint.app.editors.image.tools;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import com.polydes.paint.app.editors.image.DrawArea;
import com.polydes.paint.app.editors.image.ImageUtils;
import com.polydes.paint.app.editors.image.ShapeUtils;
public class Line implements Tool
{
private DrawArea area;
private Point beginPress;
private Rectangle oldDraw;
public Line()
{
beginPress = null;
oldDraw = new java.awt.Rectangle(0, 0, 1, 1);
}
@Override
public void setArea(DrawArea area)
{
this.area = area;
}
@Override
public void press(int x, int y)
{
beginPress = new Point(x, y);
}
@Override
public void drag(int x, int y)
{
area.repaint(oldDraw.x, oldDraw.y, oldDraw.width, oldDraw.height);
oldDraw.x = Math.min(beginPress.x, x);
oldDraw.y = Math.min(beginPress.y, y);
oldDraw.width = Math.max(beginPress.x, x) - oldDraw.x + 2;
oldDraw.height = Math.max(beginPress.y, y) - oldDraw.y + 2;
area.repaint(oldDraw.x, oldDraw.y, oldDraw.width, oldDraw.height);
}
@Override
public void release(int x, int y)
{
ShapeUtils.clip(0, 0, area.img.getWidth(), area.img.getHeight());
ImageUtils.drawPoints(area.img, ShapeUtils.getLine(beginPress.x, beginPress.y, x, y), area.currentRGB);
area.setDirty();
beginPress = null;
}
@Override
public void enter(int x, int y)
{
}
@Override
public void exit(int x, int y)
{
}
@Override
public ToolOptions getOptions()
{
return null;
}
@Override
public void move(int x, int y)
{
}
@Override
public void render(Graphics g, int x, int y, int w, int h)
{
if(beginPress == null)
return;
int s = (int) area.scale;
g.setColor(area.currentColor);
ShapeUtils.clip(x, y, w, h);
for(Point p : ShapeUtils.getLine(beginPress.x, beginPress.y, area.lastUpdated.x, area.lastUpdated.y))
{
g.fillRect(p.x * s, p.y * s, s, s);
}
}
}
| 20.451613 | 105 | 0.686646 |
5bd8290293fa55a1bda7a4071158833b20f6382b | 4,643 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.appium.uiautomator2.handler;
import androidx.test.uiautomator.UiObject;
import androidx.test.uiautomator.UiObjectNotFoundException;
import androidx.test.uiautomator.UiSelector;
import io.appium.uiautomator2.common.exceptions.ElementNotFoundException;
import io.appium.uiautomator2.common.exceptions.InvalidArgumentException;
import io.appium.uiautomator2.handler.request.SafeRequestHandler;
import io.appium.uiautomator2.http.AppiumResponse;
import io.appium.uiautomator2.http.IHttpRequest;
import io.appium.uiautomator2.model.AndroidElement;
import io.appium.uiautomator2.model.AppiumUIA2Driver;
import io.appium.uiautomator2.model.KnownElements;
import static java.util.Objects.requireNonNull;
public class ScrollToElement extends SafeRequestHandler {
public ScrollToElement(String mappedUri) {
super(mappedUri);
}
@Override
protected AppiumResponse safeHandle(IHttpRequest request) throws UiObjectNotFoundException {
String[] elementIds = getElementIds(request);
KnownElements ke = AppiumUIA2Driver.getInstance().getSessionOrThrow().getKnownElements();
AndroidElement element = ke.getElementFromCache(elementIds[0]);
if (element == null) {
throw new ElementNotFoundException();
}
AndroidElement scrollToElement = ke.getElementFromCache(elementIds[1]);
if (scrollToElement == null) {
throw new ElementNotFoundException();
}
// attempt to get UiObjects from the container and scroll to element
// if we can't, we have to error out, since scrollIntoView only works with UiObjects
// (and not for example UiObject2)
// TODO make an equivalent implementation of this method for UiObject2 if possible
StringBuilder errorMsg = new StringBuilder();
UiObject elementUiObject = null;
UiObject scrollElementUiObject = null;
try {
elementUiObject = (UiObject) element.getUiObject();
try {
scrollElementUiObject = (UiObject) scrollToElement.getUiObject();
} catch (ClassCastException e) {
errorMsg.append("Scroll to Element");
}
} catch (ClassCastException e) {
errorMsg.append("Element");
}
if (errorMsg.length() > 0) {
errorMsg.append(" was not an instance of UiObject; only UiSelector is supported. " +
"Ensure you use the '-android uiautomator' locator strategy when " +
"finding elements for use with ScrollToElement");
throw new InvalidArgumentException(errorMsg.toString());
}
UiScrollable uiScrollable = new UiScrollable(requireNonNull(elementUiObject).getSelector());
if (!uiScrollable.scrollIntoView(requireNonNull(scrollElementUiObject))) {
throw new UiObjectNotFoundException(String.format("Cannot scroll to %s element",
requireNonNull(scrollElementUiObject).getSelector().toString()));
}
return new AppiumResponse(getSessionId(request));
}
private static class UiScrollable extends androidx.test.uiautomator.UiScrollable {
public UiScrollable(UiSelector container) {
super(container);
}
@Override
public boolean scrollIntoView(UiObject obj) throws UiObjectNotFoundException {
if (obj.exists()) {
return true;
}
// we will need to reset the search from the beginning to start search
flingToBeginning(getMaxSearchSwipes());
if (obj.exists()) {
return true;
}
for (int x = 0; x < getMaxSearchSwipes(); x++) {
if (!scrollForward()) {
return false;
}
if (obj.exists()) {
return true;
}
}
return false;
}
}
}
| 39.347458 | 100 | 0.665949 |
4479f912c5872d80eca7f78e5b711b39b9f3df84 | 1,194 | package app.model;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import app.util.Quantity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@NoArgsConstructor
public class Tshirt {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "tshirt_id")
private String tshirtID;
@Column(name = "tshirt_quantity")
private int tshirtQuantity;
@Column(name = "tshirt_brand")
private String tshirtBrand;
@Column(name = "tshirt_model")
private String tshirtModel; // male,female,unisex
@Column
private String description;
@Column(name = "in_stock")
private boolean inStock;
@Column
private int size;
@Column
private String colour;
@Column
private double price;
}
| 24.367347 | 78 | 0.79732 |
f3046472265a6c933dacf6cdfec1b3361926c454 | 2,245 | package com.shahin.httpServer.utils;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class ParserUtils {
public final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
public static String parseIncomingUri(String r, Map<String, List<String>> params) {
int s = r.indexOf("?");
if (s < 0) {
return urlDecode(r);
}
decodeParams(r.substring(s + 1), params);
return urlDecode(r.substring(0, s));
}
public static String urlDecode(String str) {
return URLDecoder.decode(str, StandardCharsets.UTF_8);
}
public static void decodeParams(String str, Map<String, List<String>> result) {
StringTokenizer tokenizer = new StringTokenizer(str, "&");
while (tokenizer.hasMoreElements()) {
String p = tokenizer.nextToken();
int pos = p.indexOf("=");
String key;
String value;
if (pos > 0) {
key = urlDecode(p.substring(0, pos));
value = urlDecode(p.substring(pos + 1));
} else {
key = urlDecode(p);
value = "";
}
List<String> vals = result.computeIfAbsent(key, k -> new ArrayList<>());
vals.add(value);
}
}
public static String encodeBase64(byte[] buf) {
int size = buf.length;
char[] ar = new char[(size + 2) / 3 * 4];
int a = 0;
int i = 0;
while (i < size) {
byte b0 = buf[i++];
byte b1 = i < size ? buf[i++] : 0;
byte b2 = i < size ? buf[i++] : 0;
int mask = 0x3F;
ar[a++] = ALPHABET[b0 >> 2 & mask];
ar[a++] = ALPHABET[(b0 << 4 | (b1 & 0xFF) >> 4) & mask];
ar[a++] = ALPHABET[(b1 << 2 | (b2 & 0xFF) >> 6) & mask];
ar[a++] = ALPHABET[b2 & mask];
}
switch (size % 3) {
case 1:
ar[--a] = '=';
case 2:
ar[--a] = '=';
}
return new String(ar);
}
}
| 31.619718 | 123 | 0.513586 |
f765cbbb1ccef96974a49abbf9f79a55e929c17b | 3,560 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.db.tools.memestimation;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import io.airlift.airline.Cli;
import io.airlift.airline.Help;
import io.airlift.airline.ParseArgumentsMissingException;
import io.airlift.airline.ParseArgumentsUnexpectedException;
import io.airlift.airline.ParseCommandMissingException;
import io.airlift.airline.ParseCommandUnrecognizedException;
import io.airlift.airline.ParseOptionConversionException;
import io.airlift.airline.ParseOptionMissingException;
import io.airlift.airline.ParseOptionMissingValueException;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.engine.fileSystem.SystemFileFactory;
public class MemEstTool {
public static void main(String... args) throws IOException {
List<Class<? extends Runnable>> commands = Lists.newArrayList(
Help.class,
MemEstToolCmd.class
);
Cli.CliBuilder<Runnable> builder = Cli.builder("memory-tool");
builder.withDescription("Estimate memory for writing")
.withDefaultCommand(Help.class)
.withCommands(commands);
Cli<Runnable> parser = builder.build();
int status = 0;
try {
Runnable parse = parser.parse(args);
parse.run();
} catch (IllegalArgumentException |
IllegalStateException |
ParseArgumentsMissingException |
ParseArgumentsUnexpectedException |
ParseOptionConversionException |
ParseOptionMissingException |
ParseOptionMissingValueException |
ParseCommandMissingException |
ParseCommandUnrecognizedException e) {
badUse(e);
status = 1;
} catch (Exception e) {
err(Throwables.getRootCause(e));
status = 2;
}
FileUtils.deleteDirectory(SystemFileFactory.INSTANCE.getFile(IoTDBDescriptor.getInstance().getConfig().getSystemDir()));
FileUtils.deleteDirectory(SystemFileFactory.INSTANCE.getFile(IoTDBDescriptor.getInstance().getConfig().getWalDir()));
for(int i=0; i < IoTDBDescriptor.getInstance().getConfig().getDataDirs().length; i++){
FileUtils.deleteDirectory(SystemFileFactory.INSTANCE.getFile(IoTDBDescriptor.getInstance().getConfig().getDataDirs()[i]));
}
System.exit(status);
}
private static void badUse(Exception e) {
System.out.println("memory-tool: " + e.getMessage());
System.out.println("See 'memory-tool help' or 'memory-tool help <command>'.");
}
private static void err(Throwable e) {
System.err.println("error: " + e.getMessage());
System.err.println("-- StackTrace --");
System.err.println(Throwables.getStackTraceAsString(e));
}
}
| 37.87234 | 128 | 0.741292 |
b32a7cd3911917bff6206c634f7f06be5ab42096 | 1,897 | package io.onebeacon.sample.baseservice;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.Collection;
import io.onebeacon.api.Beacon;
import io.onebeacon.api.BeaconsMonitor;
/**
* Monitor Service
*/
public class MonitorService extends Service {
/** Simple binder that returns the in-process service instance */
class LocalServiceBinder extends Binder {
MonitorService getService() {
return MonitorService.this;
}
}
private final LocalServiceBinder mBinder = new LocalServiceBinder();
private boolean mServiceStarted = false;
private BeaconsMonitor mBeaconsMonitor = null;
@Override
public IBinder onBind(Intent intent) {
log("onBind");
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
log("onStartCommand");
if (!mServiceStarted) {
if (null == mBeaconsMonitor) {
// create and start a new beacons monitor, subclassing a few callbacks
mBeaconsMonitor = new MyBeaconsMonitor(this);
}
mServiceStarted = true;
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
log("onDestroy");
// unregister from beacons API
if (null != mBeaconsMonitor) {
mBeaconsMonitor.close();
mBeaconsMonitor = null;
}
mServiceStarted = false;
super.onDestroy();
}
/** Return all the known beacons, for example to be bound to an adapter for displaying them **/
public Collection<Beacon> getBeacons() {
return mBeaconsMonitor.getBeacons();
}
private void log(String msg) {
Log.d("MonitorService", msg);
}
} | 25.635135 | 99 | 0.642066 |
5ce1c537dbe835b3cca2a80c97e70e81f3c1414b | 395 | package mxrcon.Code;
public class DefineValues
{
public static final int MODULE_VERSION_SUPPORT = 1;
public static final String PATH_FILE_SETTING = "setting.xml";
public static final String PATH_FILE_SERVERS = "servers.xml";
public static final String PATH_FOLDER_PLUGIN = "./plugins/";
public static final String PATH_FOLDER_MODULES_PROVIDERS_QUOTES = "/Plugins/Games/";
} | 35.909091 | 88 | 0.764557 |
e43cd0d895439bfb6f37ce49c6201640d70683c2 | 3,330 | package com.gemserk.resources.monitor;
import static org.junit.Assert.assertThat;
import org.hamcrest.core.IsEqual;
import org.junit.Test;
import com.gemserk.resources.MockResource;
import com.gemserk.resources.dataloaders.MockDataLoader;
public class ResourceStatusMonitorTest {
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void shouldDetectWhenResourceWasLoaded() {
MockResource resource = new MockResource(new MockDataLoader("DATA"));
ResourceStatusMonitor resourceStatusMonitor = new ResourceStatusMonitor(resource);
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasLoaded(), IsEqual.equalTo(false));
resource.load();
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasLoaded(), IsEqual.equalTo(true));
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void shouldDetectWhenResourceWasLoadedOnlyOnce() {
MockResource resource = new MockResource(new MockDataLoader("DATA"));
ResourceStatusMonitor resourceStatusMonitor = new ResourceStatusMonitor(resource);
resource.load();
resourceStatusMonitor.checkChanges();
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasLoaded(), IsEqual.equalTo(false));
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasLoaded(), IsEqual.equalTo(false));
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void shouldNotDetectWasLoadedIfWasLoadedBefore() {
MockResource resource = new MockResource(new MockDataLoader("DATA"));
resource.load();
ResourceStatusMonitor resourceStatusMonitor = new ResourceStatusMonitor(resource);
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasLoaded(), IsEqual.equalTo(false));
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void shouldDetectWhenResourceWasUnloaded() {
MockResource resource = new MockResource(new MockDataLoader("DATA"));
resource.load();
ResourceStatusMonitor resourceStatusMonitor = new ResourceStatusMonitor(resource);
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasUnloaded(), IsEqual.equalTo(false));
resource.unload();
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasUnloaded(), IsEqual.equalTo(true));
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void shouldDetectWhenResourceWasUnloadedOnlyOnce() {
MockResource resource = new MockResource(new MockDataLoader("DATA"));
resource.load();
ResourceStatusMonitor resourceStatusMonitor = new ResourceStatusMonitor(resource);
resource.unload();
resourceStatusMonitor.checkChanges();
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasUnloaded(), IsEqual.equalTo(false));
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasUnloaded(), IsEqual.equalTo(false));
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void shouldNotDetectWhenResourceWasUnloadedIfWasNotLoaded() {
MockResource resource = new MockResource(new MockDataLoader("DATA"));
resource.unload();
ResourceStatusMonitor resourceStatusMonitor = new ResourceStatusMonitor(resource);
resourceStatusMonitor.checkChanges();
assertThat(resourceStatusMonitor.wasUnloaded(), IsEqual.equalTo(false));
}
}
| 32.019231 | 84 | 0.793093 |
71127de628da4cb882ceb3cf90faa7d7a7b41498 | 71 | public class Foo {
void m() {
true && false.<caret>
}
} | 14.2 | 29 | 0.464789 |
323629271247664930469feacf8c0358a5309808 | 1,627 | package com.db117.example.leetcode.solution;
/**
* 实现 pow(x, n) ,即计算 x 的 n 次幂函数。
* <p>
* 示例 1:
* <p>
* 输入: 2.00000, 10
* 输出: 1024.00000
* 示例 2:
* <p>
* 输入: 2.10000, 3
* 输出: 9.26100
* 示例 3:
* <p>
* 输入: 2.00000, -2
* 输出: 0.25000
* 解释: 2-2 = 1/22 = 1/4 = 0.25
* 说明:
* <p>
* -100.0 < x < 100.0
* n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/powx-n
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @author db117
* @date 2019/6/24
**/
public class Solution50 {
public static void main(String[] args) {
System.out.println(new Solution50().myPow2(2.0, 2));
}
public double myPow(double x, int n) {
if (n < 0) {
// 如果幂为负数
x = 1 / x;
n = -n;
}
return pow(x, n);
}
public double pow(double x, long n) {
if (n == 0) {
// 结束
return 1;
}
double pow = pow(x, n / 2);
if (n % 2 == 0) {
// 如果为偶数
return pow * pow;
} else {
// 奇数
return pow * pow * x;
}
}
// 循环
public double myPow2(double x, int n) {
if (n < 0) {
//
x = 1 / x;
n = -n;
}
double res = 1;
double cur = x;
int index = n;
while (index > 0) {
if ((index % 2) == 1) {
// 当n为奇数时,把多余的1单拉出来乘
res = res * cur;
}
// 如果index==1时,一下无效
cur = cur * cur;
index = index / 2;
}
return res;
}
}
| 18.488636 | 60 | 0.408113 |
36d9fd7be698ec126e59ce7efda9e0f38b1644e0 | 1,749 | // Copyright 2020 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 com.android.webview.chromium;
import android.annotation.TargetApi;
import android.net.Network;
import android.webkit.PacProcessor;
import org.chromium.android_webview.AwPacProcessor;
import org.chromium.base.JNIUtils;
import org.chromium.base.library_loader.LibraryLoader;
@TargetApi(28)
final class PacProcessorImpl implements PacProcessor {
static {
JNIUtils.setClassLoader(WebViewChromiumFactoryProvider.class.getClassLoader());
LibraryLoader.getInstance().ensureInitialized();
// This will set up Chromium environment to run proxy resolver.
AwPacProcessor.initializeEnvironment();
}
private static class LazyHolder {
static final PacProcessorImpl sInstance = new PacProcessorImpl();
}
AwPacProcessor mProcessor;
private PacProcessorImpl() {
mProcessor = new AwPacProcessor();
}
public static PacProcessor getInstance() {
return LazyHolder.sInstance;
}
public static PacProcessor createInstance() {
return new PacProcessorImpl();
}
@Override
public void release() {
mProcessor.destroy();
}
@Override
public boolean setProxyScript(String script) {
return mProcessor.setProxyScript(script);
}
@Override
public String findProxyForUrl(String url) {
return mProcessor.makeProxyRequest(url);
}
@Override
public void setNetwork(Network network) {
mProcessor.setNetwork(network);
}
@Override
public Network getNetwork() {
return mProcessor.getNetwork();
}
}
| 25.720588 | 87 | 0.707833 |
6cf744d9c84fc6f4e56042fe3da4348b28f9f4b4 | 2,246 | package net.optifine.entity.model;
import java.util.Iterator;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.client.renderer.entity.GhastRenderer;
import net.minecraft.client.renderer.entity.model.GhastModel;
import net.minecraft.client.renderer.model.Model;
import net.minecraft.client.renderer.model.ModelRenderer;
import net.minecraft.entity.EntityType;
import net.optifine.Config;
public class ModelAdapterGhast extends ModelAdapter
{
public ModelAdapterGhast()
{
super(EntityType.GHAST, "ghast", 0.5F);
}
public Model makeModel()
{
return new GhastModel();
}
public ModelRenderer getModelRenderer(Model model, String modelPart)
{
if (!(model instanceof GhastModel))
{
return null;
}
else
{
GhastModel ghastmodel = (GhastModel)model;
Iterator<ModelRenderer> iterator = ghastmodel.getParts().iterator();
if (modelPart.equals("body"))
{
return ModelRendererUtils.getModelRenderer(iterator, 0);
}
else
{
String s = "tentacle";
if (modelPart.startsWith(s))
{
String s1 = modelPart.substring(s.length());
int i = Config.parseInt(s1, -1);
return ModelRendererUtils.getModelRenderer(iterator, i);
}
else
{
return null;
}
}
}
}
public String[] getModelRendererNames()
{
return new String[] {"body", "tentacle1", "tentacle2", "tentacle3", "tentacle4", "tentacle5", "tentacle6", "tentacle7", "tentacle8", "tentacle9"};
}
public IEntityRenderer makeEntityRender(Model modelBase, float shadowSize)
{
EntityRendererManager entityrenderermanager = Minecraft.getInstance().getRenderManager();
GhastRenderer ghastrenderer = new GhastRenderer(entityrenderermanager);
ghastrenderer.entityModel = (GhastModel)modelBase;
ghastrenderer.shadowSize = shadowSize;
return ghastrenderer;
}
}
| 31.194444 | 154 | 0.617542 |
1a49f6670c6f75333a33f5950d36d9bffbe9c232 | 4,109 | package edu.harvard.hms.dbmi.avillach.hpds.etl.phenotype;
import java.io.*;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.log4j.Logger;
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
import edu.harvard.hms.dbmi.avillach.hpds.crypto.Crypto;
import edu.harvard.hms.dbmi.avillach.hpds.data.phenotype.PhenoCube;
@SuppressWarnings({"unchecked", "rawtypes"})
public class CSVLoader {
private static LoadingStore store = new LoadingStore();
private static Logger log = Logger.getLogger(CSVLoader.class);
private static final int PATIENT_NUM = 0;
private static final int CONCEPT_PATH = 1;
private static final int NUMERIC_VALUE = 2;
private static final int TEXT_VALUE = 3;
private static final int DATETIME = 4;
public static void main(String[] args) throws IOException {
store.allObservationsStore = new RandomAccessFile("/opt/local/hpds/allObservationsStore.javabin", "rw");
initialLoad();
store.saveStore();
}
private static void initialLoad() throws IOException {
Crypto.loadDefaultKey();
Reader in = new FileReader("/opt/local/hpds/allConcepts.csv");
Iterable<CSVRecord> records = CSVFormat.DEFAULT.withSkipHeaderRecord().withFirstRecordAsHeader().parse(new BufferedReader(in, 1024*1024));
final PhenoCube[] currentConcept = new PhenoCube[1];
for (CSVRecord record : records) {
processRecord(currentConcept, record);
}
}
private static void processRecord(final PhenoCube[] currentConcept, CSVRecord record) {
if(record.size()<4) {
log.info("Record number " + record.getRecordNumber()
+ " had less records than we expected so we are skipping it.");
return;
}
try {
String conceptPathFromRow = record.get(CONCEPT_PATH);
String[] segments = conceptPathFromRow.split("\\\\");
for(int x = 0;x<segments.length;x++) {
segments[x] = segments[x].trim();
}
conceptPathFromRow = String.join("\\", segments) + "\\";
conceptPathFromRow = conceptPathFromRow.replaceAll("\\ufffd", "");
String textValueFromRow = record.get(TEXT_VALUE) == null ? null : record.get(TEXT_VALUE).trim();
if(textValueFromRow!=null) {
textValueFromRow = textValueFromRow.replaceAll("\\ufffd", "");
}
String conceptPath = conceptPathFromRow.endsWith("\\" +textValueFromRow+"\\") ? conceptPathFromRow.replaceAll("\\\\[^\\\\]*\\\\$", "\\\\") : conceptPathFromRow;
// This is not getDouble because we need to handle null values, not coerce them into 0s
String numericValue = record.get(NUMERIC_VALUE);
if((numericValue==null || numericValue.isEmpty()) && textValueFromRow!=null) {
try {
numericValue = Double.parseDouble(textValueFromRow) + "";
}catch(NumberFormatException e) {
}
}
boolean isAlpha = (numericValue == null || numericValue.isEmpty());
if(currentConcept[0] == null || !currentConcept[0].name.equals(conceptPath)) {
System.out.println(conceptPath);
try {
currentConcept[0] = store.store.get(conceptPath);
} catch(InvalidCacheLoadException e) {
currentConcept[0] = new PhenoCube(conceptPath, isAlpha ? String.class : Double.class);
store.store.put(conceptPath, currentConcept[0]);
}
}
String value = isAlpha ? record.get(TEXT_VALUE) : numericValue;
if(value != null && !value.trim().isEmpty() && ((isAlpha && currentConcept[0].vType == String.class)||(!isAlpha && currentConcept[0].vType == Double.class))) {
value = value.trim();
currentConcept[0].setColumnWidth(isAlpha ? Math.max(currentConcept[0].getColumnWidth(), value.getBytes().length) : Double.BYTES);
int patientId = Integer.parseInt(record.get(PATIENT_NUM));
Date date = null;
if(record.size()>4 && record.get(DATETIME) != null && ! record.get(DATETIME).isEmpty()) {
date = new Date(Long.parseLong(record.get(DATETIME)));
}
currentConcept[0].add(patientId, isAlpha ? value : Double.parseDouble(value), date);
store.allIds.add(patientId);
}
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
| 38.401869 | 163 | 0.711365 |
f7318b7e19143ba58230e96ca1a635a288327b49 | 801 | package org.jboss.resteasy.tracing.providers.jsonb;
import org.jboss.resteasy.tracing.api.RESTEasyTracingInfoFormat;
import org.jboss.resteasy.tracing.api.providers.TextBasedRESTEasyTracingInfo;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
public class JSONBJsonFormatRESTEasyTracingInfo extends TextBasedRESTEasyTracingInfo {
private Jsonb mapper = JsonbBuilder.create();
@Override
public String[] getMessages() {
try {
return new String[]{mapper.toJson(messageList)};
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public boolean supports(RESTEasyTracingInfoFormat format) {
if (format.equals(RESTEasyTracingInfoFormat.JSON))
return true;
else
return false;
}
}
| 26.7 | 86 | 0.725343 |
858d8e2f258a95f35f631f9218e6beb169a54031 | 2,656 | package com.example.newschool.activity;
import android.content.Intent;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;
import com.example.newschool.R;
import com.example.newschool.adapter.HomeworkFragmentAdapter;
import com.example.newschool.fragment.HomeworkFragment1;
import com.example.newschool.fragment.HomeworkFragment2;
public class StuHomeworkActivity extends AppCompatActivity implements
HomeworkFragment1.OnFragmentInteractionListener,
HomeworkFragment2.OnFragmentInteractionListener{
private Toolbar toolbar;
private TabLayout tableLayout;
private ViewPager viewPager;
private HomeworkFragmentAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stu_homework);
initView();
}
private void initView() {
toolbar=findViewById(R.id.DoHomeworkActivity_toolbar);
tableLayout=findViewById(R.id.DoHomeworkActivity_tabLayout);
viewPager=findViewById(R.id.DoHomeworkActivity_viewPage);
setSupportActionBar(toolbar);
//toolbar.setTitle("签到详情[" + intent.getStringExtra("signCode") + "]");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
adapter = new HomeworkFragmentAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tableLayout.setupWithViewPager(viewPager);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//TODO 菜单的逻辑实现
case android.R.id.home:
finish();
break;
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
adapter.getItem(1).onActivityResult(requestCode, resultCode, data);
}
@Override
public void onFragmentInteraction(final String done,final String not) {
runOnUiThread(new Runnable() {
@Override
public void run() {
((TextView)findViewById(R.id.HomeworkFragment1_textDone)).setText(done);
((TextView)findViewById(R.id.HomeworkFragment1_textNot)).setText(not);
}
});
}
}
| 36.383562 | 88 | 0.712349 |
2b894521bb2dc38ec47c660a9b13dbab71a209c2 | 923 | package com.bugtrack.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Embeddable;
import java.io.Serializable;
/**
* The grpermission provides data structure
* to store links between users and groups
* @version 0.9.9 1 July 2016
* @author Sergey Samsonov
*/
public class grpermiss implements Serializable {
@Column
private Integer groupid;
@Column
private Integer permissid;
public grpermiss () {
}
public grpermiss ( Integer groupid, Integer permissid ) {
this.groupid = groupid;
this.permissid = permissid;
}
public Integer getGroupid() { return this.groupid; }
public void setGroupid(Integer groupid) {
this.groupid = groupid;
}
public Integer getPermissid() { return this.permissid; }
public void setPermissid(Integer permissid) {
this.permissid = permissid;
}
}
| 20.977273 | 61 | 0.691224 |
b5a136a2adf71bc51c26dc562bd8a79c92617391 | 6,547 | package io.ebean.xtest.plugin;
import io.ebean.DB;
import io.ebean.Database;
import io.ebean.FetchPath;
import io.ebean.Query;
import io.ebean.plugin.BeanDocType;
import io.ebean.plugin.BeanType;
import io.ebean.plugin.Property;
import io.ebean.text.PathProperties;
import io.ebeaninternal.api.SpiQuery;
import io.ebeaninternal.server.querydefn.OrmQueryDetail;
import org.junit.jupiter.api.Test;
import org.tests.inheritance.Stockforecast;
import org.tests.model.basic.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
public class BeanTypeTest {
private static Database db = DB.getDefault();
private <T> BeanType<T> beanType(Class<T> cls) {
return db.pluginApi().beanType(cls);
}
@Test
public void getBeanType() {
assertThat(beanType(Order.class).type()).isEqualTo(Order.class);
}
@Test
public void getTypeAtPath_when_ManyToOne() {
BeanType<Order> orderType = beanType(Order.class);
BeanType<?> customerType = orderType.beanTypeAtPath("customer");
assertThat(customerType.type()).isEqualTo(Customer.class);
}
@Test
public void getTypeAtPath_when_OneToMany() {
BeanType<Order> orderType = beanType(Order.class);
BeanType<?> detailsType = orderType.beanTypeAtPath("details");
assertThat(detailsType.type()).isEqualTo(OrderDetail.class);
}
@Test
public void getTypeAtPath_when_nested() {
BeanType<Order> orderType = beanType(Order.class);
BeanType<?> productType = orderType.beanTypeAtPath("details.product");
assertThat(productType.type()).isEqualTo(Product.class);
}
@Test
public void getTypeAtPath_when_simpleType() {
assertThrows(RuntimeException.class, () -> beanType(Order.class).beanTypeAtPath("status"));
}
@Test
public void createBean() {
assertThat(beanType(Order.class).createBean()).isNotNull();
}
@Test
public void property() {
Order order = new Order();
order.setStatus(Order.Status.APPROVED);
Property statusProperty = beanType(Order.class).property("status");
assertThat(statusProperty.value(order)).isEqualTo(order.getStatus());
}
@Test
public void getBaseTable() {
assertThat(beanType(Order.class).baseTable()).isEqualTo("o_order");
}
@Test
public void beanId_and_getBeanId() {
Order order = new Order();
order.setId(42);
Object id1 = beanType(Order.class).id(order);
assertThat(id1).isEqualTo(order.getId());
}
@Test
public void setBeanId() {
Order order = new Order();
beanType(Order.class).setId(order, 42);
assertThat(42).isEqualTo(order.getId());
}
@Test
public void isDocStoreIndex() {
assertThat(beanType(Order.class).isDocStoreMapped()).isFalse();
assertThat(beanType(Person.class).isDocStoreMapped()).isFalse();
assertThat(beanType(Order.class).docMapping()).isNotNull();
assertThat(beanType(Person.class).docMapping()).isNull();
}
@Test
public void docStore_getEmbedded() {
BeanDocType<Order> orderDocType = beanType(Order.class).docStore();
FetchPath customer = orderDocType.embedded("customer");
assertThat(customer).isNotNull();
assertThat(customer.getProperties(null)).contains("id", "name");
}
@Test
public void docStore_getEmbeddedManyRoot() {
BeanDocType<Order> orderDocType = beanType(Order.class).docStore();
FetchPath detailsPath = orderDocType.embedded("details");
assertThat(detailsPath).isNotNull();
FetchPath detailsRoot = orderDocType.embeddedManyRoot("details");
assertThat(detailsRoot).isNotNull();
assertThat(detailsRoot.getProperties(null)).containsExactly("id", "details");
assertThat(detailsRoot.hasPath("details")).isTrue();
}
@Test
public void getDocStoreQueueId() {
assertThat(beanType(Order.class).docStoreQueueId()).isEqualTo("order");
assertThat(beanType(Customer.class).docStoreQueueId()).isEqualTo("customer");
}
@Test
public void getDocStoreIndexType() {
assertThat(beanType(Order.class).docStore().indexType()).isEqualTo("order");
assertThat(beanType(Customer.class).docStore().indexType()).isEqualTo("customer");
}
@Test
public void getDocStoreIndexName() {
assertThat(beanType(Order.class).docStore().indexType()).isEqualTo("order");
assertThat(beanType(Customer.class).docStore().indexType()).isEqualTo("customer");
}
@Test
public void docStoreNested() {
FetchPath parse = PathProperties.parse("id,name");
FetchPath nestedCustomer = beanType(Order.class).docStore().embedded("customer");
assertThat(nestedCustomer.toString()).isEqualTo(parse.toString());
}
@Test
public void docStoreApplyPath() {
SpiQuery<Order> orderQuery = (SpiQuery<Order>) db.find(Order.class);
beanType(Order.class).docStore().applyPath(orderQuery);
OrmQueryDetail detail = orderQuery.getDetail();
assertThat(detail.getChunk("customer", false).getIncluded()).containsExactly("id", "name");
}
@Test
public void docStoreIndex() {
assertThrows(IllegalStateException.class, () -> beanType(Order.class).docStore().index(1, new Order(), null));
}
@Test
public void docStoreDeleteById() {
assertThrows(IllegalStateException.class, () -> beanType(Order.class).docStore().deleteById(1, null));
}
@Test
public void docStoreUpdateEmbedded() {
assertThrows(IllegalStateException.class, () -> beanType(Order.class).docStore().updateEmbedded(1, "customer", "someJson", null));
}
@Test
public void hasInheritance_when_not() {
assertFalse(beanType(Order.class).hasInheritance());
}
@Test
public void hasInheritance_when_root() {
assertTrue(beanType(Vehicle.class).hasInheritance());
}
@Test
public void hasInheritance_when_leaf() {
assertTrue(beanType(Car.class).hasInheritance());
}
@Test
public void getDiscColumn_when_default() {
assertEquals(beanType(Car.class).discColumn(), "dtype");
}
@Test
public void getDiscColumn_when_set() {
assertEquals(beanType(Stockforecast.class).discColumn(), "type");
}
@Test
public void createBeanUsingDisc_when_set() {
Vehicle vehicle = beanType(Vehicle.class).createBeanUsingDisc("C");
assertTrue(vehicle instanceof Car);
}
@Test
public void addInheritanceWhere_when_leaf() {
Query<Vehicle> query = db.find(Vehicle.class);
beanType(Car.class).addInheritanceWhere(query);
}
@Test
public void addInheritanceWhere_when_root() {
Query<Vehicle> query = db.find(Vehicle.class);
beanType(Vehicle.class).addInheritanceWhere(query);
}
}
| 28.219828 | 134 | 0.719719 |
c1772d25a0aa0e3b93d9329720148f14d10f1297 | 3,813 | package controllers;
import config.AuthorizationServerManager;
import config.AuthorizationServerSecure;
import config.JwtUtils;
import dtos.ConstraintGroups;
import dtos.RegistrationDto;
import models.User;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.*;
import repositories.EventRepository;
import repositories.UserRepository;
import javax.inject.Inject;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
public class LoginController extends Controller {
private final FormFactory formFactory;
private final UserRepository userRepository;
private final EventRepository eventRepository;
private final JwtUtils jwtUtils;
private final AuthorizationServerManager authorizationServerManager;
@Inject
public LoginController(FormFactory formFactory, UserRepository userRepository, EventRepository eventRepository, JwtUtils jwtUtils, AuthorizationServerManager authorizationServerManager) {
this.formFactory = formFactory;
this.userRepository = userRepository;
this.eventRepository = eventRepository;
this.jwtUtils = jwtUtils;
this.authorizationServerManager = authorizationServerManager;
}
@AuthorizationServerSecure(optional = true)
public Result get(String next) {
Optional<User> user = request().attrs().getOptional(AuthorizationServerSecure.USER);
if(user.isPresent()){ // already authenticated
if(next != null && next.matches("^/.*$"))
return redirect(next);
else
return redirect(routes.ProfileController.get());
}
return ok(views.html.login.render(next, authorizationServerManager.getProviders()));
}
public Result post(String next) {
Form<RegistrationDto> form = formFactory.form(RegistrationDto.class, ConstraintGroups.Login.class).bindFromRequest();
if(form.hasErrors()) {
flash("warning", "Please fill in the form");
return redirect(routes.LoginController.get(next));
}
List<User> list = userRepository.findByUsernameOrEmailMulti(form.get().getEmail());
User validUser = null;
boolean disabled = false;
for (User user : list) {
if(user != null && user.checkPassword(form.get().getPassword())) {
if (user.isDisabled()) {
disabled = true;
continue;
}
validUser = user;
break;
}
}
if (disabled) {
flash("error", "Your account was disabled.");
return redirect(routes.LoginController.get(next));
} else if (validUser == null) {
flash("error", "Invalid login");
eventRepository.badLogin(request(), null, form.get().getEmail());
return redirect(routes.LoginController.get(next));
} else {
flash("info", "Login successful");
eventRepository.login(request(), validUser, form.get().getEmail());
return jwtUtils.prepareCookieThenRedirect(validUser, next);
}
}
@AuthorizationServerSecure(optional = true)
public Result logout(){
Optional<User> user = request().attrs().getOptional(AuthorizationServerSecure.USER);
Http.Cookie ltat = Http.Cookie.builder("ltat", "")
.withPath("/").withHttpOnly(true).withMaxAge(Duration.ZERO).build();
Optional<String> referer = request().header("Referer");
eventRepository.logout(request(), user.orElse(null));
flash("info", "Logout successful");
if(referer.isPresent()){
return redirect(referer.get()).withCookies(ltat);
} else {
return redirect(routes.LoginController.get(null));
}
}
}
| 39.309278 | 191 | 0.654603 |
0588c8985e0c0b61e262c5957e07c6bd43d44656 | 1,202 | package listeningrain.cn.blog.utils;
import java.security.MessageDigest;
/**
* User: sunqingfeng6
* Date: 2018/11/19 9:25
* Description:
*/
public class EncryptUtils {
//MD5加密
public static String MD5(String originStr) {
char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
try {
byte[] btInput = originStr.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
String result = new String(str);
//LOGGER.debug("Origin string: {}, md5 string: {}", originStr, result);
return result;
} catch (Exception e) {
return null;
}
}
}
| 30.05 | 91 | 0.477537 |
eaf2db629c5eba15b411b3224770e172db735280 | 669 | package com.virt.GCM;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* Class helper for receiving the broadcast messages
*
* @author KjellZijlemaker
*
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
| 26.76 | 68 | 0.793722 |
334278cb943ea147c26ed3de5fcade3bc36f347a | 2,181 | package cn.az.project.news.admin.shiro;
import cn.az.project.news.core.jwt.JwtFilter;
import cn.hutool.core.map.MapUtil;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* ShiroConfiguration
*
* @author <a href="mailto:[email protected]">az</a>
* @see ShiroRealm
* @since 2020-03-20
*/
@Configuration
public class ShiroConfiguration {
private static final String JWT = "jwt";
@Autowired
private ShiroRealm shiroRealm;
@Bean
public SessionsSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm);
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean() {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
factoryBean.setSecurityManager(securityManager());
Map<String, Filter> filters = MapUtil.createMap(LinkedHashMap.class);
filters.put(JWT, jwtFilter());
factoryBean.setFilters(filters);
Map<String, String> filterChain = MapUtil.createMap(LinkedHashMap.class);
filterChain.put("/*", JWT);
factoryBean.setFilterChainDefinitionMap(filterChain);
return factoryBean;
}
@Bean
public JwtFilter jwtFilter() {
return new JwtFilter();
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
return authorizationAttributeSourceAdvisor;
}
}
| 33.045455 | 124 | 0.757909 |
87c846994132f4d9ca53f8b5d6853ee555d16d5b | 1,902 | package com.seko0716.es.plugin.pipeline.rest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;
import java.io.IOException;
import java.util.Map;
import static com.seko0716.es.plugin.pipeline.constants.IndexConstants.INDEX;
import static com.seko0716.es.plugin.pipeline.constants.IndexConstants.TYPE;
import static com.seko0716.es.plugin.pipeline.constants.RestConstants.PARAMS_PIPELINE_ID;
import static com.seko0716.es.plugin.pipeline.constants.RestConstants.PATH_WITH_ID;
import static org.elasticsearch.rest.RestRequest.Method.POST;
public class RestPostPipelineAction extends BaseRestHandler {
public RestPostPipelineAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(POST, PATH_WITH_ID, this);
}
@Override
public String getName() {
return "Create or update pipeline";
}
@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
String pipelineId = request.param(PARAMS_PIPELINE_ID);
try (XContentParser xContentParser = request.contentParser()) {
Map<String, Object> pipelineBody = xContentParser.mapOrdered();
UpdateRequest createOrUpdateRequest = new UpdateRequest(INDEX, TYPE, pipelineId);
createOrUpdateRequest.docAsUpsert(true);
createOrUpdateRequest.doc(pipelineBody);
return channel -> client.update(createOrUpdateRequest, new RestToXContentListener<>(channel));
}
}
} | 42.266667 | 118 | 0.77918 |
af86df10ea00a5a9ea42b50a95f4c1ff9efedf4c | 3,543 | /*
* Copyright 2014+ Carnegie Mellon University
*
* 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 edu.cmu.lti.oaqa.flexneuart.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Test;
import edu.cmu.lti.oaqa.flexneuart.utils.CompressUtils;
import edu.cmu.lti.oaqa.flexneuart.utils.Const;
public class CompressUtilsTest {
void doTestGZIP(String src) {
try {
byte [] compr = CompressUtils.gzipStr(src);
float srcLen = src.getBytes(Const.ENCODING).length;
System.out.println("GZIP String byte length: " + srcLen + " compressed len: " + compr.length +
" ratio: " + (srcLen/compr.length));
assertEquals(src, CompressUtils.ungzipStr(compr));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
void doTestBZIP2(String src) {
try {
byte [] compr = CompressUtils.bzip2Str(src);
float srcLen = src.getBytes(Const.ENCODING).length;
System.out.println("BZIP2 String byte length: " + srcLen + " compressed len: " + compr.length +
" ratio: " + (srcLen/compr.length));
assertEquals(src, CompressUtils.unbzip2Str(compr));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
void doTestCompr(String src) {
try {
byte [] compr = CompressUtils.comprStr(src);
float srcLen = src.getBytes(Const.ENCODING).length;
System.out.println("COMPR String byte length: " + srcLen + " compressed len: " + compr.length +
" ratio: " + (srcLen/compr.length));
assertEquals(src, CompressUtils.decomprStr(compr));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
String mTestStr[] = {
"",
"This is a simple string.",
"This is a simple string. Но оно потребует использование utf8 (it will need to use utf8)",
"\"i'm no expert, but generally speaking, a finer-toothed saw will make cleaner cuts (and slower ones ;-) ).\n" +
" among hand tools, i'd try a hack saw; for handheld power tools, a fine-toothed circle saw or perhaps one \n\r" +
" of those \\\"super disks\\\"; and for table-based power tools, a band saw. either way, take your time.\n\n" +
"by the way, if you've got significant excess length, you can always practice a couple of different approaches " +
"before making the final cut.\"",
"manhattan project. the manhattan project was a research and development undertaking during world war ii that " +
"produced the first nuclear weapons. it was led by the united states with the support of the united kingdom and canada." +
" from 1942 to 1946, the project was under the direction of major general leslie groves of the u.s. army corps of engineers. " +
" nuclear physicist robert oppenheimer was the director of the los alamos laboratory that designed the actual bombs. " +
"the army component of the project was designated the\n"
};
@Test
public void test() {
for (String s : mTestStr) {
doTestGZIP(s);
doTestBZIP2(s);
doTestCompr(s);
}
}
}
| 37.294737 | 130 | 0.695738 |
ca33d62b4f57930b9a2ad4a35411fc517771d864 | 210 | package co.nstant.in.cbor.model;
public class HalfPrecisionFloat extends AbstractFloat {
public HalfPrecisionFloat(float value) {
super(SpecialType.IEEE_754_HALF_PRECISION_FLOAT, value);
}
}
| 21 | 64 | 0.757143 |
be506d00f37126c270493f39b10a7c73dfcde6ca | 3,509 | package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
/**
* @Title: WebMvcConfig
* @Package com/example/config/WebMvcConfig.java
* @Description:
* ** Spring提供了两种方法将资源的Java表述形式转换为发送给客户端的表述形式:
* 1. 内容协商(Content negotiation):选择一个视图,它能够将模型渲染为呈现给客户端的表述形式;
* 2. 消息转换器(Message conversion):通过一个消息转换器将控制器所返回的对象转换为呈现给客户端的表述形式
*
* 内容协商的两个步骤:
* 1.确定请求的媒体类型;
* 2.找到适合请求媒体类型的最佳视图。
* @author zhaozhiwei
* @date 2022/3/7 上午10:19
* @version V1.0
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.web")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
/**
* 解析流程:
* ContentNegotiatingViewResolver将会考虑到Accept头部信
* 息并使用它所请求的媒体类型,但是它会首先查看URL的文件扩展
* 名, 如.json .xml等
*
* 如果根据文件扩展名不能得到任何媒体类型的话,那就会考虑请求中
* 的Accept头部信息
* 如果没有Accept头部信息,并且扩展名也无法提供帮助的
* 话,ContentNegotiatingViewResolver将会使用“/”作为默认
* 的内容类型,这就意味着客户端必须要接收服务器发送的任何形式的
* 表述
*/
@Bean
public ViewResolver viewResolver(ContentNegotiationManager contentNegotiationManager){
final ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver();
viewResolver.setContentNegotiationManager(contentNegotiationManager);
return viewResolver;
}
/**
* @Description: 描述
* 配置ContentNegotiationManager的方法:
* 直接声明一个ContentNegotiationManager类型的bean;
* 通过ContentNegotiationManagerFactoryBean间接创建bean;
* 重载WebMvcConfigurerAdapter的 configureContentNegotiation()方法
*/
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
// 客户端没有明确的扩展名如.json,或者没有指定accept, 如application/json, 默认返回json
// configurer.defaultContentType(MediaType.APPLICATION_JSON);
configurer.defaultContentType(MediaType.TEXT_HTML);
}
/**
* @Description: 用bean的形式查找视图
*/
@Bean
public ViewResolver beanNameViewResolver(){
final BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver();
return beanNameViewResolver;
}
/**
* @Description:
* 如果返回为users则解析为json
* 添加@ResponseBody注解, 跳过正常的模型/视图流程,这样就能让Spring将方法返回的List<User>转换为响应体
*/
// @Bean
public View users(){
return new MappingJackson2JsonView();
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
// 要求DispatcherServlet将对静态资源的请求转发到Servlet容
// 器中默认的Servlet上,而不是使用DispatcherServlet本身来处理
// 此类请求
configurer.enable();
}
}
| 35.09 | 97 | 0.764605 |
163072629d1ae127770f141da9585283bf92ff8d | 5,577 | package mf;
/*Generated by MPS */
import junit.framework.TestCase;
import org.junit.Assert;
import junit.textui.TestRunner;
import junit.framework.TestSuite;
public class DateRangeTester extends TestCase {
/*package*/ MfDate myDec15 = new MfDate(1999, 12, 15);
/*package*/ MfDate myJan2 = new MfDate(2000, 1, 2);
/*package*/ MfDate myJan10 = new MfDate(2000, 1, 10);
/*package*/ MfDate myJan11 = new MfDate(2000, 1, 11);
/*package*/ MfDate myJan15 = new MfDate(2000, 1, 15);
/*package*/ MfDate myDec14 = new MfDate(1999, 12, 14);
/*package*/ MfDate myJan16 = new MfDate(2000, 1, 16);
/*package*/ MfDate myJan1 = new MfDate(2000, 1, 1);
/*package*/ MfDate myFeb2 = new MfDate(2000, 2, 2);
/*package*/ MfDate myFeb3 = new MfDate(2000, 2, 3);
/*package*/ MfDate myFeb8 = new MfDate(2000, 2, 8);
/*package*/ MfDate myFeb9 = new MfDate(2000, 2, 9);
/*package*/ DateRange myR15_15 = new DateRange(myDec15, myJan15);
/*package*/ DateRange myR15_16 = new DateRange(myJan15, myJan16);
/*package*/ DateRange myR16_2 = new DateRange(myJan16, myFeb2);
/*package*/ DateRange myR1_16 = new DateRange(myJan1, myJan16);
/*package*/ DateRange myR1_15 = new DateRange(myJan1, myJan15);
/*package*/ DateRange myR1_10 = new DateRange(myJan1, myJan10);
/*package*/ DateRange myR2_2 = new DateRange(myFeb2, myFeb2);
/*package*/ DateRange myF3_9 = new DateRange(myFeb3, myFeb9);
/*package*/ DateRange myJ1_f9 = new DateRange(myJan1, myFeb9);
/*package*/ DateRange myJ2_15 = new DateRange(myJan2, myJan15);
/*package*/ DateRange myF3_8 = new DateRange(myFeb3, myFeb8);
/*package*/ DateRange[] myComplete = {myR1_15, myR16_2, myF3_9};
/*package*/ DateRange[] myWithGap = {myR1_15, myF3_9};
/*package*/ DateRange[] myOverlap = {myR1_15, myR1_10, myR16_2, myF3_9};
public DateRangeTester(String arg) {
super(arg);
}
public void testBasic() {
Assert.assertTrue(myR15_15.includes(myJan1));
Assert.assertTrue(myR15_15.includes(myJan15));
Assert.assertTrue(myR15_15.includes(myDec15));
Assert.assertTrue(!(myR15_15.includes(myJan16)));
Assert.assertTrue(!(myR15_15.includes(myDec14)));
}
public void testOneDate() {
Assert.assertTrue(myR2_2.includes(myFeb2));
Assert.assertTrue(myR2_2.includes(myR2_2));
Assert.assertTrue(myR16_2.includes(myR2_2));
}
public void testEmpty() {
Assert.assertTrue(!(myR15_15.isEmpty()));
Assert.assertTrue(!(new DateRange(myDec15, myDec15).isEmpty()));
Assert.assertTrue(new DateRange(myDec15, myDec14).isEmpty());
Assert.assertTrue(DateRange.EMPTY.isEmpty());
}
public void testOverlaps() {
Assert.assertTrue(myR1_15.overlaps(myR1_16));
Assert.assertTrue(myR1_16.overlaps(myR1_15));
Assert.assertTrue(myR15_15.overlaps(myR15_15));
Assert.assertTrue(myR15_15.overlaps(myR1_15));
Assert.assertTrue(myR15_15.overlaps(myR15_16));
Assert.assertTrue(myR15_16.overlaps(myR15_15));
Assert.assertTrue(!(myR15_15.overlaps(myR16_2)));
Assert.assertTrue(!(myR16_2.overlaps(myR15_15)));
}
public void testIncludesRange() {
Assert.assertTrue(myR15_15.includes(myR15_15));
Assert.assertTrue(myR15_15.includes(myR1_15));
Assert.assertTrue(!(myR1_15.includes(myR15_15)));
Assert.assertTrue(!(myR1_16.includes(myR15_15)));
}
public void testEquals() {
Assert.assertEquals(myR1_15, new DateRange(myJan1, myJan15));
Assert.assertTrue(!(myR1_15.equals(myR1_16)));
Assert.assertTrue(!(myR15_15.equals(myR15_16)));
}
public void testCompare() {
Assert.assertTrue(myDec15.compareTo(myJan1) < 0);
Assert.assertTrue(myR15_15.compareTo(myR1_15) < 0);
Assert.assertTrue(myR1_15.compareTo(myR1_16) < 0);
Assert.assertTrue(myR1_15.compareTo(myR1_15) == 0);
Assert.assertTrue(myR1_16.compareTo(myR1_15) > 0);
Assert.assertTrue(myR15_15.compareTo(myR1_10) < 0);
}
public void testGap() {
DateRange expected = new DateRange(myJan11, myJan15);
Assert.assertEquals(expected, myR1_10.gap(myR16_2));
Assert.assertEquals(expected, myR16_2.gap(myR1_10));
Assert.assertTrue(myR15_15.gap(myR1_10).isEmpty());
Assert.assertTrue(myR1_15.gap(myR15_16).isEmpty());
Assert.assertTrue(myR1_15.gap(myR16_2).isEmpty());
}
public void testAbuts() {
Assert.assertTrue(myR1_15.abuts(myR16_2));
Assert.assertTrue(myR16_2.abuts(myR1_15));
Assert.assertTrue(!(myR1_15.abuts(myR15_15)));
Assert.assertTrue(!(myR1_10.abuts(myR15_16)));
}
public void testCombine() {
Assert.assertEquals(myJ1_f9, DateRange.combination(myComplete));
}
public void testContiguous() {
Assert.assertTrue(DateRange.isContiguous(myComplete));
Assert.assertTrue(!(DateRange.isContiguous(myWithGap)));
Assert.assertTrue(!(DateRange.isContiguous(myOverlap)));
}
public void testPartition() {
Assert.assertTrue(myJ1_f9.partitionedBy(myComplete));
Assert.assertTrue(!(myJ1_f9.partitionedBy(myWithGap)));
Assert.assertTrue(!(myJ1_f9.partitionedBy(myOverlap)));
DateRange[] off_end = {myR15_15, myR16_2, myF3_9};
Assert.assertTrue(!(myJ1_f9.partitionedBy(off_end)));
DateRange[] missingStart = {myJ2_15, myR16_2, myF3_9};
Assert.assertTrue(!(myJ1_f9.partitionedBy(missingStart)));
DateRange[] missingEnd = {myR1_15, myR16_2, myF3_8};
Assert.assertTrue(!(myJ1_f9.partitionedBy(missingEnd)));
}
public void testStarting() {
DateRange dr = DateRange.startingOn(myDec15);
Assert.assertTrue(dr.includes(myJan2));
}
public static void main(String[] args) {
TestRunner.run(new TestSuite(DateRangeTester.class));
}
}
| 43.570313 | 74 | 0.715259 |
74c919d4e355d3e3c147af043b5216cc299a46fc | 1,943 | /* 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.activiti.test.cactus;
import java.io.File;
import java.io.PrintWriter;
/**
* @author Tom Baeyens
*/
public class ListTests {
public static void main(String[] args) {
try {
File rootPath = new File("../activiti-engine/src/test/java");
System.out.println("Listing tests in dir "+rootPath.getCanonicalPath()+" in target/classes/activiti.cactus.tests.txt");
PrintWriter writer = new PrintWriter("target/classes/activiti.cactus.tests.txt");
try {
scan(rootPath, null, writer);
} finally {
writer.flush();
writer.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void scan(File directory, String packageName, PrintWriter writer) {
for (File file: directory.listFiles()) {
if (file.isFile()) {
String fileName = file.getName();
if (fileName.endsWith("Test.java")) {
String className = packageName+"."+fileName.substring(0, fileName.length()-5);
writer.println(className);
}
} else if (file.isDirectory()) {
String fileName = file.getName();
String newPackageName = (packageName==null ? fileName : packageName+"."+fileName);
if (!newPackageName.startsWith("org.activiti.standalone")) {
scan(file, newPackageName, writer);
}
}
}
}
}
| 31.33871 | 125 | 0.65054 |
293c7a5ac59418d498f735616e7999b662d9c31e | 3,042 | package com.pushtorefresh.storio.contentresolver.operations.put;
import android.content.ContentValues;
import android.support.annotation.NonNull;
import com.pushtorefresh.storio.contentresolver.StorIOContentResolver;
import com.pushtorefresh.storio.operations.PreparedOperation;
import java.util.Collection;
/**
* Represents an Operation for {@link StorIOContentResolver} which performs insert or update data
* in {@link android.content.ContentProvider}.
*
*/
public abstract class PreparedPut<Result> implements PreparedOperation<Result> {
@NonNull
protected final StorIOContentResolver storIOContentResolver;
protected PreparedPut(@NonNull StorIOContentResolver storIOContentResolver) {
this.storIOContentResolver = storIOContentResolver;
}
/**
* Builder for {@link PreparedPut}.
*/
public static final class Builder {
@NonNull
private final StorIOContentResolver storIOContentResolver;
public Builder(@NonNull StorIOContentResolver storIOContentResolver) {
this.storIOContentResolver = storIOContentResolver;
}
/**
* Prepares Put Operation that should put one object.
*
* @param object object to put.
* @param <T> type of object.
* @return builder for {@link PreparedPutObject}.
*/
@NonNull
public <T> PreparedPutObject.Builder<T> object(@NonNull T object) {
return new PreparedPutObject.Builder<T>(storIOContentResolver, object);
}
/**
* Prepares Put Operation that should put multiple objects.
*
* @param objects objects to put.
* @param <T> type of objects.
* @return builder for {@link PreparedPutCollectionOfObjects}.
*/
@NonNull
public <T> PreparedPutCollectionOfObjects.Builder<T> objects(@NonNull Collection<T> objects) {
return new PreparedPutCollectionOfObjects.Builder<T>(storIOContentResolver, objects);
}
/**
* Prepares Put Operation that should put one instance of {@link ContentValues}.
*
* @param contentValues non-null content values to put.
* @return builder for {@link PreparedPutContentValues}.
*/
@NonNull
public PreparedPutContentValues.Builder contentValues(@NonNull ContentValues contentValues) {
return new PreparedPutContentValues.Builder(storIOContentResolver, contentValues);
}
/**
* Prepares Put Operation that should put several instances of {@link ContentValues}.
*
* @param contentValues non-null collection of {@link ContentValues}.
* @return builder for {@link PreparedPutContentValuesIterable}.
*/
@NonNull
public PreparedPutContentValuesIterable.Builder contentValues(@NonNull Iterable<ContentValues> contentValues) {
return new PreparedPutContentValuesIterable.Builder(storIOContentResolver, contentValues);
}
}
}
| 36.214286 | 119 | 0.680473 |
df7345f62f038137432b495e7a58716d0cc3f3f6 | 6,217 | package com.jinhx.blog.controller.social;
import com.jinhx.blog.common.aop.annotation.Log;
import com.jinhx.blog.common.constants.RedisKeyConstants;
import com.jinhx.blog.common.enums.ResponseEnums;
import com.jinhx.blog.common.exception.MyException;
import com.jinhx.blog.common.util.MyAssert;
import com.jinhx.blog.common.validator.ValidatorUtils;
import com.jinhx.blog.common.validator.group.InsertGroup;
import com.jinhx.blog.entity.base.PageData;
import com.jinhx.blog.entity.base.Response;
import com.jinhx.blog.entity.social.FriendLink;
import com.jinhx.blog.entity.social.vo.HomeFriendLinkInfoVO;
import com.jinhx.blog.service.social.FriendLinkService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* FriendLinkController
*
* @author jinhx
* @since 2019-02-14
*/
@RestController
@CacheConfig(cacheNames = RedisKeyConstants.FRIENDLINKS)
public class FriendLinkController {
@Autowired
private FriendLinkService friendLinkService;
/**
* 查询首页信息
*
* @return 首页信息
*/
@GetMapping("/manage/friendlink/homeinfo")
@RequiresPermissions("friendlink:list")
public Response<HomeFriendLinkInfoVO> selectHommeFriendLinkInfoVO() {
return Response.success(friendLinkService.selectHommeFriendLinkInfoVO());
}
/**
* 分页查询友链列表
*
* @param page page
* @param limit limit
* @param title title
* @return 友链列表
*/
@GetMapping("/manage/friendlinks/page")
@RequiresPermissions("friendlink:list")
public Response<PageData<FriendLink>> selectFriendLinksByPage(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit,
@RequestParam(value = "title", required = false) String title){
return Response.success(friendLinkService.selectFriendLinksByPage(page, limit, title));
}
/**
* 根据friendLinkId查询友链
*
* @param friendLinkId friendLinkId
* @return 友链
*/
@GetMapping("/manage/friendlink/{friendLinkId}")
@RequiresPermissions("friendlink:detail")
public Response<FriendLink> selectFriendLinkById(@PathVariable Long friendLinkId){
return Response.success(friendLinkService.selectFriendLinkById(friendLinkId));
}
/**
* 新增友链
*
* @param friendLink friendLink
* @return 新增结果
*/
@PostMapping("/manage/friendlink")
@RequiresPermissions("friendlink:insert")
@CacheEvict(allEntries = true)
public Response<Void> insertFriendLink(@RequestBody FriendLink friendLink){
ValidatorUtils.validateEntity(friendLink, InsertGroup.class);
friendLinkService.insertFriendLink(friendLink);
return Response.success();
}
/**
* 发布友链
*
* @param friendLink 友链信息
* @return 更新结果
*/
@PutMapping("/manage/friendlink/publish")
@RequiresPermissions("friendlink:update")
@CacheEvict(allEntries = true)
public Response<Void> publishFriendLink(@RequestBody FriendLink friendLink){
MyAssert.notNull(friendLink, "friendLinkId不能为空");
MyAssert.notNull(friendLink.getFriendLinkId(), "friendLinkId不能为空");
friendLink.setPublish(FriendLink.PublishEnum.YES.getCode());
friendLinkService.updateFriendLinkStatus(friendLink);
return Response.success();
}
/**
* 下架友链
*
* @param friendLink 友链信息
* @return 更新结果
*/
@PutMapping("/manage/friendlink/undercarriage")
@RequiresPermissions("friendlink:update")
@CacheEvict(allEntries = true)
public Response<Void> undercarriageFriendLink(@RequestBody FriendLink friendLink){
MyAssert.notNull(friendLink, "friendLinkId不能为空");
MyAssert.notNull(friendLink.getFriendLinkId(), "friendLinkId不能为空");
friendLink.setPublish(FriendLink.PublishEnum.NO.getCode());
friendLinkService.updateFriendLinkStatus(friendLink);
return Response.success();
}
/**
* 根据friendLinkId更新友链
*
* @param friendLink friendLink
* @return 更新结果
*/
@PutMapping("/manage/friendlink")
@RequiresPermissions("friendlink:update")
@CacheEvict(allEntries = true)
public Response<Void> updateFriendLinkById(@RequestBody FriendLink friendLink){
friendLinkService.updateFriendLinkById(friendLink);
return Response.success();
}
/**
* 批量根据friendLinkId删除友链
*
* @param friendLinkIds friendLinkIds
* @return 删除结果
*/
@DeleteMapping("/manage/friendlinks")
@RequiresPermissions("friendlink:delete")
@CacheEvict(allEntries = true)
public Response<Void> deleteFriendLinksById(@RequestBody List<Long> friendLinkIds){
MyAssert.sizeBetween(friendLinkIds, 1, 100, "friendLinkIds");
friendLinkService.deleteFriendLinksById(friendLinkIds);
return Response.success();
}
/********************** portal ********************************/
/**
* 查询已发布的友链列表
*
* @return 友链列表
*/
@RequestMapping("/listfriendlinks")
@Log(module = 6)
public Response<List<FriendLink>> selectPortalFriendLinks() {
return Response.success(friendLinkService.selectPortalFriendLinks());
}
/**
* 申请友链
*
* @param friendLink friendLink
* @return 申请结果
*/
@PostMapping("/friendlink")
@Log(module = 6)
public Response<Void> applyFriendLink(@RequestBody FriendLink friendLink){
ValidatorUtils.validateEntity(friendLink, InsertGroup.class);
if(!friendLink.getUrl().startsWith("https://") && !friendLink.getUrl().startsWith("http://")){
throw new MyException(ResponseEnums.PARAM_ERROR.getCode(), "网址格式不对");
}
if(!friendLink.getAvatar().startsWith("https://") && !friendLink.getAvatar().startsWith("http://")){
throw new MyException(ResponseEnums.PARAM_ERROR.getCode(), "头像格式不对");
}
friendLinkService.applyFriendLink(friendLink);
return Response.success();
}
}
| 33.069149 | 139 | 0.687148 |
f12420391d629ff7e9868ae07b940b2ff5ad1a37 | 1,597 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.security.implementation;
import com.azure.resourcemanager.security.fluent.models.ServerVulnerabilityAssessmentInner;
import com.azure.resourcemanager.security.models.ServerVulnerabilityAssessment;
import com.azure.resourcemanager.security.models.ServerVulnerabilityAssessmentPropertiesProvisioningState;
public final class ServerVulnerabilityAssessmentImpl implements ServerVulnerabilityAssessment {
private ServerVulnerabilityAssessmentInner innerObject;
private final com.azure.resourcemanager.security.SecurityManager serviceManager;
ServerVulnerabilityAssessmentImpl(
ServerVulnerabilityAssessmentInner innerObject,
com.azure.resourcemanager.security.SecurityManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
}
public String id() {
return this.innerModel().id();
}
public String name() {
return this.innerModel().name();
}
public String type() {
return this.innerModel().type();
}
public ServerVulnerabilityAssessmentPropertiesProvisioningState provisioningState() {
return this.innerModel().provisioningState();
}
public ServerVulnerabilityAssessmentInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.security.SecurityManager manager() {
return this.serviceManager;
}
}
| 33.978723 | 106 | 0.763932 |
045b2a63eed48b0cad7522fd021c2371c316ceba | 11,689 | /*
* $Id$
*/
/*
Copyright (c) 2000-2016 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin.highwire.elife;
import java.net.MalformedURLException;
import java.util.Properties;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.plugin.ArchivalUnit.ConfigurationException;
import org.lockss.plugin.definable.*;
import org.lockss.test.*;
import org.lockss.util.ListUtil;
import org.lockss.util.urlconn.CacheException;
import org.lockss.util.urlconn.HttpResultMap;
public class TestClockssELifeDrupalPlugin extends LockssTestCase {
static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey();
static final String VOL_KEY = ConfigParamDescr.VOLUME_NAME.getKey();
private MockLockssDaemon theDaemon;
private DefinablePlugin plugin;
public TestClockssELifeDrupalPlugin(String msg) {
super(msg);
}
@Override
public void setUp() throws Exception {
super.setUp();
setUpDiskSpace();
theDaemon = getMockLockssDaemon();
plugin = new DefinablePlugin();
plugin.initPlugin(getMockLockssDaemon(),
"org.lockss.plugin.highwire.elife.ClockssELifeDrupalPlugin");
}
public void testGetAuNullConfig()
throws ArchivalUnit.ConfigurationException {
try {
plugin.configureAu(null, null);
fail("Didn't throw ArchivalUnit.ConfigurationException");
} catch (ArchivalUnit.ConfigurationException e) {
}
}
public void testCreateAu() throws ConfigurationException {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, "http://www.example.com/");
props.setProperty(VOL_KEY, "32");
makeAuFromProps(props);
}
private DefinableArchivalUnit makeAuFromProps(Properties props)
throws ArchivalUnit.ConfigurationException {
Configuration config = ConfigurationUtil.fromProps(props);
return (DefinableArchivalUnit)plugin.configureAu(config, null);
}
public void testGetAuConstructsProperAu()
throws ArchivalUnit.ConfigurationException, MalformedURLException {
Properties props = new Properties();
props.setProperty(VOL_KEY, "2013");
props.setProperty(BASE_URL_KEY, "http://www.example.com/");
String[] starturl = new String[]{
"http://www.example.com/clockss-manifest/2013.html",
"http://www.example.com/clockss-manifest/elife_2013.html",
};
DefinableArchivalUnit au = makeAuFromProps(props);
assertEquals("eLife Sciences Plugin (retired site for CLOCKSS), Base URL http://www.example.com/, Volume 2013",
au.getName());
assertEquals(ListUtil.fromArray(starturl), au.getStartUrls());
}
public void testGetPluginId() {
assertEquals("org.lockss.plugin.highwire.elife.ClockssELifeDrupalPlugin",
plugin.getPluginId());
}
public void testGetAuConfigProperties() {
assertEquals(ListUtil.list(ConfigParamDescr.BASE_URL,
ConfigParamDescr.VOLUME_NAME),
plugin.getLocalAuConfigDescrs());
}
public void testHandles500Result() throws Exception {
Properties props = new Properties();
props.setProperty(VOL_KEY, "2013");
props.setProperty(BASE_URL_KEY, "http://www.example.com/");
String starturl =
"http://www.example.com/lockss-manifest/elife_2013.html";
DefinableArchivalUnit au = makeAuFromProps(props);
MockLockssUrlConnection conn = new MockLockssUrlConnection();
conn.setURL("http://uuu17/");
CacheException exc =
((HttpResultMap)plugin.getCacheResultMap()).mapException(au, conn,
500, "foo");
assertClass(CacheException.RetryDeadLinkException.class, exc);
conn.setURL(starturl);
exc = ((HttpResultMap)plugin.getCacheResultMap()).mapException(au, conn,
500, "foo");
assertClass(CacheException.RetrySameUrlException.class, exc);
}
public void testHandles403Result() throws Exception {
Properties props = new Properties();
props.setProperty(VOL_KEY, "2013");
props.setProperty(BASE_URL_KEY, "http://www.example.com/");
String starturl =
"http://www.example.com/lockss-manifest/elife_2013.html";
DefinableArchivalUnit au = makeAuFromProps(props);
MockLockssUrlConnection conn = new MockLockssUrlConnection();
conn.setURL("http://uuu17/download/somestuff");
CacheException exc =
((HttpResultMap)plugin.getCacheResultMap()).mapException(au, conn,
403, "foo");
assertClass(CacheException.RetryDeadLinkException.class, exc);
conn.setURL(starturl);
exc = ((HttpResultMap)plugin.getCacheResultMap()).mapException(au, conn,
403, "foo");
assertClass(CacheException.RetrySameUrlException.class, exc);
}
// Test the crawl rules for eLife
public void testShouldCacheProperPages() throws Exception {
String ROOT_URL = "http://elifesciences.org/";
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, ROOT_URL);
props.setProperty(VOL_KEY, "2013");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
theDaemon.getLockssRepository(au);
// Test for pages that should get crawled or not
// permission page/start url
shouldCacheTest(ROOT_URL + "lockss-manifest/2013.html", false, au);
shouldCacheTest(ROOT_URL + "clockss-manifest/elife_2013.html", true, au);
// crawl_rule allows following
shouldCacheTest(ROOT_URL + "clockss-manifest/vol_2013_manifest.html", true, au);
shouldCacheTest(ROOT_URL + "manifest/year=2013", false, au);
// toc page for an issue, there is no issue
// shouldCacheTest(ROOT_URL + "content/1", false, au); // changed crawl rule as there are some volume only tocs (iwa) so this test is true
// article files
shouldCacheTest(ROOT_URL + "content/1/e00002", true, au);
shouldCacheTest(ROOT_URL.replace("http:", "https:") + "content/1/e00002", true, au);
shouldCacheTest(ROOT_URL + "content/1/e00003/article-data", false, au);
shouldCacheTest(ROOT_URL + "content/1/e00003/article-info", false, au);
shouldCacheTest(ROOT_URL + "content/1/e00003.abstract", false, au);
shouldCacheTest(ROOT_URL + "content/1/e00003.full.pdf", true, au);
shouldCacheTest(ROOT_URL + "content/1/2/e00003.full.pdf", true, au);
shouldCacheTest(ROOT_URL + "content/elife/1/e00003/F1.large.jpg", false, au);
shouldCacheTest(ROOT_URL + "content/elife/1/e00003/F3/F4.large.jpg", false, au);
shouldCacheTest(ROOT_URL + "content/elife/1/e00003.full.pdf", true, au);
shouldCacheTest(ROOT_URL + "highwire/citation/12/ris", false, au);
shouldCacheTest(ROOT_URL + "highwire/citation/9/1/ris", false, au);
shouldCacheTest(ROOT_URL + "highwire/markup/113/expansion", false, au);
// This now returns true in error; however, the plugin is deprecated;
// and it's possible that we should have collected these pages;
// and it's possible that the urls like these are crawl filtered out anyway;
// moving on...
// shouldCacheTest(ROOT_URL + "content/1/e00011/DC5", false, au);
shouldCacheTest(ROOT_URL + "sites/all/libraries/modernizr/modernizr.min.js", false, au);
shouldCacheTest(ROOT_URL + "sites/default/files/js/js_0j8_f76rvZ212f4rg.js", false, au);
shouldCacheTest(ROOT_URL + "sites/default/themes/elife/font/fontawesome-webfont.eot", false, au);
shouldCacheTest(ROOT_URL + "sites/default/themes/font/fontawesome-webfont.eot", false, au);
shouldCacheTest(ROOT_URL + "content/1/e00003/article-metrics", false, au);
shouldCacheTest(ROOT_URL + "panels_ajax_tab/jnl_elife_article_article/node:8375/0", false, au);
shouldCacheTest(ROOT_URL + "panels_ajax_tab/jnl_elife_article_figdata/node:8375/1", false, au);
shouldCacheTest(ROOT_URL + "panels_ajax_tab/jnl_elife_article_metrics/node:8375/1", false, au);
shouldCacheTest(ROOT_URL + "panels_ajax_tab/jnl_elife_article_author/node:8375/1", false, au);
shouldCacheTest(ROOT_URL + "elife/download-pdf/content/1/e00352/n/Nerve%20diversity%20in%20skin.pdf/1", true, au);
shouldCacheTest(ROOT_URL + "elife/download-suppl/250/supplementary-file-1.media-1.pdf/0/1", true, au);
shouldCacheTest(ROOT_URL + "elife/download-suppl/267/supplementary-file-1.media-1.xls/0/1", true, au);
shouldCacheTest(ROOT_URL + "elife/download-suppl/293/supplementary-file-1.media-4.xlsx/0/1", true, au);
shouldCacheTest(ROOT_URL + "elife/download-suppl/297/figure-10—source-data-1.media-3.xlsx/0/1", true, au);
shouldCacheTest(ROOT_URL + "elife/download-video/http%253A%252F%252Fstatic-movie-usa.glencoesoftware.com%252Fmp4%252F10.7554%252F6873ae4599bf%252Felife00007v001.mp4", true, au);
shouldCacheTest(ROOT_URL + "elife/download-suppl/23743/source-code-1.media-5.pl/0/1", true, au);
shouldCacheTest(ROOT_URL + "content/elife/suppl/2014/04/23/eLife.02130.DC1/elife02130_Supplemental_files.zip", true, au);
shouldCacheTest("http://cdn-site.elifesciences.org/content/elife/1/e00003/F1.medium.gif", false, au);
shouldCacheTest("http://cdn-site.elifesciences.org/content/elife/1/e00003/F3/F4.small.gif", false, au);
shouldCacheTest("http://cdn-site.elifesciences.org/misc/draggable.png", false, au);
shouldCacheTest("http://cdn-site.elifesciences.org/sites/all/libraries/cluetip/images/arrowdown.gif", false, au);
shouldCacheTest("http://cdn-site.elifesciences.org/sites/default/files/cdn/css/http/css_2iejb0.css", false, au);
shouldCacheTest("http://cdn-site.elifesciences.org/sites/default/themes/elife/css/PIE/PIE.htc", false, au);
shouldCacheTest("http://cdn-site.elifesciences.org/sites/default/themes/elife/font/fontawesome-webfont.woff", false, au);
shouldCacheTest("http://cdn.elifesciences.org/elife-articles/00003/figures-pdf/elife00003-figures.pdf", false, au);
shouldCacheTest("http://cdn.mathjax.org/mathjax/latest/MathJax.js", false, au);
shouldCacheTest("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", false, au);
shouldCacheTest("", false, au);
// should not get crawled - LOCKSS
shouldCacheTest("http://lockss.stanford.edu", false, au);
}
private void shouldCacheTest(String url, boolean shouldCache, ArchivalUnit au) {
log.info ("shouldCacheTest url: " + url);
assertEquals(shouldCache, au.shouldBeCached(url));
}
} | 46.943775 | 181 | 0.732655 |
7ece9e38444ffe30ae3f44df2df8e3d96d2513df | 4,662 | package rs.nicktrave.statsd.loadtest;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import rs.nicktrave.statsd.client.Collector;
import rs.nicktrave.statsd.client.StatsdClient;
import rs.nicktrave.statsd.client.Transport;
import rs.nicktrave.statsd.client.UnbufferedCollector;
import rs.nicktrave.statsd.client.netty.NettyUdpTransport;
import rs.nicktrave.statsd.common.Counter;
import rs.nicktrave.statsd.common.Metric;
/**
* A tool used to generate {@link Metric}s which are sent to a server.
*/
// TODO(nickt): Proper logging
public class LoadGenerator {
private static final class Args {
@Parameter(
names = "-serverHostname",
description ="The hostname of the server the client will connect to")
private String serverHostname = "localhost";
@Parameter(
names = "-port",
description ="The port of the server the client will connect to")
private int serverPort = 8125;
@Parameter(
names = "-numClients",
description = "The number of distinct clients that will be used to send metrics")
private int numClients = 1;
@Parameter(
names = "-batchSize",
description = "The number of metrics to send per client in each batch")
private int batchSize = 1;
@Parameter(
names = "-iterations",
description = "The number of iterations through the send loop")
private int iterations = 5;
@Parameter(
names = "-delay",
description = "The amount of time (in milliseconds) between each send loop run")
private int delay = 1_000;
@Parameter(names = "--help", help = true)
private boolean help;
}
private void run(Args args) throws InterruptedException, IOException {
System.out.println("Starting server ...");
// Generate the collection of clients
List<StatsdClient> clients = new ArrayList<>();
for (int i = 0; i < args.numClients; i++) {
clients.add(newClient(args.serverHostname, args.serverPort));
}
AtomicInteger count = new AtomicInteger();
AtomicBoolean isFinished = new AtomicBoolean(false);
CountDownLatch doneLatch = new CountDownLatch(1);
Metric[] metrics = generateMetrics(args.batchSize);
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.scheduleWithFixedDelay(() -> {
if (isFinished.get()) {
return;
}
if (count.getAndIncrement() == args.iterations) {
isFinished.set(true);
doneLatch.countDown();
return;
}
System.out.println("Iteration " + count.get() + " of " + args.iterations);
clients.forEach(c -> c.send(metrics));
}, 1_000, args.delay, TimeUnit.MILLISECONDS);
System.out.println("Awaiting shutdown ...");
doneLatch.await();
System.out.println("Shutting down ...");
service.shutdown();
for (StatsdClient client : clients) {
client.close();
}
}
public static void main(String ...args) throws IOException, InterruptedException {
Args cliArgs = new Args();
JCommander jCommander = JCommander.newBuilder()
.addObject(cliArgs)
.build();
jCommander.parse(args);
if (cliArgs.help) {
jCommander.usage();
return;
}
System.out.println("Starting load test:");
System.out.println("\tServer: " + cliArgs.serverHostname + ":" + cliArgs.serverPort);
System.out.println("\tClients: " + cliArgs.numClients);
System.out.println("\tBatch size: " + cliArgs.batchSize);
System.out.println("\tIterations: " + cliArgs.iterations);
System.out.println("\tDelay: " + cliArgs.delay + "ms");
new LoadGenerator().run(cliArgs);
}
private static StatsdClient newClient(String hostname, int port) throws InterruptedException {
Transport t = new NettyUdpTransport(new InetSocketAddress(hostname, port));
Collector c = new UnbufferedCollector(t);
return StatsdClient.newBuilder()
.withTransport(t)
.withCollector(c)
.build();
}
private static Metric[] generateMetrics(int size) {
Metric[] metrics = new Metric[size];
for (int i = 0; i < size; i++) {
metrics[i] = new Counter("foo", 1);
}
return metrics;
}
}
| 31.931507 | 96 | 0.67589 |
d6d4b905b924ff7f6cf407ed2b712420a6386439 | 3,406 | package org.revenj.server.servlet;
import org.junit.Assert;
import org.junit.Test;
import org.revenj.TreePath;
import org.revenj.Utils;
import org.w3c.dom.Element;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
public class JsonTest {
@Test
public void dateFormat() throws IOException {
JacksonSerialization jackson = new JacksonSerialization(null, Optional.empty());
String value = jackson.serialize(LocalDate.of(2015, 9, 26));
Assert.assertEquals("\"2015-09-26\"", value);
}
@Test
public void timestampFormat() throws IOException {
JacksonSerialization jackson = new JacksonSerialization(null, Optional.empty());
String value = jackson.serialize(OffsetDateTime.of(LocalDateTime.of(2015, 9, 26, 1, 2, 3), ZoneOffset.ofHours(2)));
Assert.assertEquals("\"2015-09-26T01:02:03+02:00\"", value);
}
@Test
public void jacksonPoint() throws IOException {
JacksonSerialization jackson = new JacksonSerialization(null, Optional.empty());
java.awt.Point value = jackson.deserialize("{}", java.awt.Point.class);
Assert.assertEquals(0, value.x);
Assert.assertEquals(0, value.y);
value = jackson.deserialize("{\"x\":1,\"y\":2}", java.awt.Point.class);
Assert.assertEquals(1, value.x);
Assert.assertEquals(2, value.y);
value = jackson.deserialize("\"3,4\"", java.awt.Point.class);
Assert.assertEquals(3, value.x);
Assert.assertEquals(4, value.y);
}
@Test
public void jacksonXml() throws IOException {
JacksonSerialization jackson = new JacksonSerialization(null, Optional.empty());
Element value = jackson.deserialize("{\"root\":null}", Element.class);
Assert.assertEquals("root", value.getNodeName());
value = jackson.deserialize("\"<root/>\"", Element.class);
Assert.assertEquals("root", value.getNodeName());
}
static class WithXml {
public String URI;
public List<Element> xmls;
}
@Test
public void xmlJacksonClass() throws IOException {
final JacksonSerialization json = new JacksonSerialization(null, Optional.empty());
byte[] bytes = "[null,{\"document\":null},{\"TextElement\":\"some text & \"},{\"ElementWithCData\":\"\"},{\"AtributedElement\":{\"@foo\":\"bar\",\"@qwe\":\"poi\"}},{\"NestedTextElement\":{\"FirstNest\":{\"SecondNest\":\"bird\"}}}]".getBytes();
List<Element> xmls = (List<Element>) json.deserialize(Utils.makeGenericType(ArrayList.class, Element.class), bytes, bytes.length);
WithXml instance = new WithXml();
instance.URI = "abc";
instance.xmls = xmls;
String res = json.serialize(instance);
WithXml deser = (WithXml) json.deserialize(WithXml.class, res.getBytes(), res.length());
assertEquals(6, deser.xmls.size());
}
@Test
public void treePath() throws IOException {
final JacksonSerialization json = new JacksonSerialization(null, Optional.empty());
List<TreePath> paths = Arrays.asList(TreePath.create("abc.def"), null, TreePath.create("a.b"), TreePath.EMPTY);
String res = json.serialize(paths);
List<TreePath> deser = (List<TreePath>) json.deserialize(Utils.makeGenericType(ArrayList.class, TreePath.class), res);
assertEquals(deser, paths);
}
}
| 39.149425 | 246 | 0.707868 |
f4f4349f9f75a2d51aeedcdbacc347adcf6509be | 319 | package io.api.etherscan.model.utility;
import io.api.etherscan.model.UncleBlock;
/**
* ! NO DESCRIPTION !
*
* @author GoodforGod
* @since 30.10.2018
*/
public class UncleBlockResponseTO extends BaseResponseTO {
private UncleBlock result;
public UncleBlock getResult() {
return result;
}
}
| 16.789474 | 58 | 0.695925 |
8538e39c6c8844f7bc78523d67e83b7e373c4a42 | 3,348 | /*
* #%L
* BroadleafCommerce Integration
* %%
* Copyright (C) 2009 - 2016 Broadleaf Commerce
* %%
* Licensed under the Broadleaf Fair Use License Agreement, Version 1.0
* (the "Fair Use License" located at http://license.broadleafcommerce.org/fair_use_license-1.0.txt)
* unless the restrictions on use therein are violated and require payment to Broadleaf in which case
* the Broadleaf End User License Agreement (EULA), Version 1.1
* (the "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt)
* shall apply.
*
* Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the "Custom License")
* between you and Broadleaf Commerce. You may not use this file except in compliance with the applicable license.
* #L%
*/
package org.broadleafcommerce.profile.web.core.service;
import org.broadleafcommerce.common.id.domain.IdGeneration;
import org.broadleafcommerce.common.id.domain.IdGenerationImpl;
import org.broadleafcommerce.common.id.service.IdGenerationService;
import org.broadleafcommerce.test.TestNGSiteIntegrationSetup;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class IdGenerationTest extends TestNGSiteIntegrationSetup {
@Resource
private IdGenerationService idGenerationService;
@PersistenceContext(unitName = "blPU")
protected EntityManager em;
List<Long> userIds = new ArrayList<>();
List<String> userNames = new ArrayList<>();
@Test(groups = "createId")
@Rollback(false)
@Transactional
public void createId() {
IdGeneration idGeneration = new IdGenerationImpl();
idGeneration.setType("IdGenerationTest");
idGeneration.setBatchStart(1L);
idGeneration.setBatchSize(10L);
em.persist(idGeneration);
}
@Test(groups = "findIds", dependsOnGroups = "createId")
@Rollback(true)
public void findIds() {
for (int i = 1; i < 101; i++) {
Long id = idGenerationService.findNextId("IdGenerationTest");
assert id == i;
}
}
@Test(groups = "createIdForBeginEndSequence")
@Rollback(false)
@Transactional
public void createIdForBeginEndSequence() {
IdGeneration idGeneration = new IdGenerationImpl();
idGeneration.setType("IdGenerationBeginEndTest");
idGeneration.setBegin(1L);
idGeneration.setEnd(10L);
idGeneration.setBatchStart(1L);
idGeneration.setBatchSize(3L);
em.persist(idGeneration);
}
@Test(groups = "findIdsForBeginEndSequence", dependsOnGroups = "createIdForBeginEndSequence")
@Rollback(true)
public void findIdsForBeginEndSequence() {
for (int i = 1; i < 101; i++) {
Long id = idGenerationService.findNextId("IdGenerationBeginEndTest");
int expected = i % 10;
if (expected == 0) {
expected = 10;
}
//System.out.println("jbtest: i=" + i + ", id=" + id + ", expected=" + expected);
assert id == expected;
}
}
}
| 35.617021 | 115 | 0.698029 |
d5534257a7981a08edef9392b8f0eeb817af71d4 | 480 | /**
* *****************************************************************************
*
* <p>Copyright FUJITSU LIMITED 2019
*
* <p>Creation Date: 24.09.2019
*
* <p>*****************************************************************************
*/
package org.oscm.identity.model;
import lombok.Data;
/** Simple data transfer object representing group information */
@Data
public class GroupInfo {
private String id;
private String name;
private String description;
}
| 21.818182 | 83 | 0.46875 |
fbf0e43250dd628064591e8b12b81f94340833a6 | 964 | package ee.tuleva.onboarding.audit;
import ee.tuleva.onboarding.auth.principal.Person;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
@RequiredArgsConstructor
public class AuditServiceMonitor {
private final AuditEventPublisher auditEventPublisher;
@Before(
"execution(* ee.tuleva.onboarding.account.AccountStatementService.getAccountStatement(..)) && args(person)")
public void logServiceAccess(Person person) {
auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_ACCOUNT_STATEMENT);
}
@Before(
"execution(* ee.tuleva.onboarding.comparisons.overview.AccountOverviewProvider.getAccountOverview(..)) && args(person, ..)")
public void logCashFlowAccess(Person person) {
auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_CASH_FLOWS);
}
}
| 34.428571 | 130 | 0.798755 |
b3befb531fafa0c766e6346e693b75439e5fc9b3 | 1,019 | class Solution
{
static void breakLine()
{
System.out.print("\n---------------------------------\n");
}
static int MAX = 10;
static int arr[] = new int[MAX], no;
static void nQueens(int k, int n)
{
for (int i = 1; i <= n; i++)
{
if (canPlace(k, i))
{
arr[k] = i;
if (k == n)
{
display(n);
}
else
{
nQueens(k + 1, n);
}
}
}
}
static boolean canPlace(int k, int i)
{
for (int j = 1; j <= k - 1; j++)
{
if (arr[j] == i ||
(Math.abs(arr[j] - i) == Math.abs(j - k)))
{
return false;
}
}
return true;
}
static void display(int n)
{
breakLine();
System.out.print("Arrangement No. " + ++no);
breakLine();
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (arr[i] != j)
{
System.out.print("\t_");
}
else
{
System.out.print("\tQ");
}
}
System.out.println("");
}
breakLine();
}
public static void main(String[] args)
{
int n = 4;
nQueens(1, n);
}
}
| 14.152778 | 60 | 0.447498 |
af2c5aed93da1468051f272c67d30dde404b5c14 | 7,378 | /*
* The MIT License
*
* Copyright: Copyright (C) 2014 T2Ti.COM
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* The author may be contacted at: [email protected]
*
* @author Claudio de Barros (T2Ti.com)
* @version 2.0
*/
package com.t2tierp.model.bean.nfe;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "NFE_DETALHE_IMPOSTO_ISSQN")
public class NfeDetalheImpostoIssqn implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private Integer id;
@Column(name = "BASE_CALCULO_ISSQN")
private BigDecimal baseCalculoIssqn;
@Column(name = "ALIQUOTA_ISSQN")
private BigDecimal aliquotaIssqn;
@Column(name = "VALOR_ISSQN")
private BigDecimal valorIssqn;
@Column(name = "MUNICIPIO_ISSQN")
private Integer municipioIssqn;
@Column(name = "ITEM_LISTA_SERVICOS")
private Integer itemListaServicos;
@Column(name = "VALOR_DEDUCAO")
private BigDecimal valorDeducao;
@Column(name = "VALOR_OUTRAS_RETENCOES")
private BigDecimal valorOutrasRetencoes;
@Column(name = "VALOR_DESCONTO_INCONDICIONADO")
private BigDecimal valorDescontoIncondicionado;
@Column(name = "VALOR_DESCONTO_CONDICIONADO")
private BigDecimal valorDescontoCondicionado;
@Column(name = "VALOR_RETENCAO_ISS")
private BigDecimal valorRetencaoIss;
@Column(name = "INDICADOR_EXIGIBILIDADE_ISS")
private Integer indicadorExigibilidadeIss;
@Column(name = "CODIGO_SERVICO")
private String codigoServico;
@Column(name = "MUNICIPIO_INCIDENCIA")
private Integer municipioIncidencia;
@Column(name = "PAIS_SEVICO_PRESTADO")
private Integer paisSevicoPrestado;
@Column(name = "NUMERO_PROCESSO")
private String numeroProcesso;
@Column(name = "INDICADOR_INCENTIVO_FISCAL")
private Integer indicadorIncentivoFiscal;
@JoinColumn(name = "ID_NFE_DETALHE", referencedColumnName = "ID")
@ManyToOne(optional = false)
private NfeDetalhe nfeDetalhe;
public NfeDetalheImpostoIssqn() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public BigDecimal getBaseCalculoIssqn() {
return baseCalculoIssqn;
}
public void setBaseCalculoIssqn(BigDecimal baseCalculoIssqn) {
this.baseCalculoIssqn = baseCalculoIssqn;
}
public BigDecimal getAliquotaIssqn() {
return aliquotaIssqn;
}
public void setAliquotaIssqn(BigDecimal aliquotaIssqn) {
this.aliquotaIssqn = aliquotaIssqn;
}
public BigDecimal getValorIssqn() {
return valorIssqn;
}
public void setValorIssqn(BigDecimal valorIssqn) {
this.valorIssqn = valorIssqn;
}
public Integer getMunicipioIssqn() {
return municipioIssqn;
}
public void setMunicipioIssqn(Integer municipioIssqn) {
this.municipioIssqn = municipioIssqn;
}
public Integer getItemListaServicos() {
return itemListaServicos;
}
public void setItemListaServicos(Integer itemListaServicos) {
this.itemListaServicos = itemListaServicos;
}
public BigDecimal getValorDeducao() {
return valorDeducao;
}
public void setValorDeducao(BigDecimal valorDeducao) {
this.valorDeducao = valorDeducao;
}
public BigDecimal getValorOutrasRetencoes() {
return valorOutrasRetencoes;
}
public void setValorOutrasRetencoes(BigDecimal valorOutrasRetencoes) {
this.valorOutrasRetencoes = valorOutrasRetencoes;
}
public BigDecimal getValorDescontoIncondicionado() {
return valorDescontoIncondicionado;
}
public void setValorDescontoIncondicionado(BigDecimal valorDescontoIncondicionado) {
this.valorDescontoIncondicionado = valorDescontoIncondicionado;
}
public BigDecimal getValorDescontoCondicionado() {
return valorDescontoCondicionado;
}
public void setValorDescontoCondicionado(BigDecimal valorDescontoCondicionado) {
this.valorDescontoCondicionado = valorDescontoCondicionado;
}
public BigDecimal getValorRetencaoIss() {
return valorRetencaoIss;
}
public void setValorRetencaoIss(BigDecimal valorRetencaoIss) {
this.valorRetencaoIss = valorRetencaoIss;
}
public Integer getIndicadorExigibilidadeIss() {
return indicadorExigibilidadeIss;
}
public void setIndicadorExigibilidadeIss(Integer indicadorExigibilidadeIss) {
this.indicadorExigibilidadeIss = indicadorExigibilidadeIss;
}
public String getCodigoServico() {
return codigoServico;
}
public void setCodigoServico(String codigoServico) {
this.codigoServico = codigoServico;
}
public Integer getMunicipioIncidencia() {
return municipioIncidencia;
}
public void setMunicipioIncidencia(Integer municipioIncidencia) {
this.municipioIncidencia = municipioIncidencia;
}
public Integer getPaisSevicoPrestado() {
return paisSevicoPrestado;
}
public void setPaisSevicoPrestado(Integer paisSevicoPrestado) {
this.paisSevicoPrestado = paisSevicoPrestado;
}
public String getNumeroProcesso() {
return numeroProcesso;
}
public void setNumeroProcesso(String numeroProcesso) {
this.numeroProcesso = numeroProcesso;
}
public Integer getIndicadorIncentivoFiscal() {
return indicadorIncentivoFiscal;
}
public void setIndicadorIncentivoFiscal(Integer indicadorIncentivoFiscal) {
this.indicadorIncentivoFiscal = indicadorIncentivoFiscal;
}
public NfeDetalhe getNfeDetalhe() {
return nfeDetalhe;
}
public void setNfeDetalhe(NfeDetalhe nfeDetalhe) {
this.nfeDetalhe = nfeDetalhe;
}
@Override
public String toString() {
return "com.t2tierp.model.bean.nfe.NfeDetalheImpostoIssqn[id=" + id + "]";
}
}
| 30.36214 | 88 | 0.728246 |
c328ed6ef77a795218bc66ec12e422af6f6bcd0e | 8,772 | package net.mattcarpenter.srs.sm2;
import com.google.common.collect.ImmutableMap;
import net.mattcarpenter.srs.sm2.utils.MockTimeProvider;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Map;
import java.util.Set;
public class SchedulerTest {
private MockTimeProvider mockTimeProvider;
private DateTime initialDate;
@BeforeMethod
public void before() {
initialDate = makeDate("2019-01-01 12:00:00 AM");
mockTimeProvider = new MockTimeProvider(initialDate);
}
@Test
public void addItem_dedupes() {
Item item = Item.builder().build();
Item item2 = Item.builder().build();
Scheduler scheduler = Scheduler.builder().build();
scheduler.addItem(item);
scheduler.addItem(item);
scheduler.addItem(item2);
Set<Item> items = scheduler.getItems();
Assert.assertEquals(items.size(), 2);
}
@Test
public void updateItemInterval_allCorrect_SM2_defaults() {
Scheduler scheduler = Scheduler.builder().build();
Item item = Item.builder().interval(0).build();
SessionItemStatistics statistics = new SessionItemStatistics(false, 5);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 1);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 6);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 17);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 49);
}
@Test
public void updateItemInterval_resetsAfterLapse() {
Scheduler scheduler = Scheduler.builder().build();
Item item = Item.builder().interval(0).build();
SessionItemStatistics statistics = new SessionItemStatistics(false, 5);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 1);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 6);
// represents a session where a lapse occurred but item answered successfully at the end
SessionItemStatistics statistics2 = new SessionItemStatistics(true, 5);
scheduler.updateItemInterval(item, statistics2);
Assert.assertEquals(item.getInterval(), 1);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 6);
}
@Test
public void updateItemInterval_failedSession() {
Scheduler scheduler = Scheduler.builder().build();
Item item = Item.builder().interval(0).build();
SessionItemStatistics statistics = new SessionItemStatistics(true, 2);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 0);
}
@Test
public void updateItemInterval_customConsecutiveCorrectIntervalMapping() {
Map<Integer, Float> intervalMapping = ImmutableMap.of(
1, 1f,
2, 2f,
3, 4f
);
Scheduler scheduler = Scheduler.builder()
.consecutiveCorrectIntervalMappings(intervalMapping)
.build();
Item item = Item.builder().interval(0).build();
SessionItemStatistics statistics = new SessionItemStatistics(false, 5);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 1);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 2);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 4);
scheduler.updateItemInterval(item, statistics);
Assert.assertEquals(item.getInterval(), 12);
}
@Test
public void getConsecutiveCorrectInterval_getsDefaults() {
Scheduler scheduler = Scheduler.builder().build();
Assert.assertEquals(scheduler.getConsecutiveCorrectInterval(1).floatValue(), 1f);
Assert.assertEquals(scheduler.getConsecutiveCorrectInterval(2).floatValue(), 6f);
Assert.assertNull(scheduler.getConsecutiveCorrectInterval(3));
}
@Test
public void getConsecutiveCorrectInterval_getsBothCustomAndDefault() {
Map<Integer, Float> intervalMapping = ImmutableMap.of(
1, 1f,
2, 4f
);
Scheduler scheduler = Scheduler.builder()
.consecutiveCorrectIntervalMappings(intervalMapping)
.build();
Assert.assertEquals(scheduler.getConsecutiveCorrectInterval(1).floatValue(), 1f);
Assert.assertEquals(scheduler.getConsecutiveCorrectInterval(2).floatValue(), 4f);
Assert.assertNull(scheduler.getConsecutiveCorrectInterval(3));
}
@Test
public void updateItemSchedule_computesDueDate_wholeDayInterval() {
Item item = Item.builder()
.interval(1f)
.build();
Scheduler scheduler = Scheduler.builder()
.timeProvider(mockTimeProvider)
.build();
scheduler.updateItemSchedule(item);
// interval of 1 should return a due date that is one day ahead of the initial
Assert.assertEquals(item.getDueDate(), mockTimeProvider.getNow().plusDays(1));
}
@Test
public void updateItemSchedule_computesDueDate_partialDayInterval() {
Item item = Item.builder()
.interval(1.5f)
.build();
Scheduler scheduler = Scheduler.builder()
.timeProvider(mockTimeProvider)
.build();
scheduler.updateItemSchedule(item);
// interval of 1.5 should return a due date that is one 1 day 12 hours ahead of now
Assert.assertEquals(item.getDueDate(), initialDate.plusDays(1).plusHours(12));
}
@Test
public void applySession_schedules_ok() {
Item item = Item.builder().build();
Session session = new Session();
Scheduler scheduler = Scheduler.builder().timeProvider(mockTimeProvider).build();
Review review = new Review(item, 5);
session.applyReview(review);
// apply first session and check that the due date is 1 days from the initial date
scheduler.applySession(session);
Assert.assertEquals(item.getDueDate(), initialDate.plusDays(1));
Assert.assertEquals(item.getConsecutiveCorrectCount(), 1);
// change mock date to simulate late review
mockTimeProvider.setNow(makeDate("2019-01-10 12:00:00 AM"));
// apply the first session again and check that the due date is 7 days from the second review date
scheduler.applySession(session);
Assert.assertEquals(item.getDueDate(), makeDate("2019-01-16 12:00:00 AM"));
Assert.assertEquals(item.getConsecutiveCorrectCount(), 2);
}
@Test
public void applySession_schedules_lapsed() {
Item item = Item.builder().build();
Session session = new Session();
Scheduler scheduler = Scheduler.builder().timeProvider(mockTimeProvider).build();
Review review = new Review(item, 5);
session.applyReview(review);
// apply first session and check that the due date is 1 days from the initial date
scheduler.applySession(session);
Assert.assertEquals(item.getDueDate(), initialDate.plusDays(1));
Assert.assertEquals(item.getConsecutiveCorrectCount(), 1);
// apply the first session again and check that the due date is 7 days from the initial date
Session session2 = new Session();
Review review2 = new Review(item, 0);
Review review3 = new Review(item, 5);
session2.applyReview(review2);
session2.applyReview(review3);
scheduler.applySession(session2);
Assert.assertEquals(item.getDueDate(), initialDate.plusDays(1));
Assert.assertEquals(item.getConsecutiveCorrectCount(), 1);
}
@Test
public void consecutiveCorrectIntervalMappings_get_set() {
Scheduler scheduler = Scheduler.builder().build();
Map<Integer, Float> intervalMapping = ImmutableMap.of(
1, 1f,
2, 2f,
3, 4f
);
scheduler.setConsecutiveCorrectIntervalMappings(intervalMapping);
Assert.assertEquals(scheduler.getConsecutiveCorrectIntervalMappings(), intervalMapping);
}
public DateTime makeDate(String date) {
String pattern = "yyyy-mm-dd hh:mm:ss aa";
return DateTime.parse(date, DateTimeFormat.forPattern(pattern));
}
}
| 36.55 | 106 | 0.668035 |
50f8f8ba4a62f3754fda47e6e4d061e841b40807 | 7,669 |
package shiver.me.timbers.aws.medialive;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import shiver.me.timbers.aws.Property;
/**
* ChannelOutputDestination
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html
*
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonPropertyOrder({
"MultiplexSettings",
"Id",
"Settings",
"MediaPackageSettings"
})
public class ChannelOutputDestination implements Property<ChannelOutputDestination>
{
/**
* ChannelMultiplexProgramChannelDestinationSettings
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-multiplexprogramchanneldestinationsettings.html
*
*/
@JsonProperty("MultiplexSettings")
@JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-multiplexprogramchanneldestinationsettings.html")
private Property<ChannelMultiplexProgramChannelDestinationSettings> multiplexSettings;
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-id
*
*/
@JsonProperty("Id")
@JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-id")
private CharSequence id;
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-settings
*
*/
@JsonProperty("Settings")
@JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-settings")
private List<Property<ChannelOutputDestinationSettings>> settings = new ArrayList<Property<ChannelOutputDestinationSettings>>();
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-mediapackagesettings
*
*/
@JsonProperty("MediaPackageSettings")
@JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-mediapackagesettings")
private List<Property<ChannelMediaPackageOutputDestinationSettings>> mediaPackageSettings = new ArrayList<Property<ChannelMediaPackageOutputDestinationSettings>>();
/**
* ChannelMultiplexProgramChannelDestinationSettings
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-multiplexprogramchanneldestinationsettings.html
*
*/
@JsonIgnore
public Property<ChannelMultiplexProgramChannelDestinationSettings> getMultiplexSettings() {
return multiplexSettings;
}
/**
* ChannelMultiplexProgramChannelDestinationSettings
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-multiplexprogramchanneldestinationsettings.html
*
*/
@JsonIgnore
public void setMultiplexSettings(Property<ChannelMultiplexProgramChannelDestinationSettings> multiplexSettings) {
this.multiplexSettings = multiplexSettings;
}
public ChannelOutputDestination withMultiplexSettings(Property<ChannelMultiplexProgramChannelDestinationSettings> multiplexSettings) {
this.multiplexSettings = multiplexSettings;
return this;
}
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-id
*
*/
@JsonIgnore
public CharSequence getId() {
return id;
}
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-id
*
*/
@JsonIgnore
public void setId(CharSequence id) {
this.id = id;
}
public ChannelOutputDestination withId(CharSequence id) {
this.id = id;
return this;
}
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-settings
*
*/
@JsonIgnore
public List<Property<ChannelOutputDestinationSettings>> getSettings() {
return settings;
}
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-settings
*
*/
@JsonIgnore
public void setSettings(List<Property<ChannelOutputDestinationSettings>> settings) {
this.settings = settings;
}
public ChannelOutputDestination withSettings(List<Property<ChannelOutputDestinationSettings>> settings) {
this.settings = settings;
return this;
}
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-mediapackagesettings
*
*/
@JsonIgnore
public List<Property<ChannelMediaPackageOutputDestinationSettings>> getMediaPackageSettings() {
return mediaPackageSettings;
}
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-mediapackagesettings
*
*/
@JsonIgnore
public void setMediaPackageSettings(List<Property<ChannelMediaPackageOutputDestinationSettings>> mediaPackageSettings) {
this.mediaPackageSettings = mediaPackageSettings;
}
public ChannelOutputDestination withMediaPackageSettings(List<Property<ChannelMediaPackageOutputDestinationSettings>> mediaPackageSettings) {
this.mediaPackageSettings = mediaPackageSettings;
return this;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("multiplexSettings", multiplexSettings).append("id", id).append("settings", settings).append("mediaPackageSettings", mediaPackageSettings).toString();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(mediaPackageSettings).append(multiplexSettings).append(settings).append(id).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof ChannelOutputDestination) == false) {
return false;
}
ChannelOutputDestination rhs = ((ChannelOutputDestination) other);
return new EqualsBuilder().append(mediaPackageSettings, rhs.mediaPackageSettings).append(multiplexSettings, rhs.multiplexSettings).append(settings, rhs.settings).append(id, rhs.id).isEquals();
}
}
| 41.907104 | 210 | 0.756944 |
61ae14e3d73de519cf886bb3ee90f7ecfa5e864b | 417 | package application.repositories;
import application.entities.security.UserSession;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserSessionRepository extends JpaRepository<UserSession, Integer> {
public UserSession findByTokenAndIsValidTrue(String token);
public UserSession findByUserNameAndIpAndUserAgentAndIsValidTrue(String userName, String address, String agent);
}
| 37.909091 | 116 | 0.851319 |
3de33667bd5dc0a32a49e89cf86e68a79f14eaac | 586 | package lambdaTest;
/**
* @author yyt
* @date 2021年12月26日 19:39
*/
public class Function4Test {
public static void main(String[] args) {
/**
* 通过[类名::new]的方式来实例化对象
* 原写法:ProductCreator creator = (id, name, price) -> new lambdaTest.Product(id, name, price);
*/
ProductCreator creator = Product::new;
Product p1 = creator.getProduct(1, "大棉袄", 365.00);
System.out.println(p1.toString());
}
@FunctionalInterface
interface ProductCreator {
Product getProduct(int id, String name, double price);
}
}
| 25.478261 | 101 | 0.610922 |
0869543e3c2d4420baa3d782e60ef92e4d1b2618 | 4,369 | package org.treblereel.gwt.three4g.demo.client.local.examples.performance;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.animation.client.AnimationScheduler;
import elemental2.dom.MouseEvent;
import jsinterop.base.Js;
import org.treblereel.gwt.three4g.cameras.PerspectiveCamera;
import org.treblereel.gwt.three4g.core.BufferGeometry;
import org.treblereel.gwt.three4g.demo.client.local.AppSetup;
import org.treblereel.gwt.three4g.demo.client.local.Attachable;
import org.treblereel.gwt.three4g.demo.client.local.utils.StatsProducer;
import org.treblereel.gwt.three4g.loaders.BufferGeometryLoader;
import org.treblereel.gwt.three4g.loaders.OnLoadCallback;
import org.treblereel.gwt.three4g.materials.MeshNormalMaterial;
import org.treblereel.gwt.three4g.math.Color;
import org.treblereel.gwt.three4g.math.Vector2;
import org.treblereel.gwt.three4g.objects.Mesh;
import org.treblereel.gwt.three4g.renderers.WebGLRenderer;
import org.treblereel.gwt.three4g.scenes.Scene;
/**
* @author Dmitrii Tikhomirov <[email protected]>
* Created by treblereel on 7/10/18.
*/
public class WebglPerformance extends Attachable {
public static final String name = "performance";
private Vector2 mouse = new Vector2();
private int windowHalfX = window.innerWidth / 2;
private int windowHalfY = window.innerHeight / 2;
private List<Mesh> objects = new ArrayList<>();
public WebglPerformance() {
camera = new PerspectiveCamera(60, aspect, 1, 10000);
camera.position.z = 3200;
scene = new Scene();
scene.background = new Color(0xffffff);
MeshNormalMaterial material = new MeshNormalMaterial();
BufferGeometryLoader loader = new BufferGeometryLoader();
loader.load("json/suzanne_buffergeometry.json", (OnLoadCallback<BufferGeometry>) geometry -> {
geometry.computeVertexNormals();
for (int i = 0; i < 5000; i++) {
Mesh mesh = new Mesh(geometry, material);
mesh.position.x = (float) Math.random() * 8000 - 4000;
mesh.position.y = (float) Math.random() * 8000 - 4000;
mesh.position.z = (float) Math.random() * 8000 - 4000;
mesh.rotation.x = (float) (Math.random() * 2 * Math.PI);
mesh.rotation.y = (float) (Math.random() * 2 * Math.PI);
mesh.scale.x = mesh.scale.y = mesh.scale.z = (float) Math.random() * 50 + 100;
objects.add(mesh);
scene.add(mesh);
}
});
renderer = new WebGLRenderer();
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.domElement.onmousemove = p0 -> {
MouseEvent event = Js.uncheckedCast(p0);
onDocumentMouseMove(event);
return null;
};
}
private void onDocumentMouseMove(MouseEvent event) {
event.preventDefault();
mouse.x = (float) (event.clientX - windowHalfX) * 10;
mouse.y = (float) (event.clientY - windowHalfY) * 10;
}
public void doAttachScene() {
root.appendChild(renderer.domElement);
onWindowResize();
animate();
}
@Override
protected void doAttachInfo() {
AppSetup.infoDiv.hide();
}
@Override
public void onWindowResize() {
if (camera != null && renderer != null) {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = aspect;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
}
private void animate() {
StatsProducer.getStats().update();
AnimationScheduler.get().requestAnimationFrame(timestamp -> {
if (root.parentNode != null) {
render();
animate();
}
});
}
private void render() {
camera.position.x += (mouse.x - camera.position.x) * .05;
camera.position.y += (-mouse.y - camera.position.y) * .05;
camera.lookAt(scene.position);
for (int i = 0, il = objects.size(); i < il; i++) {
objects.get(i).rotation.x += 0.01;
objects.get(i).rotation.y += 0.02;
}
renderer.render(scene, camera);
}
}
| 35.811475 | 102 | 0.634241 |
24b8c7a8e66bb90d59102e6178922892ffffb910 | 13,557 | package authoring.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.ResourceBundle;
import authoring.AuthorEnvironment;
import authoring.view.canvas.CanvasView;
import authoring.view.canvas.SpriteView;
import authoring.view.canvas.SpriteViewComparator;
import game_object.core.Dimension;
import game_object.core.ISprite;
import game_object.level.Level;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import resources.ResourceBundles;
/**
* @author billyu Controller for canvas
*/
public class CanvasController implements Observer {
private CanvasView myCanvas;
private List<SpriteView> mySpriteViews;
private ScrollPane myScrollPane;
private Group myContent; // holder for all SpriteViews
private HBox myBackground;
private AuthorEnvironment myEnvironment;
private double mySceneWidth;
private double mySceneHeight;
private double myBackgroundWidth;
private double myBackgroundHeight;
private boolean myDoesSnap;
private SpriteViewComparator mySpriteViewComparator;
private ResourceBundle myCanvasProperties;
public void init(CanvasView canvas, ScrollPane scrollPane, Group content, HBox background) {
myCanvasProperties = ResourceBundles.canvasProperties;
myCanvas = canvas;
myScrollPane = scrollPane;
myContent = content;
myBackground = background;
myEnvironment = canvas.getController().getEnvironment();
myEnvironment.addObserver(this);
mySpriteViews = new ArrayList<>();
mySpriteViewComparator = new SpriteViewComparator();
setOnDrag();
initSpriteViews();
}
/**
* refresh sprite views
* called after user selects a different level
*/
public void refresh() {
initSpriteViews();
}
/**
* method to add a SpriteView to canvas
* used for drag and drop from components view
*
* @param spView
* @param x
* @param y
* @param relative if true, x and y are positions on screen instead of real positions
*/
public void add(SpriteView spView, double x, double y, boolean relative) {
mySpriteViews.add(spView);
spView.setCanvasView(myCanvas);
myContent.getChildren().add(spView.getUI());
if (relative) {
setRelativePosition(spView, x, y);
} else {
setAbsolutePosition(spView, x, y);
}
reorderSpriteViewsWithPositionZ();
if (myDoesSnap) {
spView.snapToGrid();
}
}
public void delete(SpriteView spView) {
if (spView == null) return;
mySpriteViews.remove(spView);
myEnvironment.getCurrentLevel().removeSprite(spView.getSprite());
this.reorderSpriteViewsWithPositionZ();
}
/**
* method to set the position of a spView
*
* @param spView to be set
* @param x new position X relative to top-left corner
* @param y new position Y relative to top-left corner
* x and y are not relative to the origin of content!
*/
public void setRelativePosition(SpriteView spView, double x, double y) {
retrieveScrollPaneSize();
retrieveBackgroundSize();
double newx = 0, newy = 0;
if (mySceneWidth > myBackgroundWidth) {
newx = x;
} else {
newx = toAbsoluteX(x);
}
if (mySceneHeight > myBackgroundHeight) {
newy = y;
} else {
newy = toAbsoluteY(y);
}
setAbsolutePosition(spView, newx, newy);
}
/**
* @param spView
* @param x
* @param y x and y are absolute
*/
public void setAbsolutePosition(SpriteView spView, double x, double y) {
spView.setAbsolutePositionX(x);
spView.setAbsolutePositionY(y);
}
public void setAbsolutePositionZ(SpriteView spView, double z) {
spView.setAbsolutePositionZ(z);
}
public void onDragSpriteView(SpriteView spView, MouseEvent event) {
double x = event.getSceneX() - myCanvas.getPositionX();
double y = event.getSceneY() - myCanvas.getPositionY();
retrieveScrollPaneSize();
adjustScrollPane(x, y);
this.setRelativePosition(
spView,
x - spView.getMouseOffset().getX(),
y - spView.getMouseOffset().getY());
}
/**
* @param spView
* @param startX top left corner X
* @param startY top left corner Y
* @param endX bottom right corner X
* @param endY bottom right corner Y
* x, y are absolute sprite positions
*/
public void onResizeSpriteView(SpriteView spView,
double startX,
double startY,
double endX,
double endY) {
if (startX > endX || startY > endY) return;
this.setAbsolutePosition(spView, startX, startY);
spView.setDimensionWidth(endX - startX);
spView.setDimensionHeight(endY - startY);
}
public void reorderSpriteViewsWithPositionZ() {
mySpriteViews.sort(mySpriteViewComparator);
double hValue = myScrollPane.getHvalue();
double vValue = myScrollPane.getVvalue();
clearSpriteViews(false);
for (SpriteView spView : mySpriteViews) {
myContent.getChildren().add(spView.getUI());
}
myScrollPane.setHvalue(hValue);
myScrollPane.setVvalue(vValue);
}
public void expand() {
double width = myEnvironment.getCurrentLevel().getLevelDimension().getWidth();
width += Double.parseDouble(myCanvasProperties.getString("SCREEN_CHANGE_INTERVAL"));
myEnvironment.getCurrentLevel().getLevelDimension().setWidth(width);
updateBackground();
}
public void shrink() {
double width = myEnvironment.getCurrentLevel().getLevelDimension().getWidth();
width -= Double.parseDouble(myCanvasProperties.getString("SCREEN_CHANGE_INTERVAL"));
myEnvironment.getCurrentLevel().getLevelDimension().setWidth(width);
updateBackground();
}
public void taller() {
double height = myEnvironment.getCurrentLevel().getLevelDimension().getHeight();
height += Double.parseDouble(myCanvasProperties.getString("SCREEN_CHANGE_INTERVAL"));
myEnvironment.getCurrentLevel().getLevelDimension().setHeight(height);
updateBackground();
}
public void shorter() {
double height = myEnvironment.getCurrentLevel().getLevelDimension().getHeight();
height -= Double.parseDouble(myCanvasProperties.getString("SCREEN_CHANGE_INTERVAL"));
myEnvironment.getCurrentLevel().getLevelDimension().setHeight(height);
updateBackground();
}
// relative positions to absolute
public double toAbsoluteX(double x) {
return myScrollPane.getHvalue() * (myBackgroundWidth - mySceneWidth) + x;
}
public double toAbsoluteY(double y) {
return myScrollPane.getVvalue() * (myBackgroundHeight - mySceneHeight) + y;
}
private void initSpriteViews() {
clearSpriteViews(true);
Level currentLevel = myEnvironment.getCurrentLevel();
if (currentLevel == null) {
throw new RuntimeException("no current level for canvas");
}
for (ISprite sp : currentLevel.getAllSprites()) {
SpriteView spView = new SpriteView(myCanvas.getController());
Dimension dim = new Dimension(sp.getDimension().getWidth(), sp.getDimension().getHeight());
spView.setSprite(sp);
spView.setDimensionHeight(dim.getHeight());
spView.setDimensionWidth(dim.getWidth());
add(spView, sp.getPosition().getX(), sp.getPosition().getY(), false);
}
updateBackground();
}
private void retrieveScrollPaneSize() {
mySceneWidth = myScrollPane.getViewportBounds().getWidth();
mySceneHeight = myScrollPane.getViewportBounds().getHeight();
}
private void retrieveBackgroundSize() {
myBackgroundWidth = myBackground.getWidth();
myBackgroundHeight = myBackground.getHeight();
}
private void setOnDrag() {
myScrollPane.setOnDragOver(event -> {
if (event.getDragboard().hasImage()) {
event.acceptTransferModes(TransferMode.COPY);
}
event.consume();
});
myScrollPane.setOnDragDropped(event -> {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasImage()) {
double x = event.getSceneX() - myCanvas.getPositionX();
double y = event.getSceneY() - myCanvas.getPositionY();
makeAndAddSpriteView(x, y);
success = true;
}
event.setDropCompleted(success);
event.consume();
});
}
/**
* @param x
* @param y x and y are positions relative to screen
*/
private void makeAndAddSpriteView(double x, double y) {
SpriteView spView = myCanvas.getController().getComponentController().makeSpriteViewFromCopiedSprite(myCanvas);
add(spView, x - spView.getWidth() / 2, y - spView.getHeight() / 2, true);
myCanvas.getController().selectSpriteView(spView);
myEnvironment.getCurrentLevel().addSprite(spView.getSprite());
}
private void adjustScrollPane(double x, double y) {
if (x < Double.parseDouble(myCanvasProperties.getString("DRAG_SCROLL_THRESHOLD"))) {
myScrollPane.setHvalue(Math.max(0,
myScrollPane.getHvalue() - Double.parseDouble(myCanvasProperties.getString("SCROLL_VALUE_UNIT"))));
}
if (mySceneWidth - x < Double.parseDouble(myCanvasProperties.getString("DRAG_SCROLL_THRESHOLD"))) {
myScrollPane.setHvalue(Math.min(1,
myScrollPane.getHvalue() + Double.parseDouble(myCanvasProperties.getString("SCROLL_VALUE_UNIT"))));
}
if (y < Double.parseDouble(myCanvasProperties.getString("DRAG_SCROLL_THRESHOLD"))) {
myScrollPane.setVvalue(Math.max(0,
myScrollPane.getVvalue() - Double.parseDouble(myCanvasProperties.getString("SCROLL_VALUE_UNIT"))));
}
if (mySceneHeight - y < Double.parseDouble(myCanvasProperties.getString("DRAG_SCROLL_THRESHOLD"))) {
myScrollPane.setVvalue(Math.min(1,
myScrollPane.getVvalue() + Double.parseDouble(myCanvasProperties.getString("SCROLL_VALUE_UNIT"))));
}
}
/**
* @param data if spriteViews get cleared also
*/
private void clearSpriteViews(boolean data) {
myContent.getChildren().clear();
myContent.getChildren().add(myBackground);
if (data) {
mySpriteViews.clear();
}
}
private void updateBackground() {
// TODO: 11/29/16 allow for tiling of multiple image paths, rather than just first
myBackground.getChildren().clear();
double width = myEnvironment.getCurrentLevel().getLevelDimension().getWidth();
double height = myEnvironment.getCurrentLevel().getLevelDimension().getHeight();
if (myEnvironment.getCurrentLevel().getBackground().getImagePaths().size() == 0) {
Rectangle rectangle = new Rectangle(0, 0, width, height);
rectangle.setFill(Color.LIGHTCYAN);
myBackground.getChildren().add(rectangle);
} else {
Image backgroundImage = new Image(myEnvironment.getCurrentLevel().getBackground().getImagePaths().get(0));
double adjustedWidth = height * (backgroundImage.getWidth() / backgroundImage.getHeight());
double usedWidth;
for (usedWidth = adjustedWidth; usedWidth < width; usedWidth += adjustedWidth) {
ImageView imageView = new ImageView(backgroundImage);
imageView.setPreserveRatio(true);
imageView.setFitWidth(adjustedWidth);
myBackground.getChildren().add(imageView);
}
ImageView imageView = new ImageView(backgroundImage);
imageView.setPreserveRatio(true);
imageView.setFitHeight(height);
imageView.setViewport(new Rectangle2D(0, 0,
(1 - ((usedWidth - width) / adjustedWidth)) * backgroundImage.getWidth(),
backgroundImage.getHeight()));
myBackground.getChildren().add(imageView);
}
}
public double convertToNearestBlockValue(double value) {
return Math.max(Math.round(value / Double.parseDouble(myCanvasProperties.getString("BLOCK_SIZE"))) * Double.parseDouble(myCanvasProperties.getString("BLOCK_SIZE")), Double.parseDouble(myCanvasProperties.getString("BLOCK_SIZE")));
}
@Override
public void update(Observable o, Object arg) {
refresh();
}
public void setSnapToGrid(boolean doesSnap) {
myDoesSnap = doesSnap;
}
public boolean getSnapToGrid() {
return myDoesSnap;
}
}
| 37.868715 | 237 | 0.644538 |
3ebebe1a8f6eec7f6c04bf41069b257cb198928a | 4,309 | package com.itextpdf.text;
import com.itextpdf.text.pdf.OutputStreamCounter;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public abstract class DocWriter implements DocListener {
public static final byte EQUALS = (byte) 61;
public static final byte FORWARD = (byte) 47;
public static final byte GT = (byte) 62;
public static final byte LT = (byte) 60;
public static final byte NEWLINE = (byte) 10;
public static final byte QUOTE = (byte) 34;
public static final byte SPACE = (byte) 32;
public static final byte TAB = (byte) 9;
protected boolean closeStream = true;
protected Document document;
protected boolean open = false;
protected OutputStreamCounter os;
protected Rectangle pageSize;
protected boolean pause = false;
protected DocWriter() {
}
protected DocWriter(Document document, OutputStream os) {
this.document = document;
this.os = new OutputStreamCounter(new BufferedOutputStream(os));
}
public boolean add(Element element) throws DocumentException {
return false;
}
public void open() {
this.open = true;
}
public boolean setPageSize(Rectangle pageSize) {
this.pageSize = pageSize;
return true;
}
public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom) {
return false;
}
public boolean newPage() {
if (this.open) {
return true;
}
return false;
}
public void resetPageCount() {
}
public void setPageCount(int pageN) {
}
public void close() {
this.open = false;
try {
this.os.flush();
if (this.closeStream) {
this.os.close();
}
} catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
public static final byte[] getISOBytes(String text) {
if (text == null) {
return null;
}
int len = text.length();
byte[] b = new byte[len];
for (int k = 0; k < len; k++) {
b[k] = (byte) text.charAt(k);
}
return b;
}
public void pause() {
this.pause = true;
}
public boolean isPaused() {
return this.pause;
}
public void resume() {
this.pause = false;
}
public void flush() {
try {
this.os.flush();
} catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
protected void write(String string) throws IOException {
this.os.write(getISOBytes(string));
}
protected void addTabs(int indent) throws IOException {
this.os.write(10);
for (int i = 0; i < indent; i++) {
this.os.write(9);
}
}
protected void write(String key, String value) throws IOException {
this.os.write(32);
write(key);
this.os.write(61);
this.os.write(34);
write(value);
this.os.write(34);
}
protected void writeStart(String tag) throws IOException {
this.os.write(60);
write(tag);
}
protected void writeEnd(String tag) throws IOException {
this.os.write(60);
this.os.write(47);
write(tag);
this.os.write(62);
}
protected void writeEnd() throws IOException {
this.os.write(32);
this.os.write(47);
this.os.write(62);
}
protected boolean writeMarkupAttributes(Properties markup) throws IOException {
if (markup == null) {
return false;
}
for (Object valueOf : markup.keySet()) {
String name = String.valueOf(valueOf);
write(name, markup.getProperty(name));
}
markup.clear();
return true;
}
public boolean isCloseStream() {
return this.closeStream;
}
public void setCloseStream(boolean closeStream) {
this.closeStream = closeStream;
}
public boolean setMarginMirroring(boolean MarginMirroring) {
return false;
}
public boolean setMarginMirroringTopBottom(boolean MarginMirroring) {
return false;
}
}
| 24.907514 | 105 | 0.588071 |
3d73dec820cf70b5f5935af8fc4c4d0241303725 | 1,282 | package de.polocloud.api.component.base;
import de.polocloud.api.component.feature.ComponentOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
public class SimpleTextBase<B extends TextBased<B>> implements TextBased<B> {
/**
* All the stored options to this base
*/
protected Map<ComponentOption<B, ?>, Object> options;
/**
* All handlers when adding an option
*/
private List<Consumer<ComponentOption<B, ?>>> optionHandler;
/**
* Constructs this simple base
*/
public SimpleTextBase() {
this.options = new ConcurrentHashMap<>();
this.optionHandler = new ArrayList<>();
}
@Override
public <T> B put(ComponentOption<B, T> option, T t) {
option.setValue(t);
this.options.put(option, t);
for (Consumer<ComponentOption<B, ?>> componentOptionConsumer : this.optionHandler) {
componentOptionConsumer.accept(option);
}
return (B) this;
}
/**
* Adds a handler to this base to listen for options
*/
public void addHandler(Consumer<ComponentOption<B, ?>> handler) {
this.optionHandler.add(handler);
}
}
| 26.708333 | 92 | 0.654446 |
75bcdc31a155ea07e7ab3b7b83f65f9d5d446e5c | 527 | package dev.majek.advancements.shared;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
/**
* Enums implementing this interface are used to define data usually in {@link SharedObject}s.
* They can also be converted to a {@link String} to be used in JSON objects.
*/
public interface SharedEnum {
/**
* Get a string representation of the enum value, which can be used in Json objects.
*
* @return a string representation
*/
@NotNull
@Contract(pure = true)
String value();
}
| 25.095238 | 94 | 0.736243 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.