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
|
---|---|---|---|---|---|
0d931e15df85d91af68a05b545d0e05673e6af1c | 1,621 | package org.openecomp.sdc.be.externalapi.servlet.representation;
import javax.annotation.Generated;
import org.junit.Test;
public class ProductCategoryGroupMetadataTest {
private ProductCategoryGroupMetadata createTestSubject() {
return new ProductCategoryGroupMetadata("", "", "");
}
@Test
public void testGetCategory() throws Exception {
ProductCategoryGroupMetadata testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getCategory();
}
@Test
public void testSetCategory() throws Exception {
ProductCategoryGroupMetadata testSubject;
String category = "";
// default test
testSubject = createTestSubject();
testSubject.setCategory(category);
}
@Test
public void testGetSubCategory() throws Exception {
ProductCategoryGroupMetadata testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getSubCategory();
}
@Test
public void testSetSubCategory() throws Exception {
ProductCategoryGroupMetadata testSubject;
String subCategory = "";
// default test
testSubject = createTestSubject();
testSubject.setSubCategory(subCategory);
}
@Test
public void testGetGroup() throws Exception {
ProductCategoryGroupMetadata testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getGroup();
}
@Test
public void testSetGroup() throws Exception {
ProductCategoryGroupMetadata testSubject;
String group = "";
// default test
testSubject = createTestSubject();
testSubject.setGroup(group);
}
} | 20.518987 | 64 | 0.752622 |
512e284cd0be90934a00f58cab04d49c10188996 | 1,287 | package commenttemplate.template.tags.tags;
import commenttemplate.expressions.primitivehandle.NumHandle;
import commenttemplate.expressions.tree.Exp;
import commenttemplate.context.Context;
import commenttemplate.template.tags.ConditionalTag;
import static commenttemplate.template.tags.BasicTag.EVAL_BODY;
import static commenttemplate.template.tags.BasicTag.EVAL_ELSE;
import commenttemplate.template.writer.Writer;
import commenttemplate.template.tags.consequence.Consequence;
/**
*
* @author thiago
*/
public class IfTag extends ConditionalTag {
private Exp test;
public IfTag() {
}
protected boolean isBool(Object ob) {
return ob instanceof Boolean;
}
protected boolean isNumber(Object obj) {
return obj instanceof Number;
}
protected boolean isString(Object obj) {
return obj instanceof String;
}
protected boolean isEmptyStr(String obj) {
return ((String)obj).isEmpty();
}
public void setTest(Exp test) {
this.test = test;
}
@Override
public Consequence doTest(Context context, Writer sb) {
Exp exp = test;
Object t = exp.eval(context);
boolean b_test = (t != null) && (isBool(t) ? (Boolean)t :!((isNumber(t) && NumHandle.isZero((Number)t)) ^ (isString(t) && isEmptyStr((String)t))));
return b_test ? EVAL_BODY : EVAL_ELSE;
}
}
| 23.833333 | 149 | 0.749806 |
e58cf45c8936b7ed3398d454d8d94f7c195185fd | 2,233 | package quiz.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import quiz.controllerAdvice.ParticipantExceptionHandler;
import quiz.entity.Participant;
import quiz.service.ParticipantService;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ParticipantControllerTest {
@Mock
private ParticipantService participantService;
@InjectMocks
private ParticipantController participantController;
private MockMvc mockMvc;
private ObjectMapper mapper;
private Participant expectedParticipant;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(participantController)
.setControllerAdvice(new ParticipantExceptionHandler())
.setUseSuffixPatternMatch(false)
.build();
mapper = new ObjectMapper();
expectedParticipant = new Participant();
when(participantService.saveParticipant(any(Participant.class)))
.thenReturn(expectedParticipant);
}
@Test
public void testSaveParticipantAnswer() throws Exception {
MvcResult result = mockMvc
.perform(MockMvcRequestBuilders
.post(ParticipantController.PATH)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content("{}"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
assertEquals(mapper.writeValueAsString(expectedParticipant), result.getResponse().getContentAsString());
}
}
| 35.444444 | 112 | 0.734886 |
65a03a2e76a7bdc0e47bad42f0aa69fdc95730fa | 10,763 | package org.broadinstitute.hellbender.tools.walkers.haplotypecaller;
import htsjdk.variant.variantcontext.VariantContext;
import org.broadinstitute.barclay.argparser.Advanced;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.ArgumentCollection;
import org.broadinstitute.barclay.argparser.Hidden;
import org.broadinstitute.hellbender.cmdline.argumentcollections.DbsnpArgumentCollection;
import org.broadinstitute.hellbender.engine.FeatureInput;
import org.broadinstitute.hellbender.tools.walkers.genotyper.StandardCallerArgumentCollection;
import org.broadinstitute.hellbender.utils.haplotype.HaplotypeBAMWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Set of arguments for Assembly Based Callers
*/
public abstract class AssemblyBasedCallerArgumentCollection extends StandardCallerArgumentCollection {
private static final long serialVersionUID = 1L;
@ArgumentCollection
public AssemblyRegionTrimmerArgumentCollection assemblyRegionTrimmerArgs = new AssemblyRegionTrimmerArgumentCollection();
@ArgumentCollection
public ReadThreadingAssemblerArgumentCollection assemblerArgs = new ReadThreadingAssemblerArgumentCollection();
@ArgumentCollection
public LikelihoodEngineArgumentCollection likelihoodArgs = new LikelihoodEngineArgumentCollection();
/**
* rsIDs from this file are used to populate the ID column of the output. Also, the DB INFO flag will be set when appropriate.
* dbSNP is not used in any way for the calculations themselves.
*/
@ArgumentCollection
public DbsnpArgumentCollection dbsnp = new DbsnpArgumentCollection();
/**
* If a call overlaps with a record from the provided comp track, the INFO field will be annotated
* as such in the output with the track name (e.g. -comp:FOO will have 'FOO' in the INFO field). Records that are
* filtered in the comp track will be ignored. Note that 'dbSNP' has been special-cased (see the --dbsnp argument).
*/
@Advanced
@Argument(fullName = "comp", shortName = "comp", doc = "Comparison VCF file(s)", optional = true)
public List<FeatureInput<VariantContext>> comps = Collections.emptyList();
@Advanced
@Argument(fullName="debug", shortName="debug", doc="Print out very verbose debug information about each triggering active region", optional = true)
public boolean debug;
@Advanced
@Argument(fullName="useFilteredReadsForAnnotations", shortName="useFilteredReadsForAnnotations", doc = "Use the contamination-filtered read maps for the purposes of annotating variants", optional=true)
public boolean USE_FILTERED_READ_MAP_FOR_ANNOTATIONS = false;
/**
* The reference confidence mode makes it possible to emit a per-bp or summarized confidence estimate for a site being strictly homozygous-reference.
* See http://www.broadinstitute.org/gatk/guide/article?id=2940 for more details of how this works.
* Note that if you set -ERC GVCF, you also need to set -variant_index_type LINEAR and -variant_index_parameter 128000 (with those exact values!).
* This requirement is a temporary workaround for an issue with index compression.
*/
@Advanced
@Argument(fullName="emitRefConfidence", shortName="ERC", doc="Mode for emitting reference confidence scores", optional = true)
public ReferenceConfidenceMode emitReferenceConfidence = ReferenceConfidenceMode.NONE;
/**
* The assembled haplotypes and locally realigned reads will be written as BAM to this file if requested. Really
* for debugging purposes only. Note that the output here does not include uninformative reads so that not every
* input read is emitted to the bam.
*
* Turning on this mode may result in serious performance cost for the caller. It's really only appropriate to
* use in specific areas where you want to better understand why the caller is making specific calls.
*
* The reads are written out containing an "HC" tag (integer) that encodes which haplotype each read best matches
* according to the haplotype caller's likelihood calculation. The use of this tag is primarily intended
* to allow good coloring of reads in IGV. Simply go to "Color Alignments By > Tag" and enter "HC" to more
* easily see which reads go with these haplotype.
*
* Note that the haplotypes (called or all, depending on mode) are emitted as single reads covering the entire
* active region, coming from sample "HC" and a special read group called "ArtificialHaplotype". This will increase the
* pileup depth compared to what would be expected from the reads only, especially in complex regions.
*
* Note also that only reads that are actually informative about the haplotypes are emitted. By informative we mean
* that there's a meaningful difference in the likelihood of the read coming from one haplotype compared to
* its next best haplotype.
*
* If multiple BAMs are passed as input to the tool (as is common for M2), then they will be combined in the bamout
* output and tagged with the appropriate sample names.
*
* The best way to visualize the output of this mode is with IGV. Tell IGV to color the alignments by tag,
* and give it the "HC" tag, so you can see which reads support each haplotype. Finally, you can tell IGV
* to group by sample, which will separate the potential haplotypes from the reads. All of this can be seen in
* <a href="https://www.dropbox.com/s/xvy7sbxpf13x5bp/haplotypecaller%20bamout%20for%20docs.png">this screenshot</a>
*
*/
@Advanced
@Argument(fullName="bamOutput", shortName="bamout", doc="File to which assembled haplotypes should be written", optional = true)
public String bamOutputPath = null;
/**
* The type of BAM output we want to see. This determines whether HC will write out all of the haplotypes it
* considered (top 128 max) or just the ones that were selected as alleles and assigned to samples.
*/
@Advanced
@Argument(fullName="bamWriterType", shortName="bamWriterType", doc="Which haplotypes should be written to the BAM", optional = true)
public HaplotypeBAMWriter.WriterType bamWriterType = HaplotypeBAMWriter.WriterType.CALLED_HAPLOTYPES;
/**
* If set, certain "early exit" optimizations in HaplotypeCaller, which aim to save compute and time by skipping
* calculations if an ActiveRegion is determined to contain no variants, will be disabled. This is most likely to be useful if
* you're using the -bamout argument to examine the placement of reads following reassembly and are interested in seeing the mapping of
* reads in regions with no variations. Setting the -forceActive and -dontTrimActiveRegions flags may also be necessary.
*/
@Advanced
@Argument(fullName = "disableOptimizations", shortName="disableOptimizations", doc="Don't skip calculations in ActiveRegions with no variants",
optional = true)
public boolean disableOptimizations = false;
// -----------------------------------------------------------------------------------------------
// arguments for debugging / developing
// -----------------------------------------------------------------------------------------------
@Hidden
@Argument(fullName = "keepRG", shortName = "keepRG", doc = "Only use reads from this read group when making calls (but use all reads to build the assembly)", optional = true)
public String keepRG = null;
/**
* This argument is intended for benchmarking and scalability testing.
*/
@Hidden
@Argument(fullName = "justDetermineActiveRegions", shortName = "justDetermineActiveRegions", doc = "Just determine ActiveRegions, don't perform assembly or calling", optional = true)
public boolean justDetermineActiveRegions = false;
/**
* This argument is intended for benchmarking and scalability testing.
*/
@Hidden
@Argument(fullName = "dontGenotype", shortName = "dontGenotype", doc = "Perform assembly but do not genotype variants", optional = true)
public boolean dontGenotype = false;
@Advanced
@Argument(fullName = "dontUseSoftClippedBases", shortName = "dontUseSoftClippedBases", doc = "Do not analyze soft clipped bases in the reads", optional = true)
public boolean dontUseSoftClippedBases = false;
@Hidden
@Argument(fullName = "captureAssemblyFailureBAM", shortName = "captureAssemblyFailureBAM", doc = "Write a BAM called assemblyFailure.bam capturing all of the reads that were in the active region when the assembler failed for any reason", optional = true)
public boolean captureAssemblyFailureBAM = false;
// Parameters to control read error correction
/**
* Enabling this argument may cause fundamental problems with the assembly graph itself.
*/
@Hidden
@Argument(fullName = "errorCorrectReads", shortName = "errorCorrectReads", doc = "Use an exploratory algorithm to error correct the kmers used during assembly", optional = true)
public boolean errorCorrectReads = false;
/**
* As of GATK 3.3, HaplotypeCaller outputs physical (read-based) information (see version 3.3 release notes and documentation for details). This argument disables that behavior.
*/
@Advanced
@Argument(fullName = "doNotRunPhysicalPhasing", shortName = "doNotRunPhysicalPhasing", doc = "Disable physical phasing", optional = true)
public boolean doNotRunPhysicalPhasing = false;
/**
* Bases with a quality below this threshold will not be used for calling.
*/
@Argument(fullName = "min_base_quality_score", shortName = "mbq", doc = "Minimum base quality required to consider a base for calling", optional = true)
public byte minBaseQualityScore = 10;
//Annotations
/**
* Which annotations to exclude from output in the VCF file. Note that this argument has higher priority than the
* -A or -G arguments, so these annotations will be excluded even if they are explicitly included with the other
* options. When HaplotypeCaller is run with -ERC GVCF or -ERC BP_RESOLUTION, some annotations are excluded from the
* output by default because they will only be meaningful once they have been recalculated by GenotypeGVCFs. As
* of version 3.3 this concerns ChromosomeCounts, FisherStrand, StrandOddsRatio and QualByDepth.
*
*/
@Advanced
@Argument(fullName = "excludeAnnotation", shortName = "XA", doc = "One or more specific annotations to exclude", optional = true)
public List<String> annotationsToExclude = new ArrayList<>();
}
| 57.25 | 258 | 0.733067 |
4348d016a36ad058dcf4a147deb2f9ec74fd03fb | 2,315 | package me.robotoraccoon.warden;
import me.robotoraccoon.warden.books.BookEvents;
import me.robotoraccoon.warden.items.ItemEvents;
import me.robotoraccoon.warden.ores.OreEvents;
import me.robotoraccoon.warden.signs.SignEvents;
import me.robotoraccoon.warden.logger.WardenLogger;
import me.robotoraccoon.warden.ores.OreManager;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Logger;
public class Main extends JavaPlugin {
private static Plugin plugin;
// Loggers and log handlers
public static List<Handler> handlers;
public static Logger wardenLog;
private int schedulerId;
public void onEnable() {
plugin = this;
PluginManager pluginManager = getServer().getPluginManager();
// Always save sample. Only save config if it's removed.
getPlugin().saveResource("sampleConfig.yml", true);
if (!new File(getDataFolder() + File.separator + "config.yml").exists())
getPlugin().saveResource("config.yml", false);
getCommand("warden").setExecutor(new Commands());
pluginManager.registerEvents(new BookEvents(), this);
pluginManager.registerEvents(new ItemEvents(), this);
pluginManager.registerEvents(new OreEvents(), this);
pluginManager.registerEvents(new SignEvents(), this);
// Load ores
OreManager.loadOres();
// Logger
if (handlers == null) handlers = new ArrayList<>();
else handlers.clear();
wardenLog = WardenLogger.setupLog(getPlugin(), "warden.log");
// Flush logs to disk every 5 seconds
schedulerId = this.getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> {
Iterator<Handler> i = handlers.iterator();
while (i.hasNext()) {
i.next().flush();
}
}, 60L, 30L);
}
public void onDisable() {
// Kill the logger.
getPlugin().getServer().getScheduler().cancelTask(schedulerId);
WardenLogger.destroyLog(wardenLog);
}
public static Plugin getPlugin() {
return plugin;
}
}
| 30.866667 | 93 | 0.675162 |
8828b33ba52a0249681a73523f670008e4601d9e | 418 | package pclements;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.dataflow.server.EnableDataFlowServer;
@SpringBootApplication
@EnableDataFlowServer
public class AwsLambdaDataflowServer {
public static void main(String[] args) {
SpringApplication.run(AwsLambdaDataflowServer.class, args);
}
} | 27.866667 | 70 | 0.820574 |
fa35615342f1033d55483e4575ffb844f71092dc | 1,359 | package org.erp.tarak.salesorder;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service("salesOrderService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class SalesOrderServiceImpl implements SalesOrderService {
@Autowired
private SalesOrderDao salesOrderDao;
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addSalesOrder(SalesOrder salesOrder) {
salesOrderDao.addSalesOrder(salesOrder);
}
public List<SalesOrder> listSalesOrders(String finYear) {
return salesOrderDao.listSalesOrders(finYear);
}
public SalesOrder getSalesOrder(long salesOrderId,String finYear) {
return salesOrderDao.getSalesOrder(salesOrderId,finYear);
}
public void deleteSalesOrder(SalesOrder salesOrder) {
salesOrderDao.deleteSalesOrder(salesOrder);
}
@Override
public List<SalesOrder> listPendingSalesOrders(String finYear) {
return salesOrderDao.listPendingSalesOrders(finYear);
}
@Override
public List<SalesOrder> listProcessedSalesOrders(String finYear) {
return salesOrderDao.listProcessedSalesOrders(finYear);
}
}
| 30.886364 | 70 | 0.794702 |
0e5d976fde0c8531c851ba1565b251da425d0ce6 | 1,364 | package com.github.kristofa.brave.mysql;
import com.github.kristofa.brave.ClientTracer;
import com.google.common.base.Optional;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
public class MySQLStatementInterceptorManagementBeanTest {
private ClientTracer clientTracer;
@Before
public void setup() {
clientTracer = mock(ClientTracer.class);
}
@After
public void clearStatementInterceptor() {
MySQLStatementInterceptor.setClientTracer(Optional.<ClientTracer>absent());
}
@Test
public void afterPropertiesSetShouldSetTracerOnStatementInterceptor() {
new MySQLStatementInterceptorManagementBean(clientTracer);
assertSame(clientTracer, MySQLStatementInterceptor.clientTracer.get());
}
@Test
public void closeShouldCleanUpStatementInterceptor() throws IOException {
final MySQLStatementInterceptorManagementBean subject = new MySQLStatementInterceptorManagementBean(clientTracer);
MySQLStatementInterceptor.setClientTracer(Optional.of(clientTracer));
subject.close();
assertEquals(Optional.<ClientTracer>absent(), MySQLStatementInterceptor.clientTracer);
}
}
| 28.416667 | 122 | 0.767595 |
e48ea4cac2f3d3c48adaa77ffe3519a096d5859d | 243 | package com.njuzhy.demo.data;
import lombok.Data;
/**
* @Author stormbroken
* Create by 2021/07/07
* @Version 1.0
**/
@Data
public class MySystemInfo {
Double memoryUsage;
Double cpuUsage;
Double diskUsage;
Long time;
}
| 13.5 | 29 | 0.670782 |
e68a285fe9b89e36a045c68c1bfd514a2bc2265c | 138 | package com.hkm.slider.Layouts;
/**
* Created by hesk on 7/3/16.
*/
public abstract class Decor {
public abstract void create();
}
| 15.333333 | 34 | 0.673913 |
49b89d42a6503fcaef434ab086700d774f2cf20d | 693 | package vacheck.demo.service;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vacheck.demo.repository.ConsultaRepository;
import vacheck.demo.model.*;
@Service
public class ConsultaService {
@Autowired
ConsultaRepository consultaRepository;
public List<Consulta> getAll(){
return consultaRepository.findAll();
}
public void save(Consulta c) {
consultaRepository.saveAndFlush(c);
}
public void delete(Integer id) {
consultaRepository.deleteById(id);
}
public Consulta getById(Integer id) {
return consultaRepository.getOne(id);
}
}
| 18.72973 | 62 | 0.730159 |
2f3c86503a8d038ae490d8c86cbb854a2e7af294 | 3,322 | package config;
public class Constants {
private Constants() {
}
public static final String SKIP_UNSTABLE_TESTS = "SKIP_UNSTABLE_TESTS";
// For Socket Mode, Event Auth APIs
public static final String SLACK_SDK_TEST_APP_TOKEN = "SLACK_SDK_TEST_APP_TOKEN";
// Socket Mode
public static final String SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN = "SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN";
public static final String SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN = "SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN";
// --------------------------------------------
// Enterprise Grid
// Workspace admin user's token in Grid
public static final String SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN = "SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN";
// Org admin user's token in Grid
public static final String SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN = "SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN";
// Main team Id for testing
public static final String SLACK_SDK_TEST_GRID_TEAM_ID = "SLACK_SDK_TEST_GRID_TEAM_ID";
// IDP User Group connected to SLACK_SDK_TEST_GRID_TEAM_ID
public static final String SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID = "SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID";
public static final String SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID_2 = "SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID_2";
public static final String SLACK_SDK_TEST_GRID_USER_ID_ADMIN_AUTH = "SLACK_SDK_TEST_GRID_USER_ID_ADMIN_AUTH";
// Shared channel ID for testing with Grid
public static final String SLACK_SDK_TEST_GRID_SHARED_CHANNEL_ID = "SLACK_SDK_TEST_GRID_SHARED_CHANNEL_ID";
public static final String SLACK_SDK_TEST_GRID_SHARED_CHANNEL_OTHER_ORG_USER_ID = "SLACK_SDK_TEST_GRID_SHARED_CHANNEL_OTHER_ORG_USER_ID";
// Org level installed app
public static final String SLACK_SDK_TEST_GRID_ORG_LEVEL_APP_BOT_TOKEN = "SLACK_SDK_TEST_GRID_ORG_LEVEL_APP_BOT_TOKEN";
// --------------------------------------------
// normal user token / bot token
public static final String SLACK_SDK_TEST_USER_TOKEN = "SLACK_SDK_TEST_USER_TOKEN";
public static final String SLACK_SDK_TEST_BOT_TOKEN = "SLACK_SDK_TEST_BOT_TOKEN";
// https://api.slack.com/apps?new_classic_app=1
public static final String SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN = "SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN";
// shared channel tests
public static final String SLACK_SDK_TEST_SHARED_CHANNEL_ID = "SLACK_SDK_TEST_SHARED_CHANNEL_ID";
public static final String SLACK_SDK_TEST_INCOMING_WEBHOOK_URL = "SLACK_SDK_TEST_INCOMING_WEBHOOK_URL";
public static final String SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME = "SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME";
// Slack Connect API tests
public static final String SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN = "SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN";
public static final String SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN = "SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN";
public static final String SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID = "SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID";
public static final String SLACK_SDK_TEST_EMAIL_ADDRESS = "SLACK_SDK_TEST_EMAIL_ADDRESS";
public static final String SLACK_SDK_TEST_REDIS_ENABLED = "SLACK_SDK_TEST_REDIS_ENABLED";
}
| 60.4 | 141 | 0.801023 |
e9fdf40cafb749aaee82599ff6e41c544175e4d0 | 4,475 | package com.isaacsheff.charlotte.node;
import static com.isaacsheff.charlotte.node.PortUtil.getFreshPort;
import static java.util.Collections.emptySet;
import static java.util.Collections.singletonMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.isaacsheff.charlotte.node.CharlotteNodeClient;
import com.isaacsheff.charlotte.proto.Block;
import com.isaacsheff.charlotte.proto.SendBlocksResponse;
import com.isaacsheff.charlotte.yaml.Config;
import com.isaacsheff.charlotte.yaml.Contact;
import com.isaacsheff.charlotte.yaml.GenerateX509;
import com.isaacsheff.charlotte.yaml.JsonConfig;
import com.isaacsheff.charlotte.yaml.JsonContact;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.file.Paths;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.logging.Level;
/**
* Test the CharlotteNodeClient.
* This may use ports 8100 - 8199
* @author Isaac Sheff
*/
public class CharlotteNodeClientTest {
/** Use this for logging events in the class. */
private static final Logger logger = Logger.getLogger(CharlotteNodeClientTest.class.getName());
/** The port used on the dummy server for an individual test. */
private int port;
/**
* Set stuff up before running any tests in this class.
* In this case, generate some crypto key files.
*/
@BeforeAll
static void setup() {
GenerateX509.generateKeyFiles("src/test/resources/server.pem",
"src/test/resources/private-key.pem",
"localhost",
"127.0.0.1");
}
/** launch a dummy server, send 3 blocks to it, and check to see the proper 3 blocks arrived. */
@Test
void sendSomeBlocks() throws InterruptedException {
// calcualte what port to put this server on
port = getFreshPort();
// populate the stack of blocks we expect to receive
final BlockingQueue<Block> receivedBlocks = new ArrayBlockingQueue<Block>(3);
final Config config = (
new Config(new JsonConfig("src/test/resources/private-key.pem",
"localhost",
singletonMap("localhost",
new JsonContact("src/test/resources/server.pem", "localhost", port))
),
Paths.get(".")
));
// create a CharlotteNodeService that queues the blocks received
final CharlotteNodeService service = new CharlotteNodeService(config) {
@Override public Iterable<SendBlocksResponse> onSendBlocksInput(Block block) {
try {
receivedBlocks.put(block);
} catch (InterruptedException e) {
logger.log(Level.SEVERE, "CANNOT RECEIVE BLOCK", e);
}
return emptySet();
}
};
// start up a server on a separate thread with the service
final CharlotteNode charlotteNode = new CharlotteNode(service);
final Thread thread = new Thread(charlotteNode);
thread.start();
TimeUnit.SECONDS.sleep(1); // wait a second for the server to start up
// create a client, and send the expected sequence of blocks
final CharlotteNodeClient client = (new Contact(
new JsonContact("src/test/resources/server.pem", "localhost", port), Paths.get("."), config)).
getCharlotteNodeClient();
client.sendBlock(Block.newBuilder().setStr("block 0").build());
client.sendBlock(Block.newBuilder().setStr("block 1").build());
client.sendBlock(Block.newBuilder().setStr("block 2").build());
// check that the blocks received were the same as the ones sent
assertEquals(Block.newBuilder().setStr("block 0").build(), receivedBlocks.take(),
"block received should match block sent");
assertEquals(Block.newBuilder().setStr("block 1").build(), receivedBlocks.take(),
"block received should match block sent");
assertEquals(Block.newBuilder().setStr("block 2").build(), receivedBlocks.take(),
"block received should match block sent");
// check to ensure no other blocks somehow got queued
assertTrue(receivedBlocks.isEmpty(), "no further blocks should be expected");
// client.shutdown();
// charlotteNode.stop();
}
}
| 41.055046 | 104 | 0.68 |
afb25555e4113d081815820d1256161b46e5fc8f | 7,239 | package test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.nio.channels.Channels;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import de.uni_hildesheim.sse.codeEraser.annotations.Variability;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.EndSystem;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.Monitor;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.StartSystem;
/**
* Perform simple network IO testing of the monitoring infrastructure. This
* class realizes a simple TCP client as well as a simple server over NIO
* channels.<p>
* Monitoring must be enabled via the agent JVM parameter!
*
* @author Robin Gawenda, Yilmaz Eldogan
* @since 1.00
* @version 1.00
*/
@Variability(id = AnnotationId.VAR_TESTING)
@Monitor(id = "netIoTest")
public class NetIoChannelTest {
/**
* Defines the port used for communication operations.
*/
private static final int PORT = 10101;
/**
* The size of an int over the data in/out streams.
*/
private static final int NET_SIZE_INT = 4;
/**
* The overhead of a string over the data in/out streams (size).
*/
private static final int NET_OVERHEAD_STRING = 2;
/**
* Prevents this class from being instantiated from outside.
*
* @since 1.00
*/
private NetIoChannelTest() {
}
/**
* Implements a simple thread for accepting network connections.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.00
*/
private static class ServerMainThread extends Thread {
/**
* Stores the underlying server socket.
*/
private ServerSocketChannel ssc;
/**
* Stores if this thread is ready for accepting connections.
*/
private boolean ready = true;
/**
* Creates a new server thread on the given socket.
*
* @since 1.00
*/
public ServerMainThread() {
try {
ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(PORT));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Executes the thread, i.e. waits for incoming connections. We assume
* that an appropriate SO timeout is set so that this thread my stop
* after certain seconds of no new connection (for graceful end of
* test program).
*/
public void run() {
while (ready) {
try {
SocketChannel sc = ssc.accept();
Thread t = new ServerWorkThread(sc);
t.start();
} catch (SocketTimeoutException e) {
ready = false;
} catch (IOException e) {
System.err.println("error while accepting connection");
e.printStackTrace();
}
}
}
}
/**
* Implements a thread which is started on an accepted connection. This
* thread does the communication work for the server.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.00
*/
private static class ServerWorkThread extends Thread {
/**
* Stores the concrete channel for communication with client.
*/
private SocketChannel channel;
/**
* Creates the working thread for the given socket.
*
* @param channel the channel to communicate on
*
* @since 1.00
*/
public ServerWorkThread(SocketChannel channel) {
this.channel = channel;
}
/**
* Performs the communication work, i.e. receives data according to
* a simple protocol.
*/
public void run() {
try {
DataInputStream in
= new DataInputStream(Channels.newInputStream(channel));
DataOutputStream out
= new DataOutputStream(Channels.newOutputStream(channel));
int totalRead = 0;
int totalWrite = 0;
int count = in.readInt();
totalRead += NET_SIZE_INT;
for (int i = 1; i <= count; i++) {
String string = in.readUTF();
totalRead += TestHelper.getUtfLen(string)
+ NET_OVERHEAD_STRING;
}
out.writeInt(totalRead);
totalWrite += 2 * NET_SIZE_INT;
out.writeInt(totalWrite);
} catch (IOException ioe) {
System.err.println("Error in server thread");
ioe.printStackTrace();
}
}
}
/**
* Starts the server part, executes the client part and prints out the
* results. Currently to be compared manually with the output of the
* monitoring infrastructure.
*
* @param args command line arguments (ignored)
* @throws IOException any kind of network I/O problem in the client
*
* @since 1.00
*/
@StartSystem
@EndSystem
public static void main(String[] args) throws IOException {
String testString = NetIoChannelTest.class.getName();
System.out.println(testString);
System.out.println("Starting server on port " + PORT);
InetSocketAddress addr = new InetSocketAddress(PORT);
ServerMainThread serverThread = new ServerMainThread();
serverThread.start();
// client starts here
SocketChannel sc = SocketChannel.open();
sc.connect(addr);
System.out.println("Client connected on address " + addr);
DataInputStream in = new DataInputStream(
Channels.newInputStream(sc));
DataOutputStream out = new DataOutputStream(
Channels.newOutputStream(sc));
int count = 10;
out.writeInt(count);
int write = NET_SIZE_INT;
for (int i = 1; i <= count; i++) {
out.writeUTF(testString);
write += TestHelper.getUtfLen(testString) + NET_OVERHEAD_STRING;
}
int read = 0;
//Bei folgender Zeile haengt er
int serverRead = in.readInt(); //FEHLER
read += NET_SIZE_INT;
int serverWrite = in.readInt();
read += NET_SIZE_INT;
System.out.println("write " + write + " server " + serverWrite
+ " total " + (write + serverWrite));
System.out.println("read " + read + " server " + serverRead
+ " total " + (read + serverRead));
System.out.println("------------------ done: NetIo");
}
}
| 32.755656 | 79 | 0.550629 |
0a03109c27f5e3625f88708fa1774f41e0120fec | 7,667 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2010, 2012, 2013, 2014, 2016 Synacor, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.common.localconfig;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.python.google.common.base.Strings;
public class LocalConfigTest {
private static LocalConfig localConfig;
@BeforeClass
public static void init() throws Exception {
if (Strings.isNullOrEmpty(System.getProperty("zimbra.config"))) {
System.setProperty("zimbra.config", "../store/src/java-test/localconfig-test.xml");
}
localConfig = LocalConfig.getInstance();
}
@Rule
public TestName TEST_NAME = new TestName();
private String getTestName() {
return TEST_NAME.getMethodName();
}
private String keyName(String suffix) {
return getTestName() + "-" + suffix;
}
private String get(String key) throws ConfigException {
return localConfig.get(key);
}
private String get(KnownKey key) throws ConfigException {
return get(key.key());
}
private void assertEquals(String expected, KnownKey key) {
try {
String actual = get(key);
Assert.assertEquals(expected, actual);
} catch (ConfigException e) {
e.printStackTrace();
Assert.fail();
}
}
private void assertRecursive(KnownKey key) {
boolean caught = false;
try {
get(key);
} catch (ConfigException e) {
Assert.assertTrue(e.getMessage().contains("recursive expansion of key"));
caught = true;
}
Assert.assertTrue(caught);
}
private void assertNullKey(KnownKey key) {
boolean caught = false;
try {
get(key);
} catch (ConfigException e) {
Assert.assertTrue(e.getMessage().contains("null valued key"));
caught = true;
}
Assert.assertTrue(caught);
}
@Test
public void multipleSimple() throws Exception {
KnownKey a = new KnownKey(keyName("a"), String.format("${%s} ${%s}", keyName("b"), keyName("b")));
KnownKey b = new KnownKey(keyName("b"), "123");
assertEquals("123 123", a);
}
@Test
public void multipleDeep() throws Exception {
KnownKey a = new KnownKey(keyName("a"), String.format("${%s} ${%s}", keyName("b"), keyName("b")));
KnownKey b = new KnownKey(keyName("b"), String.format("${%s} ${%s}", keyName("c"), keyName("d")));
KnownKey c = new KnownKey(keyName("c"), String.format("${%s} ${%s}", keyName("d"), keyName("d")));
KnownKey d = new KnownKey(keyName("d"), "123");
assertEquals("123 123 123 123 123 123", a);
assertEquals("123 123 123", b);
assertEquals("123 123", c);
assertEquals("123", d);
}
@Test
public void recursiveContainsSelf() {
KnownKey a = new KnownKey(keyName("a"), String.format("${%s}", keyName("a")));
assertRecursive(a);
}
@Test
public void recursiveContainsMutual() {
KnownKey a = new KnownKey(keyName("a"), String.format("${%s}", keyName("b")));
KnownKey b = new KnownKey(keyName("b"), String.format("${%s}", keyName("a")));
assertRecursive(a);
assertRecursive(b);
}
@Test
public void recursiveContainsLoop() {
KnownKey a = new KnownKey(keyName("a"), String.format("${%s}", keyName("b")));
KnownKey b = new KnownKey(keyName("b"), String.format("${%s}", keyName("c")));
KnownKey c = new KnownKey(keyName("c"), String.format("${%s}", keyName("a")));
assertRecursive(a);
assertRecursive(b);
assertRecursive(c);
}
@Test
public void recursiveContainsSubLoop() {
KnownKey a = new KnownKey(keyName("a"), String.format("${%s}", keyName("b")));
KnownKey b = new KnownKey(keyName("b"), String.format("${%s}", keyName("c")));
KnownKey c = new KnownKey(keyName("c"), String.format("${%s}", keyName("d")));
KnownKey d = new KnownKey(keyName("d"), String.format("hello ${%s}", keyName("b")));
assertRecursive(a);
assertRecursive(b);
assertRecursive(c);
assertRecursive(d);
}
@Test
public void indirect() throws Exception {
KnownKey a = new KnownKey(keyName("a"), "$");
KnownKey b = new KnownKey(keyName("b"), String.format("${%s}{%s}", keyName("a"), keyName("a")));
assertEquals("$", a);
assertEquals("$", b);
KnownKey c = new KnownKey(keyName("c"), "${");
KnownKey d = new KnownKey(keyName("d"), String.format("${%s}%s}", keyName("c"), keyName("c")));
assertEquals("${", c);
assertEquals("${", d);
KnownKey e = new KnownKey(keyName("e"), String.format("${%s", keyName("e")));
KnownKey f = new KnownKey(keyName("f"), String.format("${%s}}", keyName("e")));
assertEquals(String.format("${%s", keyName("e")), e);
assertEquals(String.format("${%s", keyName("e")), f);
}
@Test
public void indirectBad() throws Exception {
KnownKey a = new KnownKey(keyName("a"), "${");
KnownKey b = new KnownKey(keyName("b"), String.format("${%s}%s${%s}", keyName("a"), keyName("a"), keyName("c")));
KnownKey c = new KnownKey(keyName("c"), "}");
assertEquals("${", a);
assertNullKey(b);
assertEquals("}", c);
}
@Test
public void indirectRecursiveContainsSelf() throws Exception {
KnownKey a = new KnownKey(keyName("a"), "${");
KnownKey b = new KnownKey(keyName("b"), String.format("${%s}%s}", keyName("a"), keyName("b")));
assertEquals("${", a);
assertRecursive(b);
}
@Test
public void indirectRecursiveContainsMutual() throws Exception {
KnownKey a = new KnownKey(keyName("a"), "${");
KnownKey b = new KnownKey(keyName("b"), String.format("${%s}%s}", keyName("a"), keyName("c")));
KnownKey c = new KnownKey(keyName("c"), String.format("${%s}", keyName("b")));
assertEquals("${", a);
assertRecursive(b);
assertRecursive(c);
}
@Test
public void indirectRecursiveContainsLoop() throws Exception {
KnownKey a = new KnownKey(keyName("a"), "${");
KnownKey b = new KnownKey(keyName("b"), String.format("${%s}%s}", keyName("a"), keyName("c")));
KnownKey c = new KnownKey(keyName("c"), String.format("${%s}%s}", keyName("a"), keyName("d")));
KnownKey d = new KnownKey(keyName("d"), String.format("${%s}%s}", keyName("a"), keyName("b")));
assertEquals("${", a);
assertRecursive(b);
assertRecursive(c);
assertRecursive(d);
}
}
| 35.331797 | 121 | 0.573758 |
709ad9cb7d78d465c8324720fc089e6f1a662340 | 4,732 | package com.example.erick.bttest;
import java.text.ParseException;
/**
* Created by ERICK on 07.05.2017.
*/
public class StringBuilderToBT {
/*
'h-' — выкл тэна
'h+' — вкл тэн
'p-' — выкл мешалку
'p+' — вкл мешалку
'c...' — задать время
't...' — задать температуру
- на блютуз модуль
*/
private volatile StringBuffer builderString = new StringBuffer("h-$p-$c__:__:__$t__");
//1st symbol
public synchronized void setHealingState(String state) {
switch(state) {
case "ON":
builderString.setCharAt(1, '+');
return;
case "OFF": default:
builderString.setCharAt(1, '-');
return;
}
}
public String getHealingState() {
char state = builderString.charAt(1);
switch (state) {
case '+':
return "ON";
case '-':
return "OFF";
default:
return "ERR";
}
}
/*//3st symbol
public synchronized void setPumpState(String state) {
switch(state) {
case "ON":
builderString.setCharAt(3, '+');
return;
case "OFF": default:
builderString.setCharAt(3, '-');
return;
}
}
public String getPumpState() {
char state = builderString.charAt(3);
switch (state) {
case '+':
return "ON";
case '-':
return "OFF";
default:
return "ERR";
}
}*/
//17-18th symbols
public synchronized void setTemperature(Integer temperature) {
String temperatureString = temperature.toString();
if (Integer.parseInt(temperatureString) > 90) {
System.out.println(temperatureString);
temperatureString = "90";
}
builderString.setCharAt(17, temperatureString.charAt(0));
builderString.setCharAt(18, temperatureString.charAt(1));
}
public Integer getTemperature() throws ParseException{
return Integer.parseInt(builderString.substring(17));
}
//7-8th - hours, 10-11th - minutes, 13-14th - secs
public synchronized void setTime(String time) {
String[] times = time.split("[^A-Za-z0-9]");
switch(times.length) {
case 1:
builderString.setCharAt(7, '0');
builderString.setCharAt(8, '0');
builderString.setCharAt(10, '0');
builderString.setCharAt(11, '0');
if (times[0].length() == 1) {
times[0] = new StringBuilder(times[0].concat("0")).reverse().toString();
}
builderString.setCharAt(13, times[0].charAt(0));
builderString.setCharAt(14, times[0].charAt(1));
return;
case 2:
builderString.setCharAt(7, '0');
builderString.setCharAt(8, '0');
if (times[0].length() == 1) {
times[0] = new StringBuilder(times[0].concat("0")).reverse().toString();
}
builderString.setCharAt(10, times[0].charAt(0));
builderString.setCharAt(11, times[0].charAt(1));
if (times[1].length() == 1) {
times[1] = new StringBuilder(times[1].concat("0")).reverse().toString();
}
builderString.setCharAt(13, times[1].charAt(0));
builderString.setCharAt(14, times[1].charAt(1));
return;
case 3:
if (times[0].length() == 1) {
times[0] = new StringBuilder(times[0].concat("0")).reverse().toString();
}
builderString.setCharAt(7, times[0].charAt(0));
builderString.setCharAt(8, times[0].charAt(1));
if (times[1].length() == 1) {
times[1] = new StringBuilder(times[1].concat("0")).reverse().toString();
}
builderString.setCharAt(10, times[1].charAt(0));
builderString.setCharAt(11, times[1].charAt(1));
if (times[2].length() == 1) {
times[2] = new StringBuilder(times[2].concat("0")).reverse().toString();
}
builderString.setCharAt(13, times[2].charAt(0));
builderString.setCharAt(14, times[2].charAt(1));
return;
}
}
public String getTime() {
return builderString.substring(7, 15);
}
public String getAll() {
return builderString.toString();
}
}
| 34.794118 | 92 | 0.499789 |
b4cfdc09c3a51dec0edc133470d33e1a4db5141e | 145 | package com.example.feature0.export;
import com.blankj.utilcode.util.ApiUtils;
public abstract class Feature0Api extends ApiUtils.BaseApi {
}
| 18.125 | 60 | 0.813793 |
136c93c2853b322c0af4a0b194d1486405ec7f23 | 1,859 | package HealthMonitorMng.util;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AssessAnalysisUtil {
public static Map<String, Double> getAnalysisResult(List<String> totalResult){
int onesum=0;
int twosum=0,threesum=0,foursum=0,fivesum=0;
for(int i=0;i<totalResult.size();i++){
if("1".equals(totalResult.get(i))){
onesum++;
}
if("2".equals(totalResult.get(i))){
twosum++;
}
if("3".equals(totalResult.get(i))){
threesum++;
}
if("4".equals(totalResult.get(i))){
foursum++;
}
if("5".equals(totalResult.get(i))){
fivesum++;
}
}
Map<String, Double> resultMap=new HashMap<String, Double>();
BigDecimal b;
Double onePrecent= ((double)onesum/totalResult.size())*100;
b = new BigDecimal(onePrecent);
onePrecent= b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
Double twoPrecent= ((double)twosum/totalResult.size())*100;
b = new BigDecimal(twoPrecent);
twoPrecent= b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
Double threePrecent=((double)threesum/totalResult.size())*100;
b = new BigDecimal(threePrecent);
threePrecent= b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
Double fourPrecent=((double)foursum/totalResult.size())*100;
b = new BigDecimal(fourPrecent);
fourPrecent= b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
Double fivePrecent=((double)fivesum/totalResult.size())*100;
b = new BigDecimal(fivePrecent);
fivePrecent= b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
resultMap.put("onePrecent", onePrecent);
resultMap.put("twoPrecent", twoPrecent);
resultMap.put("threePrecent", threePrecent);
resultMap.put("fourPrecent", fourPrecent);
resultMap.put("fivePrecent", fivePrecent);
return resultMap;
}
}
| 33.196429 | 80 | 0.699839 |
8d604f3692cef45ab972840fe2e64e56dd30f59c | 21,261 | package com.revature.dao;
import com.revature.dto.AddReimbursementDTO;
import com.revature.model.Reimbursement;
import com.revature.model.User;
import com.revature.utility.ConnectionUtility;
import jdk.nashorn.internal.ir.Assignment;
import java.io.InputStream;
import java.sql.*;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ReimbursementDao {
public Reimbursement reviewReimbursement(int reimbId, int reimResolver, int reimbStatus ) throws SQLException {
try (Connection con = ConnectionUtility.getConnection()) {
con.setAutoCommit(false);
String sql = "UPDATE ers_reimbursement " +
"SET reimb_status_id = ?, " +
"reimb_resolver = ?, " +
"reimb_resolved = ? " +
"WHERE reimb_id = ? ";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, reimbStatus);
pstmt.setInt(2, reimResolver);
pstmt.setTimestamp(3, Timestamp.from(Instant.now()));
pstmt.setInt(4, reimbId);
int status = pstmt.executeUpdate();
String sql2 = "select er.reimb_id as reimbursement_id, " +
"er.reimb_amount as reimbursement_amount, " +
"er.reimb_submitted as date_submitted, " +
"er.reimb_resolved as date_resolved, " +
"er.reimb_description as reimbursement_description, " +
"er.reimb_receipt as reimbursement_receipt, " +
"er.reimb_author as employee_id, " +
"emp_eu.ers_username as employee_username, " +
"emp_eu.ers_password as employee_password, " +
"emp_eu.user_first_name as employee_first_name, " +
"emp_eu.user_last_name as employee_last_name, " +
"emp_eu.user_email as employee_email, " +
"er.reimb_resolver as manager_id, " +
"mgr_eu.ers_username as manager_username, " +
"mgr_eu.ers_password as manager_password, " +
"mgr_eu.user_first_name as manager_first_name, " +
"mgr_eu.user_last_name as manager_last_name, " +
"mgr_eu.user_email as manager_email, " +
"ers.reimb_status as reimbursement_status, " +
"ert.reimb_type as reimbursement_type " +
"FROM ers_reimbursement er " +
"LEFT JOIN ers_users emp_eu " +
"ON emp_eu.ers_users_id = er.reimb_author " +
"LEFT JOIN ers_users mgr_eu " +
"ON mgr_eu.ers_users_id = er.reimb_resolver " +
"LEFT JOIN ers_reimbursement_status ers " +
"ON ers.reimb_status_id = er.reimb_status_id " +
"LEFT JOIN ers_reimbursement_type ert " +
"ON ert.reimb_type_id = er.reimb_type_id " +
"WHERE er.reimb_id = ?";
PreparedStatement pstmt2 = con.prepareStatement(sql2);
pstmt2.setInt(1, reimbId);
ResultSet rs = pstmt2.executeQuery();
rs.next();
// Reimbursement
int rId = rs.getInt("reimbursement_id");
double reimbAmt = rs.getDouble("reimbursement_amount");
Timestamp reimbSubmitted = rs.getTimestamp("date_submitted");
Timestamp reimbResolved = rs.getTimestamp("date_resolved");
String reimbDescription = rs.getString("reimbursement_description");
InputStream reimbReceipt = rs.getBinaryStream("reimbursement_receipt");
// Author
int reimbAuthorId = rs.getInt("employee_id");
String reimbAuthorName = rs.getString("employee_username");
String reimbAuthorPassword = rs.getString("employee_password");
String reimbAuthorFirstName = rs.getString("employee_first_name");
String reimbAuthorLastName = rs.getString("employee_last_name");
String reimbAuthorEmail = rs.getString("employee_email");
String reimbAuthorRole = "Employee";
User reimbAuthor = new User(reimbAuthorId, reimbAuthorName, reimbAuthorPassword, reimbAuthorFirstName, reimbAuthorLastName, reimbAuthorEmail, reimbAuthorRole);
// Resolver
int reimbResolverId = rs.getInt("manager_id");
String reimbResolverName = rs.getString("manager_username");
String reimbResolverPassword = rs.getString("manager_password");
String reimbResolverFirstName = rs.getString("manager_first_name");
String reimbResolverLastName = rs.getString("manager_last_name");
String reimbResolverEmail = rs.getString("manager_email");
String reimbResolverRole = "Manager";
User reimbResolver = new User(reimbResolverId, reimbResolverName, reimbResolverPassword, reimbResolverFirstName, reimbResolverLastName, reimbResolverEmail, reimbResolverRole);
String newReimbStatus = rs.getString("reimbursement_status");
String reimbType = rs.getString("reimbursement_type");
Reimbursement r = new Reimbursement(rId, reimbAmt, reimbSubmitted, reimbResolved, reimbDescription,
reimbReceipt, reimbAuthor, reimbResolver, newReimbStatus, reimbType);
con.commit();
return r;
}
}
public Reimbursement addReimbursement(int userId, AddReimbursementDTO dto) throws SQLException {
try(Connection con = ConnectionUtility.getConnection()){
// con.setAutoCommit(false);
String sql = "INSERT INTO ers_reimbursement " +
"(reimb_amount, reimb_submitted, reimb_description, " +
"reimb_receipt, reimb_author, reimb_type_id) " +
"VALUES (?,?,?,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setDouble(1,dto.getReimbAmount());
pstmt.setTimestamp(2, Timestamp.from(Instant.now()));
pstmt.setString(3, dto.getReimbDescription());
pstmt.setBinaryStream(4, dto.getReimbReceipt());
pstmt.setInt(5,userId);
pstmt.setInt(6,dto.getReimbType());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
int reimbId = rs.getInt(1);
Reimbursement reimbursement = getReimbursementsById(reimbId);
// con.commit();
return reimbursement;
}
}
public List<Reimbursement> getAllReimbursements() throws SQLException {
try(Connection con = ConnectionUtility.getConnection()) {
List<Reimbursement> reimbursements = new ArrayList<>();
String sql = "select er.reimb_id as reimbursement_id, " +
"er.reimb_amount as reimbursement_amount, " +
"er.reimb_submitted as date_submitted, " +
"er.reimb_resolved as date_resolved, " +
"er.reimb_description as reimbursement_description, " +
"er.reimb_receipt as reimbursement_receipt, " +
"er.reimb_author as employee_id, " +
"emp_eu.ers_username as employee_username, " +
"emp_eu.ers_password as employee_password, " +
"emp_eu.user_first_name as employee_first_name, " +
"emp_eu.user_last_name as employee_last_name, " +
"emp_eu.user_email as employee_email, " +
"er.reimb_resolver as manager_id, " +
"mgr_eu.ers_username as manager_username, " +
"mgr_eu.ers_password as manager_password, "+
"mgr_eu.user_first_name as manager_first_name, "+
"mgr_eu.user_last_name as manager_last_name, "+
"mgr_eu.user_email as manager_email, " +
"ers.reimb_status as reimbursement_status, "+
"ert.reimb_type as reimbursement_type "+
"FROM ers_reimbursement er "+
"LEFT JOIN ers_users emp_eu "+
"ON emp_eu.ers_users_id = er.reimb_author "+
"LEFT JOIN ers_users mgr_eu "+
"ON mgr_eu.ers_users_id = er.reimb_resolver "+
"LEFT JOIN ers_reimbursement_status ers "+
"ON ers.reimb_status_id = er.reimb_status_id "+
"LEFT JOIN ers_reimbursement_type ert " +
"ON ert.reimb_type_id = er.reimb_type_id " +
" ORDER BY er.reimb_id";
PreparedStatement ptsmt = con.prepareStatement(sql);
ResultSet rs = ptsmt.executeQuery();
while (rs.next()) {
// Reimbursement
int reimbId = rs.getInt("reimbursement_id");
double reimbAmt = rs.getDouble("reimbursement_amount");
Timestamp reimbSubmitted = rs.getTimestamp("date_submitted");
Timestamp reimbResolved = rs.getTimestamp("date_resolved");
String reimbDescription = rs.getString("reimbursement_description");
InputStream reimbReceipt = rs.getBinaryStream("reimbursement_receipt");
System.out.println(reimbReceipt);
// Author
int reimbAuthorId = rs.getInt("employee_id");
String reimbAuthorName = rs.getString("employee_username");
String reimbAuthorPassword = rs.getString("employee_password");
String reimbAuthorFirstName = rs.getString("employee_first_name");
String reimbAuthorLastName = rs.getString("employee_last_name");
String reimbAuthorEmail = rs.getString("employee_email");
String reimbAuthorRole = "Employee";
User reimbAuthor = new User(reimbAuthorId, reimbAuthorName, reimbAuthorPassword, reimbAuthorFirstName, reimbAuthorLastName, reimbAuthorEmail, reimbAuthorRole);
// Resolver
int reimbResolverId = rs.getInt("manager_id");
String reimbResolverName = rs.getString("manager_username");
String reimbResolverPassword = rs.getString("manager_password");
String reimbResolverFirstName = rs.getString("manager_first_name");
String reimbResolverLastName = rs.getString("manager_last_name");
String reimbResolverEmail = rs.getString("manager_email");
String reimbResolverRole = "Manager";
User reimbResolver = new User(reimbResolverId, reimbResolverName, reimbResolverPassword, reimbResolverFirstName, reimbResolverLastName, reimbResolverEmail, reimbResolverRole);
String reimbStatus = rs.getString("reimbursement_status");
String reimbType = rs.getString("reimbursement_type");
Reimbursement r = new Reimbursement(reimbId, reimbAmt, reimbSubmitted, reimbResolved, reimbDescription,
reimbReceipt, reimbAuthor, reimbResolver, reimbStatus, reimbType);
reimbursements.add(r);
}
return reimbursements;
}
}
public List<Reimbursement> getAllReimbursementsById(int empId) throws SQLException {
try(Connection con = ConnectionUtility.getConnection()) {
List<Reimbursement> reimbursements = new ArrayList<>();
String sql = "select er.reimb_id as reimbursement_id, " +
"er.reimb_amount as reimbursement_amount, " +
"er.reimb_submitted as date_submitted, " +
"er.reimb_resolved as date_resolved, " +
"er.reimb_description as reimbursement_description, " +
"er.reimb_receipt as reimbursement_receipt, " +
"er.reimb_author as employee_id, " +
"emp_eu.ers_username as employee_username, " +
"emp_eu.ers_password as employee_password, " +
"emp_eu.user_first_name as employee_first_name, " +
"emp_eu.user_last_name as employee_last_name, " +
"emp_eu.user_email as employee_email, " +
"er.reimb_resolver as manager_id, " +
"mgr_eu.ers_username as manager_username, " +
"mgr_eu.ers_password as manager_password, "+
"mgr_eu.user_first_name as manager_first_name, "+
"mgr_eu.user_last_name as manager_last_name, "+
"mgr_eu.user_email as manager_email, " +
"ers.reimb_status as reimbursement_status, "+
"ert.reimb_type as reimbursement_type "+
"FROM ers_reimbursement er "+
"LEFT JOIN ers_users emp_eu "+
"ON emp_eu.ers_users_id = er.reimb_author "+
"LEFT JOIN ers_users mgr_eu "+
"ON mgr_eu.ers_users_id = er.reimb_resolver "+
"LEFT JOIN ers_reimbursement_status ers "+
"ON ers.reimb_status_id = er.reimb_status_id "+
"LEFT JOIN ers_reimbursement_type ert " +
"ON ert.reimb_type_id = er.reimb_type_id " +
"WHERE er.reimb_author = ?";
PreparedStatement ptsmt = con.prepareStatement(sql);
ptsmt.setInt(1, empId);
ResultSet rs = ptsmt.executeQuery();
while (rs.next()) {
// Reimbursement
int reimbId = rs.getInt("reimbursement_id");
double reimbAmt = rs.getDouble("reimbursement_amount");
Timestamp reimbSubmitted = rs.getTimestamp("date_submitted");
Timestamp reimbResolved = rs.getTimestamp("date_resolved");
String reimbDescription = rs.getString("reimbursement_description");
InputStream reimbReceipt = rs.getBinaryStream("reimbursement_receipt");
// Author
int reimbAuthorId = rs.getInt("employee_id");
String reimbAuthorName = rs.getString("employee_username");
String reimbAuthorPassword = rs.getString("employee_password");
String reimbAuthorFirstName = rs.getString("employee_first_name");
String reimbAuthorLastName = rs.getString("employee_last_name");
String reimbAuthorEmail = rs.getString("employee_email");
String reimbAuthorRole = "Employee";
User reimbAuthor = new User(reimbAuthorId, reimbAuthorName, reimbAuthorPassword, reimbAuthorFirstName, reimbAuthorLastName, reimbAuthorEmail, reimbAuthorRole);
// Resolver
int reimbResolverId = rs.getInt("manager_id");
String reimbResolverName = rs.getString("manager_username");
String reimbResolverPassword = rs.getString("manager_password");
String reimbResolverFirstName = rs.getString("manager_first_name");
String reimbResolverLastName = rs.getString("manager_last_name");
String reimbResolverEmail = rs.getString("manager_email");
String reimbResolverRole = "Manager";
User reimbResolver = new User(reimbResolverId, reimbResolverName, reimbResolverPassword, reimbResolverFirstName, reimbResolverLastName, reimbResolverEmail, reimbResolverRole);
String reimbStatus = rs.getString("reimbursement_status");
String reimbType = rs.getString("reimbursement_type");
Reimbursement r = new Reimbursement(reimbId, reimbAmt, reimbSubmitted, reimbResolved, reimbDescription,
reimbReceipt, reimbAuthor, reimbResolver, reimbStatus, reimbType);
reimbursements.add(r);
}
return reimbursements;
}
}
public Reimbursement getReimbursementsById(int reimbId) throws SQLException {
try(Connection con = ConnectionUtility.getConnection()) {
String sql = "select er.reimb_id as reimbursement_id, " +
"er.reimb_amount as reimbursement_amount, " +
"er.reimb_submitted as date_submitted, " +
"er.reimb_resolved as date_resolved, " +
"er.reimb_description as reimbursement_description, " +
"er.reimb_receipt as reimbursement_receipt, " +
"er.reimb_author as employee_id, " +
"emp_eu.ers_username as employee_username, " +
"emp_eu.ers_password as employee_password, " +
"emp_eu.user_first_name as employee_first_name, " +
"emp_eu.user_last_name as employee_last_name, " +
"emp_eu.user_email as employee_email, " +
"er.reimb_resolver as manager_id, " +
"mgr_eu.ers_username as manager_username, " +
"mgr_eu.ers_password as manager_password, " +
"mgr_eu.user_first_name as manager_first_name, " +
"mgr_eu.user_last_name as manager_last_name, " +
"mgr_eu.user_email as manager_email, " +
"ers.reimb_status as reimbursement_status, " +
"ert.reimb_type as reimbursement_type " +
"FROM ers_reimbursement er " +
"LEFT JOIN ers_users emp_eu " +
"ON emp_eu.ers_users_id = er.reimb_author " +
"LEFT JOIN ers_users mgr_eu " +
"ON mgr_eu.ers_users_id = er.reimb_resolver " +
"LEFT JOIN ers_reimbursement_status ers " +
"ON ers.reimb_status_id = er.reimb_status_id " +
"LEFT JOIN ers_reimbursement_type ert " +
"ON ert.reimb_type_id = er.reimb_type_id " +
"WHERE er.reimb_id = ?";
PreparedStatement ptsmt = con.prepareStatement(sql);
ptsmt.setInt(1, reimbId);
ResultSet rs = ptsmt.executeQuery();
rs.next();
// Reimbursement
double reimbAmt = rs.getDouble("reimbursement_amount");
Timestamp reimbSubmitted = rs.getTimestamp("date_submitted");
Timestamp reimbResolved = rs.getTimestamp("date_resolved");
String reimbDescription = rs.getString("reimbursement_description");
InputStream reimbReceipt = rs.getBinaryStream("reimbursement_receipt");
// Author
int reimbAuthorId = rs.getInt("employee_id");
String reimbAuthorName = rs.getString("employee_username");
String reimbAuthorPassword = rs.getString("employee_password");
String reimbAuthorFirstName = rs.getString("employee_first_name");
String reimbAuthorLastName = rs.getString("employee_last_name");
String reimbAuthorEmail = rs.getString("employee_email");
String reimbAuthorRole = "Employee";
User reimbAuthor = new User(reimbAuthorId, reimbAuthorName, reimbAuthorPassword, reimbAuthorFirstName, reimbAuthorLastName, reimbAuthorEmail, reimbAuthorRole);
// Resolver
int reimbResolverId = rs.getInt("manager_id");
String reimbResolverName = rs.getString("manager_username");
String reimbResolverPassword = rs.getString("manager_password");
String reimbResolverFirstName = rs.getString("manager_first_name");
String reimbResolverLastName = rs.getString("manager_last_name");
String reimbResolverEmail = rs.getString("manager_email");
String reimbResolverRole = "Manager";
User reimbResolver = new User(reimbResolverId, reimbResolverName, reimbResolverPassword, reimbResolverFirstName, reimbResolverLastName, reimbResolverEmail, reimbResolverRole);
String reimbStatus = rs.getString("reimbursement_status");
String reimbType = rs.getString("reimbursement_type");
Reimbursement r = new Reimbursement(reimbId, reimbAmt, reimbSubmitted, reimbResolved, reimbDescription,
reimbReceipt, reimbAuthor, reimbResolver, reimbStatus, reimbType);
return r;
}
}
public InputStream getReimbursementImage(int reimbId) throws SQLException {
try(Connection con = ConnectionUtility.getConnection()){
String sql = "SELECT er.reimb_receipt " +
" FROM ers_reimbursement er " +
"WHERE er.reimb_id = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1,reimbId);
ResultSet rs = pstmt.executeQuery();
if(rs.next()){
InputStream is = rs.getBinaryStream("reimb_receipt");
return is;
} else {
return null;
}
}
};
}
| 50.742243 | 191 | 0.603688 |
47d4d04b93645911a34177ed8b29cc8181e29368 | 810 | package org.tview.visualization.redis.cache;
import java.util.Map;
import org.tview.visualization.cache.impl.FifoCache;
import org.tview.visualization.model.redis.RedisConnectionConfig;
import org.tview.visualization.redis.singlet.RedisSinglet;
/** @see RedisSinglet#getRedisNameConfigCache() */
public class RedisNameConfigCache extends FifoCache<String, RedisConnectionConfig> {
public RedisNameConfigCache(int size) {
super(size);
}
@Override
public int size() {
return super.size();
}
@Override
public void put(String key, RedisConnectionConfig value) {
super.put(key, value);
}
@Override
public RedisConnectionConfig get(String key) {
return super.get(key);
}
@Override
public Map<String, RedisConnectionConfig> getMap() {
return super.getMap();
}
}
| 23.142857 | 84 | 0.74321 |
76aee747391faf3f62e1ee2de1c2724a41b55feb | 1,896 | package org.acme.DTO;
import java.util.ArrayList;
import java.util.List;
public class Service1DTO {
String vendeur;
int numero_rue;
String adresse;
int code_postal;
int etage;
int porte;
List<String> ancienProprietaires = new ArrayList<>();
public int getNumero_rue() {
return numero_rue;
}
public void setNumero_rue(int num_rue) {
this.numero_rue = num_rue;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public int getCode_postal() {
return code_postal;
}
public void setCode_postal(int code_postal) {
this.code_postal = code_postal;
}
public int getEtage() {
return etage;
}
public void setEtage(int etage) {
this.etage = etage;
}
public int getPorte() {
return porte;
}
public void setPorte(int porte) {
this.porte = porte;
}
public String getVendeur() {
return vendeur;
}
public void setVendeur(String vendeur) {
this.vendeur = vendeur;
}
public List<String> getAncienProprietaires() {
return ancienProprietaires;
}
public void setAncienProprietaires(List<String> ancienProprietaires) {
this.ancienProprietaires = ancienProprietaires;
}
@Override
public String toString() {
return "Service1DTO{" +
"vendeur=" + vendeur +
", numero_rue=" + numero_rue +
", adresse='" + adresse + '\'' +
", code_postal=" + code_postal +
", etage=" + etage +
", porte=" + porte +
", ancienProprietaires=" + ancienProprietaires +
'}';
}
}
| 22.046512 | 75 | 0.544831 |
8d7a4033482b16047166cba28977e85962df62d9 | 8,859 | /**
* Copyright (C) 2014-2015 LinkedIn Corp. ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.pinot.core.data.manager.offline;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.helix.ZNRecord;
import org.apache.helix.store.zk.ZkHelixPropertyStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.linkedin.pinot.common.Utils;
import com.linkedin.pinot.common.config.AbstractTableConfig;
import com.linkedin.pinot.common.metadata.instance.InstanceZKMetadata;
import com.linkedin.pinot.common.metadata.segment.SegmentZKMetadata;
import com.linkedin.pinot.common.segment.SegmentMetadata;
import com.linkedin.pinot.common.segment.SegmentMetadataLoader;
import com.linkedin.pinot.core.data.manager.config.FileBasedInstanceDataManagerConfig;
import com.linkedin.pinot.core.data.manager.config.TableDataManagerConfig;
/**
* InstanceDataManager is the top level DataManger, Singleton.
*
*
*/
public class FileBasedInstanceDataManager implements InstanceDataManager {
private static final FileBasedInstanceDataManager INSTANCE_DATA_MANAGER = new FileBasedInstanceDataManager();
public static final Logger LOGGER = LoggerFactory.getLogger(FileBasedInstanceDataManager.class);
private FileBasedInstanceDataManagerConfig _instanceDataManagerConfig;
private Map<String, TableDataManager> _tableDataManagerMap = new HashMap<String, TableDataManager>();
private boolean _isStarted = false;
private SegmentMetadataLoader _segmentMetadataLoader;
public FileBasedInstanceDataManager() {
//LOGGER.info("InstanceDataManager is a Singleton");
}
public static FileBasedInstanceDataManager getInstanceDataManager() {
return INSTANCE_DATA_MANAGER;
}
public synchronized void init(FileBasedInstanceDataManagerConfig instanceDataManagerConfig)
throws ConfigurationException, InstantiationException, IllegalAccessException, ClassNotFoundException {
_instanceDataManagerConfig = instanceDataManagerConfig;
for (String tableName : _instanceDataManagerConfig.getTableNames()) {
TableDataManagerConfig tableDataManagerConfig =
_instanceDataManagerConfig.getTableDataManagerConfig(tableName);
TableDataManager tableDataManager = TableDataManagerProvider.getTableDataManager(tableDataManagerConfig);
_tableDataManagerMap.put(tableName, tableDataManager);
}
_segmentMetadataLoader = getSegmentMetadataLoader(_instanceDataManagerConfig.getSegmentMetadataLoaderClass());
}
@Override
public synchronized void init(Configuration dataManagerConfig) {
try {
_instanceDataManagerConfig = new FileBasedInstanceDataManagerConfig(dataManagerConfig);
} catch (Exception e) {
_instanceDataManagerConfig = null;
LOGGER.error("Error during InstanceDataManager initialization", e);
Utils.rethrowException(e);
}
for (String tableName : _instanceDataManagerConfig.getTableNames()) {
TableDataManagerConfig tableDataManagerConfig =
_instanceDataManagerConfig.getTableDataManagerConfig(tableName);
TableDataManager tableDataManager = TableDataManagerProvider.getTableDataManager(tableDataManagerConfig);
_tableDataManagerMap.put(tableName, tableDataManager);
}
try {
_segmentMetadataLoader = getSegmentMetadataLoader(_instanceDataManagerConfig.getSegmentMetadataLoaderClass());
LOGGER.info("Loaded SegmentMetadataLoader for class name : "
+ _instanceDataManagerConfig.getSegmentMetadataLoaderClass());
} catch (Exception e) {
LOGGER.error(
"Cannot initialize SegmentMetadataLoader for class name : "
+ _instanceDataManagerConfig.getSegmentMetadataLoaderClass(), e);
Utils.rethrowException(e);
}
}
private SegmentMetadataLoader getSegmentMetadataLoader(String segmentMetadataLoaderClassName)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return (SegmentMetadataLoader) Class.forName(segmentMetadataLoaderClassName).newInstance();
}
@Override
public synchronized void start() {
for (TableDataManager tableDataManager : _tableDataManagerMap.values()) {
tableDataManager.start();
}
try {
bootstrapSegmentsFromSegmentDir();
} catch (Exception e) {
LOGGER.error(
"Error in bootstrap segment from dir : " + _instanceDataManagerConfig.getInstanceBootstrapSegmentDir(), e);
}
_isStarted = true;
LOGGER.info("InstanceDataManager is started!");
}
private void bootstrapSegmentsFromSegmentDir() throws Exception {
if (_instanceDataManagerConfig.getInstanceBootstrapSegmentDir() != null) {
File bootstrapSegmentDir = new File(_instanceDataManagerConfig.getInstanceBootstrapSegmentDir());
if (bootstrapSegmentDir.exists()) {
for (File segment : bootstrapSegmentDir.listFiles()) {
addSegment(_segmentMetadataLoader.load(segment), null);
LOGGER.info("Bootstrapped segment from directory : " + segment.getAbsolutePath());
}
} else {
LOGGER.info("Bootstrap segment directory : " + _instanceDataManagerConfig.getInstanceBootstrapSegmentDir()
+ " doesn't exist.");
}
} else {
LOGGER.info("Config of bootstrap segment directory hasn't been set.");
}
}
@Override
public boolean isStarted() {
return _isStarted;
}
public synchronized void addTableDataManager(String tableName, TableDataManager tableDataManager) {
_tableDataManagerMap.put(tableName, tableDataManager);
}
public Collection<TableDataManager> getTableDataManagers() {
return _tableDataManagerMap.values();
}
@Override
public TableDataManager getTableDataManager(String tableName) {
return _tableDataManagerMap.get(tableName);
}
@Override
public synchronized void shutDown() {
if (isStarted()) {
for (TableDataManager tableDataManager : getTableDataManagers()) {
tableDataManager.shutDown();
}
_isStarted = false;
LOGGER.info("InstanceDataManager is shutDown!");
} else {
LOGGER.warn("InstanceDataManager is already shutDown, won't do anything!");
}
}
@Override
public synchronized void addSegment(SegmentMetadata segmentMetadata, AbstractTableConfig tableConfig) throws Exception {
String tableName = segmentMetadata.getTableName();
LOGGER.info("Trying to add segment : " + segmentMetadata.getName());
if (_tableDataManagerMap.containsKey(tableName)) {
_tableDataManagerMap.get(tableName).addSegment(segmentMetadata);
LOGGER.info("Added a segment : " + segmentMetadata.getName() + " to table : " + tableName);
} else {
LOGGER.error("InstanceDataManager doesn't contain the assigned table for segment : "
+ segmentMetadata.getName());
}
}
@Override
public synchronized void removeSegment(String segmentName) {
throw new UnsupportedOperationException();
}
@Override
public void refreshSegment(String oldSegmentName, SegmentMetadata newSegmentMetadata) {
throw new UnsupportedOperationException();
}
@Override
public String getSegmentDataDirectory() {
return _instanceDataManagerConfig.getInstanceDataDir();
}
@Override
public String getSegmentFileDirectory() {
return _instanceDataManagerConfig.getInstanceSegmentTarDir();
}
@Override
public SegmentMetadataLoader getSegmentMetadataLoader() {
return _segmentMetadataLoader;
}
@Override
public SegmentMetadata getSegmentMetadata(String table, String segmentName) {
if (_tableDataManagerMap.containsKey(table)) {
if (_tableDataManagerMap.get(table).acquireSegment(segmentName) != null) {
return _tableDataManagerMap.get(table).acquireSegment(segmentName).getSegment().getSegmentMetadata();
}
}
return null;
}
@Override
public void addSegment(ZkHelixPropertyStore<ZNRecord> propertyStore, AbstractTableConfig tableConfig,
InstanceZKMetadata instanceZKMetadata, SegmentZKMetadata segmentZKMetadata) throws Exception {
throw new UnsupportedOperationException("Not support addSegment(...) in FileBasedInstanceDataManager yet!");
}
}
| 38.855263 | 122 | 0.763517 |
07ee7e6abe59f0a2b283301f2ee4a9529aba2e82 | 6,693 | /**
* 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.s4.core;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import org.apache.s4.base.Emitter;
import org.apache.s4.base.Event;
import org.apache.s4.base.Hasher;
import org.apache.s4.base.Sender;
import org.apache.s4.base.SerializerDeserializer;
import org.apache.s4.comm.topology.Assignment;
import org.apache.s4.comm.topology.Cluster;
import org.apache.s4.comm.topology.ClusterChangeListener;
import org.apache.s4.comm.topology.ClusterNode;
import org.apache.s4.core.staging.SenderExecutorServiceFactory;
import org.apache.s4.core.util.S4Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
/**
* The {@link SenderImpl} and its counterpart {@link ReceiverImpl} are the top level classes of the communication layer.
* <p>
* {@link SenderImpl} is responsible for sending an event to a {@link ProcessingElement} instance using a hashKey.
* <p>
* Details on how the cluster is partitioned and how events are serialized and transmitted to its destination are hidden
* from the application developer.
*/
public class SenderImpl implements Sender, ClusterChangeListener {
private static Logger logger = LoggerFactory.getLogger(SenderImpl.class);
final private Emitter emitter;
final private SerializerDeserializer serDeser;
final private Hasher hasher;
private final Cluster cluster;
Assignment assignment;
private int localPartitionId = -1;
private final ExecutorService tpe;
@Inject
S4Metrics metrics;
/**
*
* @param emitter
* the emitter implements the low level communication layer.
* @param serDeser
* a serialization mechanism.
* @param hasher
* a hashing function to map keys to partition IDs.
* @param assignment
* partition assignment from the cluster manager
* @param senderExecutorServiceFactory
* factory for creating sender executors
* @param cluster
* cluster information
*/
@Inject
public SenderImpl(Emitter emitter, SerializerDeserializer serDeser, Hasher hasher, Assignment assignment,
SenderExecutorServiceFactory senderExecutorServiceFactory, Cluster cluster) {
this.emitter = emitter;
this.serDeser = serDeser;
this.hasher = hasher;
this.assignment = assignment;
this.tpe = senderExecutorServiceFactory.create();
this.cluster = cluster;
}
@Inject
private void init() {
cluster.addListener(this);
resolveLocalPartitionId();
}
private void resolveLocalPartitionId() {
ClusterNode node = assignment.assignClusterNode();
if (node != null) {
localPartitionId = node.getPartition();
}
}
/*
* (non-Javadoc)
*
* @see org.apache.s4.core.Sender#checkAndSendIfNotLocal(java.lang.String, org.apache.s4.base.Event)
*/
@Override
public boolean checkAndSendIfNotLocal(String hashKey, Event event) {
//int partition = (int) (hasher.hash(hashKey) % emitter.getPartitionCount());
int partition = emitter.getPartitionByConsistentHashing(hashKey);
if (partition == localPartitionId) {
metrics.sentLocal();
/* Hey we are in the same JVM, don't use the network. */
return false;
}
send(partition, event);
metrics.sentEvent(partition);
return true;
}
private void send(int partition, Event event) {
tpe.submit(new SerializeAndSendToRemotePartitionTask(event, partition));
}
/*
* (non-Javadoc)
*
* @see org.apache.s4.core.Sender#sendToRemotePartitions(org.apache.s4.base.Event)
*/
@Override
public void sendToAllRemotePartitions(Event event) {
tpe.submit(new SerializeAndSendToAllRemotePartitionsTask(event));
}
class SerializeAndSendToRemotePartitionTask implements Runnable {
Event event;
int remotePartitionId;
public SerializeAndSendToRemotePartitionTask(Event event, int remotePartitionId) {
this.event = event;
this.remotePartitionId = remotePartitionId;
}
@Override
public void run() {
ByteBuffer serializedEvent = serDeser.serialize(event);
try {
emitter.send(remotePartitionId, serializedEvent);
} catch (InterruptedException e) {
logger.error("Interrupted blocking send operation for event {}. Event is lost.", event);
Thread.currentThread().interrupt();
}
}
}
class SerializeAndSendToAllRemotePartitionsTask implements Runnable {
Event event;
public SerializeAndSendToAllRemotePartitionsTask(Event event) {
super();
this.event = event;
}
@Override
public void run() {
ByteBuffer serializedEvent = serDeser.serialize(event);
for (int i = 0; i < emitter.getPartitionCount(); i++) {
/* Don't use the comm layer when we send to the same partition. */
if (localPartitionId != i) {
try {
emitter.send(i, serializedEvent);
metrics.sentEvent(i);
} catch (InterruptedException e) {
logger.error("Interrupted blocking send operation for event {}. Event is lost.", event);
// no reason to continue: we were interrupted, so we reset the interrupt status and leave
Thread.currentThread().interrupt();
break;
}
}
}
}
}
@Override
public void onChange() {
resolveLocalPartitionId();
}
}
| 33.465 | 120 | 0.652323 |
60c1dd57d949da1f65330ed24592942d4ff079cf | 1,255 | package org.xlattice.crypto.u;
import java.io.File;
import java.io.IOException;
/**
* @author Jim Dixon
*/
public class Walker {
private final Visitor _v;
private final String _pathToU;
private File _uDir;
public Walker( Visitor v, final String pathToU ) throws IOException {
if (v == null)
throw new IllegalArgumentException("null visitor");
_v = v;
if (pathToU == null || pathToU.equals(""))
throw new IllegalArgumentException("null or empty pathToU");
_pathToU = pathToU;
_uDir = new File(_pathToU);
if (!_uDir.exists())
throw new IllegalArgumentException (_pathToU + " does not exist ");
}
private void walkDir(File dir) throws IOException {
File listFile[] = dir.listFiles();
if(listFile != null) {
for(int i=0; i<listFile.length; i++) {
if(listFile[i].isDirectory()) {
walkDir(listFile[i]);
} else {
_v.visitFile(listFile[i].getPath());
}
}
}
}
public void walk() throws IOException {
_v.enterU(_pathToU);
walkDir(new File(_pathToU));
_v.exitU();
}
}
| 27.888889 | 79 | 0.550598 |
d7948ea67c085f16e8c3fe2f11b28894e4b5ec28 | 2,852 | /*
* 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.openmeetings.web.admin.labels;
import java.util.Date;
import org.apache.openmeetings.db.dao.label.FieldLanguageDao;
import org.apache.openmeetings.db.entity.label.FieldLanguage;
import org.apache.openmeetings.web.app.Application;
import org.apache.openmeetings.web.app.WebSession;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
/**
*
* @author solomax, swagner
*
*/
public class AddLanguageForm extends Form<Void> {
private static final long serialVersionUID = 8743289610974962636L;
private String newLanguageName;
private String newLanguageISO;
public AddLanguageForm(String id, final LangPanel langPanel) {
super(id);
add(new RequiredTextField<String>("name", new PropertyModel<String>(this, "newLanguageName")));
add(new RequiredTextField<String>("iso", new PropertyModel<String>(this, "newLanguageISO")));
add(new AjaxButton("add", Model.of(WebSession.getString(366L)), this) {
private static final long serialVersionUID = -552597041751688740L;
@Override
public void onSubmit(AjaxRequestTarget target, Form<?> form) {
FieldLanguageDao langDao = Application.getBean(FieldLanguageDao.class);
FieldLanguage fl = new FieldLanguage();
fl.setLanguage_id(langDao.getNextAvailableId());
fl.setStarttime(new Date());
fl.setDeleted(false);
fl.setName(newLanguageName);
fl.setRtl(false); //FIXME
fl.setCode(newLanguageISO);
try {
langDao.updateLanguage(fl);
} catch (Exception e) {
// TODO add feedback message
e.printStackTrace();
}
langPanel.getLangForm().updateLanguages(target);
/* FIXME
languages.setChoices(langDao.getLanguages());
target.add(languages);
*/
target.appendJavaScript("$('#addLanguage').dialog('close');");
}
});
}
}
| 34.780488 | 97 | 0.743338 |
d51c235d79c55d4f172ef559a06e993266c38e43 | 717 | package de.atomfrede.mate.service.email;
import static org.fest.assertions.api.Assertions.*;
import org.apache.commons.configuration.ConfigurationException;
import org.junit.Test;
import de.atomfrede.mate.service.email.MailConfig;
public class MailConfigTest {
@Test
public void assertThatPropertiesCanBeCreated() throws ConfigurationException {
MailConfig config = new MailConfig();
assertThat(config.from()).isEqualTo("[email protected]");
assertThat(config.host()).isEqualTo("smtp.gmail.com");
assertThat(config.password()).isEqualTo("dummyPassword");
assertThat(config.port()).isEqualTo(465);
assertThat(config.ssl()).isTrue();
assertThat(config.user()).isEqualTo("dummyUser");
}
}
| 28.68 | 79 | 0.76848 |
36bd91af325c8a13d0ee482877b1d3ead336c003 | 973 | package x.xx.leetcode.all;
import java.util.ArrayList;
import java.util.List;
/**
* 找出所有相加之和为 n 的 k 个数的组合。
* 组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
*/
public class P216CombinationSumIII {
List<List<Integer>> ans = new ArrayList<>();
int[] nums = new int[]{1,2,3,4,5,6,7,8,9};
public List<List<Integer>> combinationSum3(int k, int n) {
dfs(n, k, 0, new ArrayList<>());
return ans;
}
void dfs(int t, int k, int i, List<Integer> a) {
if( t== 0 && k == 0) ans.add(new ArrayList<>(a));
if( t < 0 || k < 0) return;
for (int j = i; j < 9; j++) {
if(nums[j] <= t && k > 0){
a.add(nums[j]);
dfs(t - nums[j], k - 1, j + 1, a);
a.remove(a.size() - 1);
}else{
return;
}
}
}
public static void main(String[] args) {
System.out.println(new P216CombinationSumIII().combinationSum3(3, 7));
}
}
| 26.297297 | 78 | 0.498458 |
f76f518dd5d84e1b7fa3bd5d73ecdf9abfa0b6a2 | 727 | package cn.itcast.ssm.po;
public class SysRolePermission {
private String id;
private String sysRoleId;
private String sysPermissionId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getSysRoleId() {
return sysRoleId;
}
public void setSysRoleId(String sysRoleId) {
this.sysRoleId = sysRoleId == null ? null : sysRoleId.trim();
}
public String getSysPermissionId() {
return sysPermissionId;
}
public void setSysPermissionId(String sysPermissionId) {
this.sysPermissionId = sysPermissionId == null ? null : sysPermissionId.trim();
}
} | 22.030303 | 87 | 0.636864 |
12bcb1240051ea7961f403f0a86301378498701e | 2,717 | package ru.spbstu.icc.kspt.kuznetsov.tictactoe;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import ru.spbstu.icc.kspt.kuznetsov.tictactoe.gamemodel.GameModelFragment;
public class GameActivity extends Activity implements GameModelFragment.OnFragmentInteractionListener{
private static final String FTAG_MODELFRAGMENT = "tag.fragment.gamemodel";
private GameFieldAdapter adapter;
private AIAsyncTask ai = null;
private GameModelFragment modelFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_field);
FragmentManager fm = getFragmentManager();
modelFragment = (GameModelFragment) fm.findFragmentByTag(FTAG_MODELFRAGMENT);
if (modelFragment == null){
modelFragment = GameModelFragment.newInstance((MainActivity.LAUNCH_MODES) getIntent().getSerializableExtra(MainActivity.KEY_LAUNCH_MODE));
fm.beginTransaction().add(modelFragment, FTAG_MODELFRAGMENT).commit();
}
GridView gridview = (GridView) findViewById(R.id.gridView);
gridview.setNumColumns(modelFragment.getModel().getSz());
adapter = new GameFieldAdapter(this, modelFragment.getModel());
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
switch (modelFragment.getCurrentPlayer()) {
case GAME_OVER:
Toast.makeText(GameActivity.this, R.string.dialog_game_over, Toast.LENGTH_SHORT).show();
break;
case COMPUTER:
Toast.makeText(GameActivity.this, R.string.wait_your_turn, Toast.LENGTH_SHORT).show();
break;
case HUMAN:
modelFragment.makeMoveHuman(position);
adapter.notifyDataSetChanged();
break;
}
}
});
}
@Override
public void onGameOver() {
new GameOverDialogFragment().show(getFragmentManager(), "game_over");
}
@Override
public void onComputerMoved() {
adapter.notifyDataSetChanged();
}
@Override
public void onComputerGiveUp() {
Toast.makeText(this, R.string.give_up, Toast.LENGTH_SHORT).show();
}
}
| 38.814286 | 151 | 0.646669 |
d2e53830e3951cec927b5351d8272098e42e989f | 3,475 | package org.stowers.microscopy.converter;
import ij.ImagePlus;
import ij.plugin.ZProjector;
import org.scijava.command.Command;
import org.scijava.command.Previewable;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import loci.plugins.BF;
import org.stowers.microscopy.ij1plugins.FastFileSaver;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by cjw on 4/26/17.
*/
@Plugin(type = Command.class, name = "Batch Z-Project", menuPath="Plugins>Stowers>Chris>Batch Project")
public class BatchProjectPlugin implements Command, Previewable {
@Parameter(label = "Select a directory to project", style="directory")
File inputDir;
String inputDirString;
@Parameter(label="Select a directory to save to", style="directory")
File saveToDir;
String saveToDirString;
@Parameter(label="Select a method", choices={"MAX","SUM","AVERAGE"})
String method;
List<String> goodExt;
int zMethod = -1;
@Override
public void run() {
if (method.equals("MAX")) {
zMethod = ZProjector.MAX_METHOD;
} else if (method.equals("SUM")) {
zMethod = ZProjector.SUM_METHOD;
} else if (method.equals("AVERAGE")) {
zMethod = ZProjector.AVG_METHOD;
} else {
zMethod = ZProjector.SUM_METHOD;
}
inputDirString = inputDir.getAbsolutePath();
if (!inputDirString.endsWith("/")) {
inputDirString += "/";
}
saveToDirString = saveToDir.getAbsolutePath();
if (!saveToDirString.endsWith("/")) {
saveToDirString += "/";
}
goodExt = new ArrayList<>();
goodExt.add("tif");
goodExt.add("tiff");
goodExt.add("nd2");
goodExt.add("dv");
goodExt.add("lsm");
goodExt.add("cvi");
String inputname = inputDir.getAbsolutePath();
String savename = saveToDir.getAbsolutePath();
String[] filenames = inputDir.list();
for (int i = 0; i < filenames.length; i++) {
String f = filenames[i];
String ext = f.substring(f.lastIndexOf(".") + 1, f.length());
if (goodExt.contains(ext)) {
System.out.println(f);
projectFile(f);
}
}
}
protected void projectFile(String filename) {
String projectedFileName = newFileName(filename);
String f = inputDirString + filename;
ImagePlus[] imps = null;
ImagePlus imp = null;
try {
imps = BF.openImagePlus(f);
imp = imps[0];
}
catch(Exception e) {
e.printStackTrace();
return;
}
int nc = imp.getNChannels();
int nt = imp.getNFrames();
int nz = imp.getStackSize()/nc/nt;
ZProjector zproj = new ZProjector(imp);
zproj.setStartSlice(1);
zproj.setStopSlice(nz);
zproj.setMethod(zMethod);
zproj.doHyperStackProjection(true);
ImagePlus projected = zproj.getProjection();
FastFileSaver saver = new FastFileSaver(projected);
saver.saveAsTiff(projectedFileName);
return;
}
protected String newFileName(String filename) {
String res = saveToDirString + method + "_" + filename + ".tif";
return res;
}
@Override
public void preview() {
}
@Override
public void cancel() {
}
}
| 25.740741 | 104 | 0.59482 |
76c20cb3c3dfa478b3a757fd3cbe835a242729a0 | 416 | package com.anooky.testproject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class GotoAnooky {
@Test
public void visitAnooky() {
System.setProperty("webdriver.gecko.driver", "./geckodriver");
WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.anooky.com");
driver.quit();
}
}
| 21.894737 | 65 | 0.71875 |
98255a4d0ce51ac8deb41dfcbf582b66249d93de | 761 | package io.gridgo.utils.pojo.setter.data;
public interface GenericData {
default boolean isNull() {
return false;
}
default boolean isSequence() {
return false;
}
default boolean isKeyValue() {
return false;
}
default boolean isPrimitive() {
return false;
}
default boolean isReference() {
return false;
}
default KeyValueData asKeyValue() {
return (KeyValueData) this;
}
default SequenceData asSequence() {
return (SequenceData) this;
}
default PrimitiveData asPrimitive() {
return (PrimitiveData) this;
}
default ReferenceData asReference() {
return (ReferenceData) this;
}
Object getInnerValue();
}
| 17.697674 | 41 | 0.607096 |
b6e64b735ba640958067f9a2a4c8720139fa5c24 | 660 | package guru.springframework.sfgpetclinic.services.map;
import guru.springframework.sfgpetclinic.model.Pet;
import guru.springframework.sfgpetclinic.services.PetService;
import java.util.Set;
public class PetMapService extends AbstractMapService<Pet, Long> implements PetService {
@Override
public Set<Pet> findAll() {
return super.findAll();
}
@Override
public Pet findById(Long id) {
return super.findById(id);
}
@Override
public Pet save(Pet object) {
return super.save(object);
}
@Override
public void delete(Pet object) {
super.delete(object);
}
@Override
public void deleteById(Long id) {
super.deleteById(id);
}
}
| 18.333333 | 88 | 0.743939 |
085f57e276fe64fe0760c83d300805c8d724d05d | 4,269 | package com.HuaQiangWeather.App.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.HuaQiangWeather.App.R;
import com.bumptech.glide.Glide;
public class WxWeb extends AppCompatActivity {
private AppBarLayout ab_appbar;
private CollapsingToolbarLayout ctb_CollapsingToolbarLayout;
private ImageView iv_newsImg;
private TextView tv_newsTitle,tv_newsSource;
private WebView wv_webview;
private Toolbar tb_toolbar;
private FloatingActionButton fab_collect;
private String newstitle;
private String newsSource;
private String newsUrl;
private String newsImg;
public static void startAction(Context context,String newtitle,String newsSource,String newsUrl,String newsImg){
Intent intent = new Intent(context,WxWeb.class);
intent.putExtra("newstitle",newtitle);
intent.putExtra("newsSource",newsSource);
intent.putExtra("newsUrl",newsUrl);
intent.putExtra("newsImg",newsImg);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wx_web);
initView();
if (getIntent()!=null){
Intent newsData = getIntent();
newstitle = newsData.getStringExtra("newstitle");
newsSource = newsData.getStringExtra("newsSource");
newsUrl = newsData.getStringExtra("newsUrl");
newsImg = newsData.getStringExtra("newsImg");
}else Toast.makeText(this, "未获得上一页面数据", Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
super.onResume();
ViewBindData();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
}
return true;
}
private void ViewBindData() {
Glide.with(WxWeb.this).load(newsImg).into(iv_newsImg);
tv_newsTitle.setText(newstitle);
tv_newsSource.setText("来自:"+newsSource);
wv_webview.loadUrl(newsUrl);
fab_collect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(v,"已收藏!",Snackbar.LENGTH_LONG)
.setAction("返回", new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
}).show();
}
});
}
private void initView() {
ab_appbar = (AppBarLayout) findViewById(R.id.ab_appbar);
ctb_CollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.ctb_CollapsingToolbarLayout);
iv_newsImg = (ImageView) findViewById(R.id.iv_newsImg);
tv_newsTitle = (TextView) findViewById(R.id.tv_newsTitle);
tv_newsSource = (TextView) findViewById(R.id.tv_newsSource);
wv_webview = (WebView) findViewById(R.id.wv_webview);
wv_webview.setWebViewClient(new WebViewClient());
wv_webview.getSettings().setJavaScriptEnabled(true);
tb_toolbar = (Toolbar) findViewById(R.id.tb_toolbar);
setSupportActionBar(tb_toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
ctb_CollapsingToolbarLayout.setTitle("微信精选");
fab_collect = (FloatingActionButton) findViewById(R.id.fab_collect);
}
}
| 35.87395 | 116 | 0.668072 |
4f8efa20d38738794f09be42452712afd5dbdbbd | 334 | package chp02;
public class SumAve1 {
public static void main(String[] args) {
int x = 63;
int y = 18;
System.out.println("x的值是" + x + "。");
System.out.println("y的值是" + y + "。");
System.out.println("合计值是" + (x + y) + "。");
System.out.println("平均值是" + (x + y) / 2 + "。");
}
}
| 22.266667 | 55 | 0.476048 |
dfc63535c23fffe9f23f5a1014f41f12735b21f5 | 651 | package com.google.common.collect;
import java.util.Collection;
import java.util.Set;
import javax.annotation.Nullable;
final class TreeRangeSet$AsRanges extends ForwardingCollection<Range<C>> implements Set<Range<C>> {
final /* synthetic */ TreeRangeSet this$0;
TreeRangeSet$AsRanges(TreeRangeSet treeRangeSet) {
this.this$0 = treeRangeSet;
}
protected Collection<Range<C>> delegate() {
return this.this$0.rangesByLowerBound.values();
}
public int hashCode() {
return Sets.hashCodeImpl(this);
}
public boolean equals(@Nullable Object o) {
return Sets.equalsImpl(this, o);
}
}
| 25.038462 | 99 | 0.69278 |
b39cabc7925d618a05a79c70f4af2f70648981dc | 5,481 | /*
* org.riverock.portlet - Portlet Library
*
* Copyright (C) 2006, Riverock Software, All Rights Reserved.
*
* Riverock - The Open-source Java Development Community
* http://www.riverock.org
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.riverock.portlet.manager.site.action;
import java.io.Serializable;
import org.apache.log4j.Logger;
import org.riverock.portlet.main.AuthSessionBean;
import org.riverock.portlet.manager.site.DataProvider;
import org.riverock.portlet.manager.site.SiteSessionBean;
import org.riverock.portlet.manager.site.bean.XsltBean;
import org.riverock.portlet.tools.FacesTools;
import org.riverock.common.utils.PortletUtils;
/**
* @author Sergei Maslyukov
* 16.05.2006
* 20:14:59
*
*
*/
public class XsltAction implements Serializable {
private final static Logger log = Logger.getLogger( XsltAction.class );
private static final long serialVersionUID = 2057005511L;
private SiteSessionBean siteSessionBean = null;
private AuthSessionBean authSessionBean = null;
private DataProvider dataProvider = null;
public static final String[] ROLES = new String[]{"webmill.authentic"};
public XsltAction() {
}
public void setDataProvider(DataProvider dataProvider) {
this.dataProvider = dataProvider;
}
// getter/setter methods
public void setSiteSessionBean( SiteSessionBean siteSessionBean) {
this.siteSessionBean = siteSessionBean;
}
public AuthSessionBean getAuthSessionBean() {
return authSessionBean;
}
public void setAuthSessionBean( AuthSessionBean authSessionBean) {
this.authSessionBean = authSessionBean;
}
// main select action
public String selectXslt() {
log.info( "Select xslt action." );
loadCurrentObject();
return "site";
}
// Add actions
public String addXsltAction() {
log.info( "Add xslt action." );
XsltBean xsltBean = new XsltBean();
xsltBean.setSiteLanguageId(siteSessionBean.getId());
setSessionObject(xsltBean);
return "xslt-add";
}
public String processAddXsltAction() {
log.info( "Procss add xslt action." );
PortletUtils.checkRights(FacesTools.getPortletRequest(), ROLES);
if( getSessionObject() !=null ) {
Long xsltId = FacesTools.getPortalSpiProvider().getPortalXsltDao().createXslt(
getSessionObject()
);
setSessionObject(null);
siteSessionBean.setId(xsltId);
cleadDataProviderObject();
loadCurrentObject();
}
return "site";
}
public String cancelAddXsltAction() {
log.info( "Cancel add xslt action." );
setSessionObject(null);
cleadDataProviderObject();
return "site";
}
// Edit actions
public String editXsltAction() {
log.info( "Edit holding action." );
return "xslt-edit";
}
public String processEditXsltAction() {
log.info( "Save changes xslt action." );
PortletUtils.checkRights(FacesTools.getPortletRequest(), ROLES);
if( getSessionObject() !=null ) {
FacesTools.getPortalSpiProvider().getPortalXsltDao().updateXslt(getSessionObject());
cleadDataProviderObject();
loadCurrentObject();
}
return "site";
}
public String cancelEditXsltAction() {
log.info( "Cancel edit xslt action." );
loadCurrentObject();
return "site";
}
// Delete actions
public String deleteXsltAction() {
log.info( "delete xslt action." );
setSessionObject( new XsltBean(dataProvider.getXslt()) );
return "xslt-delete";
}
public String cancelDeleteXsltAction() {
log.info( "Cancel delete holding action." );
return "site";
}
public String processDeleteXsltAction() {
log.info( "Process delete xslt action." );
PortletUtils.checkRights(FacesTools.getPortletRequest(), ROLES);
if( getSessionObject() != null ) {
FacesTools.getPortalSpiProvider().getPortalXsltDao().deleteXslt(getSessionObject().getId());
setSessionObject(null);
siteSessionBean.setId(null);
siteSessionBean.setObjectType(SiteSessionBean.UNKNOWN_TYPE);
cleadDataProviderObject();
}
return "site";
}
private void setSessionObject(XsltBean bean) {
siteSessionBean.setXslt( bean );
}
private void loadCurrentObject() {
siteSessionBean.setXslt( new XsltBean(dataProvider.getXslt()) );
}
private void cleadDataProviderObject() {
dataProvider.clearXslt();
}
private XsltBean getSessionObject() {
return siteSessionBean.getXslt();
}
}
| 28.107692 | 104 | 0.667032 |
2572c390c7a6c51aa5b17b28a498f766f561786a | 554 | package com.gridgain.example;
public class CityKey {
private Integer id;
private String CountryCode;
public CityKey(Integer id, String countryCode) {
this.id = id;
CountryCode = countryCode;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCountryCode() {
return CountryCode;
}
public void setCountryCode(String countryCode) {
CountryCode = countryCode;
}
@Override
public String toString() {
return "City [id=" + id + ", CountryCode=" + CountryCode + "]";
}
}
| 16.294118 | 65 | 0.685921 |
fb452324a92584147df2b21a464c2d536d18ac5b | 4,121 | package com.github.appreciated.mvp;
import com.googlecode.gentyref.GenericTypeReflector;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Composite;
import com.vaadin.flow.internal.ReflectTools;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/*
* Copyright Vaadin
* Copyright appreciated
*
* 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.
*
*/
/**
* Instead of adding the @{@link com.vaadin.flow.router.Route} Annotations to the Views, they should be added to the
* {@link Presenter} class, the View should be the Wildcard of the the {@link Presenter}. Since the {@link Presenter}
* is derived from {@link Composite} make sure to give it's documentation a read, it has some restrictions. The user is
* not required to instantiate the model and neither the view, this will be done automatically by {@link Presenter}
* respectively {@link Composite}. The Model can be instantiated using the custom constructor.
* <p>
* The MVP Pattern consists of three "roles"
* Model - providing
* View - displaying
* Presenter - communicator
* <p>
* In Vaadin a "View" are usually represented by classes that are derived from {@link Component} (but it can be argued
* that a {@link Component} is not always a view). For the sake of simplicity this is being ignored.
* The classes {@link Model} and {@link Presenter} are not represented in Vaadin since it is a UI-Framework after all.
*
* @param <M> Wildcard that is required to implement {@link Model}.
* @param <V> Wildcard that is required to extend {@link Component}.
*/
public abstract class Presenter<M extends Model<M>, V extends Component> extends Composite<V> {
private M model;
/**
* Constructor to initialise the {@link Model} automatically.
*/
public Presenter() {
model = initModel();
}
/**
* Called when the constructor of this {@link Presenter} is called.
* <p>
* This method initializes the {@link Model} and returns it.
* <p>
* By default, this method uses reflection to instantiate the {@link Model}
* based on the generic type of the sub class.
*
* @return the {@link Model} of the {@link Presenter} never {@code null}
* <p>
* Code + comment is from {@link Composite#initContent()} (See Copyright notice) and modified to initialize the Model.
*/
@SuppressWarnings("unchecked")
protected M initModel() {
return (M) ReflectTools.createInstance(findContentType((Class<? extends Presenter<?, ?>>) this.getClass()));
}
/**
* Code taken from {@link Composite#findContentType(Class)} (See Copyright notice) and modified to initialize the Model instead.
*
* @param modelClass
* @return
*/
private static Class<? extends Model> findContentType(Class<? extends Presenter<?, ?>> modelClass) {
Type type = GenericTypeReflector.getTypeParameter(modelClass.getGenericSuperclass(), Presenter.class.getTypeParameters()[0]);
if (!(type instanceof Class) && !(type instanceof ParameterizedType)) {
throw new IllegalStateException("Presenter is used as raw type: either add type information or override initModel().");
} else {
return GenericTypeReflector.erase(type).asSubclass(Model.class);
}
}
/**
* Constructor to initialise the {@link Model} manually.
*
* @param model the model to inject into the {@link Presenter}
*/
public Presenter(M model) {
this.model = model;
}
public M getModel() {
return model;
}
}
| 40.009709 | 133 | 0.692308 |
f49d12ff1f31b075f8de7b066a58b6d83405c23a | 1,416 | package org.errai.mvp.client.local.common.mvp;
import java.lang.annotation.Annotation;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.errai.mvp.client.local.common.mvp.places.EntryPlace;
import org.errai.mvp.client.local.common.mvp.places.PlaceManager;
import org.errai.mvp.client.local.common.mvp.places.PlaceRequest;
import org.errai.mvp.client.shared.common.mvp.Presenter;
import org.jboss.errai.ioc.client.api.EntryPoint;
import org.jboss.errai.ioc.client.container.IOCBeanDef;
import org.jboss.errai.ioc.client.container.SyncBeanManager;
import org.jboss.errai.ui.nav.client.local.DefaultPage;
import org.jboss.errai.ui.nav.client.local.Page;
import com.google.gwt.user.client.ui.Composite;
@EntryPoint
@Page(role = DefaultPage.class)
public class Root extends Composite {
@Inject
private PlaceManager placeManager;
@Inject
private SyncBeanManager beanManager;
@PostConstruct
public void init() {
EntryPlace annotation = new EntryPlace() {
@Override
public Class<? extends Annotation> annotationType() {
return EntryPlace.class;
}
};
IOCBeanDef<? extends Presenter> bean = beanManager.lookupBean(Presenter.class, annotation);
Presenter presenter = bean.getInstance();
placeManager.reveal(new PlaceRequest.Builder().to(presenter.getPlace()).build());
}
}
| 34.536585 | 99 | 0.739407 |
f791c469e78340839fd248b18c4fb1ddc2822c2a | 1,142 | // Copyright © 2011-2019 Andy Goryachev <[email protected]>
package goryachev.common.io;
import java.io.EOFException;
public class BitStream
implements IBitStream
{
private byte[] bytes;
private int index;
private static final int[] MASK =
{
0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01
};
public BitStream(byte[] bytes)
{
this.bytes = bytes;
}
public int getIndex()
{
return index;
}
public boolean hasMoreBits()
{
return (index < (bytes.length * 8));
}
public int nextBits(int count) throws Exception
{
int d = 0;
while(count > 0)
{
d = (d << 1) | nextBit();
--count;
}
return d;
}
public int nextBit() throws Exception
{
int byteIndex = index/8;
if(byteIndex >= bytes.length)
{
throw new EOFException();
}
int offset = index - (byteIndex * 8);
index++;
if((MASK[offset] & bytes[byteIndex]) == 0)
{
return 0;
}
else
{
return 1;
}
}
public void skip(int bits)
{
if(bits < 0)
{
throw new IllegalArgumentException();
}
index += bits;
}
}
| 14.641026 | 61 | 0.56655 |
293398f82239d9fd1fb03886032ebd8a2e844d9d | 624 | package com.holub.database;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.xml.sax.SAXException;
import com.holub.database.XMLImporter;
import com.holub.database.ConcreteTable;
import com.holub.database.Database;
import com.holub.database.Table;
public class XMLImporterTest {
@Test
public void testExport() throws IOException, ParserConfigurationException, SAXException {
// Create Database.
Database db = new Database("c:/dp2020");
// Create Table for test.
Table t = new ConcreteTable(new XMLImporter("c:/dp2020/test.xml"));
}
}
| 24 | 90 | 0.772436 |
0c45368e63cd5fcfcae53e834d65f5be61e0c3fc | 273 | package com.jt.blog.mapper;
import com.jt.blog.dto.CategoryDto;
import com.jt.blog.model.Category;
import com.jt.blog.mybatis.common.MyMapper;
import java.util.List;
public interface CategoryMapper extends MyMapper<Category> {
List<CategoryDto> getListAndCount();
} | 22.75 | 60 | 0.787546 |
e7eafe9a8702bd57336f2afea54a66d54e352345 | 916 | package org.jeecg.modules.business.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.modules.business.entity.SiteGovFacility;
import org.jeecg.modules.business.entity.SiteMonitorDevice;
import org.jeecg.modules.business.mapper.SiteGovFacilityMapper;
import org.jeecg.modules.business.service.ISiteGovFacilityService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
/**
* @Description: 监测站治理设施
* @Author: jeecg-boot
* @Date: 2020-07-08
* @Version: V1.0
*/
@Service
public class SiteGovFacilityServiceImpl extends ServiceImpl<SiteGovFacilityMapper, SiteGovFacility> implements ISiteGovFacilityService {
@Override
public Integer findCount(String monitorId) {
return this.count(new QueryWrapper<SiteGovFacility>().lambda().eq(SiteGovFacility::getMonitorId,monitorId));
}
}
| 35.230769 | 136 | 0.804585 |
33e05d429b4e085ca1d22fbc7bf28feb9b9564b7 | 6,686 | package aitoa.algorithms;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Random;
import aitoa.structure.IBinarySearchOperator;
import aitoa.structure.IBlackBoxProcess;
import aitoa.structure.INullarySearchOperator;
import aitoa.structure.ISpace;
import aitoa.structure.IUnarySearchOperator;
import aitoa.structure.LogFormat;
import aitoa.structure.Metaheuristic2;
import aitoa.structure.Record;
import aitoa.utils.Experiment;
import aitoa.utils.RandomUtils;
/**
* An {@linkplain aitoa.algorithms.EA evolutionary algorithm}
* which restarts every couple of generations.
*
* @param <X>
* the search space
* @param <Y>
* the solution space
*/
public final class EAWithRestarts<X, Y>
extends Metaheuristic2<X, Y> {
/** the crossover rate */
public final double cr;
/** the number of selected parents */
public final int mu;
/** the number of offsprings per generation */
public final int lambda;
/**
* the number of generations without improvement until restart
*/
public final int generationsUntilRestart;
/**
* Create a new instance of the evolutionary algorithm
*
* @param pNullary
* the nullary search operator.
* @param pUnary
* the unary search operator
* @param pBinary
* the binary search operator
* @param pCr
* the crossover rate
* @param pMu
* the number of parents to be selected
* @param pLambda
* the number of offspring to be created
* @param pGenerationsUntilRestart
* the number of generations without improvement until
* restart
*/
public EAWithRestarts(final INullarySearchOperator<X> pNullary,
final IUnarySearchOperator<X> pUnary,
final IBinarySearchOperator<X> pBinary, final double pCr,
final int pMu, final int pLambda,
final int pGenerationsUntilRestart) {
super(pNullary, pUnary, pBinary);
if ((pCr < 0d) || (pCr > 1d) || (!(Double.isFinite(pCr)))) {
throw new IllegalArgumentException(
"Invalid crossover rate: " + pCr); //$NON-NLS-1$
}
this.cr = pCr;
if ((pMu < 1) || (pMu > 1_000_000)) {
throw new IllegalArgumentException(//
"Invalid mu: " + pMu); //$NON-NLS-1$
}
if ((pMu <= 1) && (pCr > 0d)) {
throw new IllegalArgumentException(//
"crossover rate must be 0 if mu is 1, but cr is " //$NON-NLS-1$
+ pCr);
}
this.mu = pMu;
if ((pLambda < 1) || (pLambda > 1_000_000)) {
throw new IllegalArgumentException(
"Invalid lambda: " + pLambda); //$NON-NLS-1$
}
this.lambda = pLambda;
if ((pGenerationsUntilRestart < 1)
|| (pGenerationsUntilRestart > 1_000_000)) {
throw new IllegalArgumentException(
"Invalid generationsUntilRestart: " //$NON-NLS-1$
+ pGenerationsUntilRestart);
}
this.generationsUntilRestart = pGenerationsUntilRestart;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
public void solve(final IBlackBoxProcess<X, Y> process) {
// create local variables
final Random random = process.getRandom();
final ISpace<X> searchSpace = process.getSearchSpace();
int p2;
final Record<X>[] P = new Record[this.mu + this.lambda];
while (!process.shouldTerminate()) { // restart
double bestF = Double.POSITIVE_INFINITY;
int nonImprovedGen = 0;
// first generation: fill population with random solutions
for (int i = P.length; (--i) >= 0;) {
final X x = searchSpace.create();
this.nullary.apply(x, random);
P[i] = new Record<>(x, process.evaluate(x));
if (process.shouldTerminate()) {
return;
}
}
while (nonImprovedGen < this.generationsUntilRestart) {
// main loop: one iteration = one generation
++nonImprovedGen; // assume no improvement
// sort the P: mu best records at front are selected
Arrays.sort(P, Record.BY_QUALITY);
// shuffle mating pool to ensure fairness if lambda<mu
RandomUtils.shuffle(random, P, 0, this.mu);
int p1 = -1; // index to iterate over first parent
// overwrite the worse lambda solutions with new offsprings
for (int index = P.length; (--index) >= this.mu;) {
if (process.shouldTerminate()) {
return; // return best solution
}
final Record<X> dest = P[index];
p1 = (p1 + 1) % this.mu;
final Record<X> parent1 = P[p1];
if (random.nextDouble() <= this.cr) { // crossover!
do { // find a second parent who is different from
p2 = random.nextInt(this.mu);
} while (p2 == p1);
this.binary.apply(parent1.x, P[p2].x, dest.x,
random);
} else { // otherwise create modified copy of p1
this.unary.apply(parent1.x, dest.x, random);
}
// map to solution/schedule and evaluate
dest.quality = process.evaluate(dest.x);
if (dest.quality < bestF) { // we improved
bestF = dest.quality; // remember best quality
nonImprovedGen = 0; // reset non-improved generation
}
} // the end of the offspring generation
} // the end of the generation loop
} // end of the main loop for independent restarts
}
/** {@inheritDoc} */
@Override
public void printSetup(final Writer output)
throws IOException {
output.write(LogFormat.mapEntry(//
LogFormat.SETUP_BASE_ALGORITHM, "ea")); //$NON-NLS-1$
output.write(System.lineSeparator());
super.printSetup(output);
output.write(LogFormat.mapEntry("mu", this.mu));///$NON-NLS-1$
output.write(System.lineSeparator());
output.write(LogFormat.mapEntry("lambda", this.lambda));//$NON-NLS-1$
output.write(System.lineSeparator());
output.write(LogFormat.mapEntry("cr", this.cr));//$NON-NLS-1$
output.write(System.lineSeparator());
output.write(LogFormat.mapEntry("clearing", false)); //$NON-NLS-1$
output.write(System.lineSeparator());
output.write(LogFormat.mapEntry("restarts", true)); //$NON-NLS-1$
output.write(System.lineSeparator());
output.write(LogFormat.mapEntry("generationsUntilRestart", //$NON-NLS-1$
this.generationsUntilRestart));
output.write(System.lineSeparator());
}
/** {@inheritDoc} */
@Override
public String toString() {
return Experiment.nameFromObjectsMerge(((((((("ea_rs_" + //$NON-NLS-1$
this.mu) + '+') + this.lambda) + '@') + this.cr) + '_')
+ this.generationsUntilRestart), this.unary,
this.binary);
}
}
| 34.112245 | 76 | 0.63102 |
4ec4f7f62da4a2f1d76678251d7d67907fc095d5 | 1,593 | /**
* Copyright 2006 Mark Miller ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mhs.qsol;
public class Util {
/**
* Utility method to dynamically load classes
*
* @param lclass
* @return
* @throws LoadException
*/
public static Object loadClass(final String lclass) {
Object loadedClass = null;
Class handlerClass = null;
try {
handlerClass = Class.forName(lclass);
} catch (final NoClassDefFoundError e) {
throw new RuntimeException("Cannot find class : " + lclass, e);
} catch (final ClassNotFoundException e) {
throw new RuntimeException("Cannot find class : " + lclass, e);
}
try {
loadedClass = handlerClass.newInstance();
} catch (final InstantiationException e) {
throw new RuntimeException("Cannot create instance of : " + lclass, e);
} catch (final IllegalAccessException e) {
throw new RuntimeException("Cannot create instance of : " + lclass, e);
}
return loadedClass;
}
}
| 32.510204 | 78 | 0.667922 |
cb53e67c60d984bc97b60e71f15efb9a1da5c519 | 503 | package kitkat.auth.repository;
import kitkat.auth.model.entity.AuthRoleToAuthorities;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface AuthRoleToAuthoritiesRepository extends CrudRepository<AuthRoleToAuthorities, UUID> {
Optional<AuthRoleToAuthorities> findByRole(@Param("role") String authRole);
}
| 31.4375 | 102 | 0.840954 |
db640628930a70a9e7ac40323433c9043dfb56f5 | 860 | package org.apache.spark.ml.feature;
/**
* Class that represents an instance of weighted data point with label and features.
* <p>
* param: label Label for this data point.
* param: weight The weight of this instance.
* param: features The vector of features for this data point.
*/
class Instance implements scala.Product, scala.Serializable {
static public abstract R apply (T1 v1, T2 v2, T3 v3) ;
static public java.lang.String toString () { throw new RuntimeException(); }
public double label () { throw new RuntimeException(); }
public double weight () { throw new RuntimeException(); }
public org.apache.spark.ml.linalg.Vector features () { throw new RuntimeException(); }
// not preceding
public Instance (double label, double weight, org.apache.spark.ml.linalg.Vector features) { throw new RuntimeException(); }
}
| 47.777778 | 128 | 0.718605 |
f08b5e2f00147ff2078791a12c3c6f565b54456c | 548 | package io.github.edmm.web.model;
import java.util.ArrayList;
import java.util.UUID;
import javax.validation.constraints.NotEmpty;
import io.github.edmm.plugins.multi.model.ComponentProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DeployRequest {
@NotEmpty
private String modelId;
private UUID correlationId;
@NotEmpty
private ArrayList<String> components;
private ArrayList<ComponentProperties> inputs;
}
| 18.266667 | 62 | 0.790146 |
25363dec690f9afc0afea6fc22b9258b74e9ac5c | 1,726 | package __TOP_LEVEL_PACKAGE__.client.scaffold.ioc;
import __TOP_LEVEL_PACKAGE__.client.managed.request.ApplicationRequestFactory;
import __TOP_LEVEL_PACKAGE__.client.scaffold.request.EventSourceRequestTransport;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.gwt.place.shared.PlaceController;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
__GAE_IMPORT__
public class ScaffoldModule extends AbstractGinModule {
@Override
protected void configure() {
bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
bind(ApplicationRequestFactory.class).toProvider(RequestFactoryProvider.class).in(Singleton.class);
bind(PlaceController.class).toProvider(PlaceControllerProvider.class).in(Singleton.class);
}
static class PlaceControllerProvider implements Provider<PlaceController> {
private final PlaceController placeController;
@Inject
public PlaceControllerProvider(EventBus eventBus) {
this.placeController = new PlaceController(eventBus);
}
public PlaceController get() {
return placeController;
}
}
static class RequestFactoryProvider implements Provider<ApplicationRequestFactory> {
private final ApplicationRequestFactory requestFactory;
@Inject
public RequestFactoryProvider(EventBus eventBus) {
requestFactory = GWT.create(ApplicationRequestFactory.class);
requestFactory.initialize(eventBus, new EventSourceRequestTransport(eventBus__GAE_REQUEST_TRANSPORT__));
}
public ApplicationRequestFactory get() {
return requestFactory;
}
}
}
| 33.843137 | 107 | 0.823291 |
dcf9dbe78594bfc85c34ed63b92f6fd073b55056 | 1,294 | package com.github.rskupnik;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
public class Response {
private boolean error;
private String url;
private String image;
private String ext;
private String filename;
private String delete;
private Integer size;
public boolean isError() {
return error;
}
public void setError(boolean error) {
this.error = error;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getDelete() {
return delete;
}
public void setDelete(String delete) {
this.delete = delete;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
}
| 17.972222 | 61 | 0.600464 |
81564583ef2a1877ddaa8dfdecfda9a8cec62180 | 5,146 | //package listeners;
//
//import net.dv8tion.jda.core.EmbedBuilder;
//import net.dv8tion.jda.core.entities.Guild;
//import net.dv8tion.jda.core.entities.Message;
//import net.dv8tion.jda.core.events.guild.GuildJoinEvent;
//import net.dv8tion.jda.core.events.message.priv.PrivateMessageReceivedEvent;
//import net.dv8tion.jda.core.hooks.ListenerAdapter;
//import utils.STATICS;
//
//import java.awt.*;
//import java.io.*;
//import java.util.*;
//import java.util.List;
//
///**
// * Created by zekro on 19.08.2017 / 11:53
// * DiscordBot.listeners
// * dev.zekro.de - github.zekro.de
// * © zekro 2017
// */
//
//
//public class ServerLimitListener extends ListenerAdapter {
//
// private Timer timer = new Timer();
//
// private List<String> wildcards;
//
//
// private List<String> getWilrdcards() {
//
// List<String> out = new ArrayList<>();
//
// try {
// BufferedReader br = new BufferedReader(new FileReader("WILDCARDS.txt"));
// br.lines().forEach(s -> {
// if (!s.startsWith("#") && !s.isEmpty())
// out.add(s.replace("\n", ""));
// });
// br.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// return out;
// }
//
// private void updateWildcards(String usedone) {
// List<String> cards = getWilrdcards();
// cards.remove(usedone);
// try {
// BufferedWriter br = new BufferedWriter(new FileWriter("WILDCARDS.txt"));
// cards.forEach(s -> {
// try {
// br.write(s + "\n");
// } catch (IOException e) {}
// });
// br.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
//
// private static String generateToken() {
// final String tokenchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
// StringBuilder sb = new StringBuilder().append("token_");
// for (int i = 0; i <= 8; i++)
// sb.append(tokenchars.charAt(new Random().nextInt(tokenchars.length())));
// return sb.toString();
// }
//
// public static void createTokenList(int ammount) {
// try {
// BufferedWriter bw = new BufferedWriter(new FileWriter("WILDCARDS.txt"));
// bw.write("# Here you can add or remove tokens. \n# Just empty the file if you don't want to enable token system.\n\n");
// for (int i = 0; i <= ammount; i++)
// bw.write(generateToken() + "\n");
// bw.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
//
//
// @Override
// public void onGuildJoin(GuildJoinEvent event) {
//
// Guild guild = event.getGuild();
// wildcards = getWilrdcards();
//
// if (guild.getJDA().getGuilds().size() > STATICS.SERVER_LIMIT) {
// guild.getOwner().getUser().openPrivateChannel().queue(pc -> pc.sendMessage(
// new EmbedBuilder().setColor(Color.ORANGE).setTitle("Server Limit Reached", null).setDescription(
// "Sorry, but because of currently limited resources the bot is limited to run on maximum " + STATICS.SERVER_LIMIT + " Servers.\n\n" +
// "If you have a wildcard, you can send the token via PM to zekroBot.\n" +
// "Otherwise, the bot will leave the server automatically after 2 minutes."
// ).build()
// ).queue());
// timer.schedule(new TimerTask() {
// @Override
// public void run() {
// guild.leave().queue();
// }
// }, 120000);
// }
//
// }
//
// @Override
// public void onPrivateMessageReceived(PrivateMessageReceivedEvent event) {
//
// String content = event.getMessage().getContent();
// Message msg = event.getMessage();
//
// if (content.startsWith("token_")) {
//
// String entered = content.replaceAll(" ", "");
// if (wildcards.contains(entered)) {
// timer.cancel();
// timer = new Timer();
// updateWildcards(entered);
// msg.getAuthor().openPrivateChannel().complete().sendMessage(new EmbedBuilder().setColor(Color.green).setDescription(
// "Access granted!\n" +
// "You'll now have access to all functions of this bot.\n\n" +
// "ATTENTION: If you kick the bot from your guild, you will need a new token and the old one got invalid!"
// ).build()).queue();
// } else {
// msg.getAuthor().openPrivateChannel().complete().sendMessage(new EmbedBuilder().setColor(Color.red).setDescription(
// "The entered token is invalid!\n\n" +
// "Try to re-enter the token. The bot will be kicked automatically after time has expired."
// ).build()).queue();
// }
//
// }
// }
//
//}
| 36.496454 | 162 | 0.536533 |
02d14dc6393e16e5880fe3ef84483e8daae58254 | 12,346 | package frc.robot.vision;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import frc.robot.subsystems.TankDrive;
/**
* <p><a href="https://github.com/KHS-Robotics/MoePi">MoePi</a> UDP Client to get
* retroreflective tape data for Destination: Deep Space.</p>
*/
public class MoePiClient implements Runnable {
/** Default UDP Port for MoePi. */
public static final int DEFAULT_UDP_PORT = 5810;
/** x-resolution of the camera */
public static final double RESOLUTION_X = 640;
/** y-resolution of the camera */
public static final double RESOLUTION_Y = 480;
/** Diagonal Field of View for the Camera. */
public static final double DIAGONAL_FIELD_OF_VIEW = 68.5;
/** Horizontal Field of View for the Camera. */
public static final double HORIZONTAL_FIELD_OF_VIEW = 57.5;
/** Width between the two target's x-coordinates in inches. */
public static final double TARGET_WIDTH = 11.5;
// MoePi status codes
public static final short STATUS_NONE_FOUND = (short) 1;
public static final short STATUS_ONE_FOUND = (short) 2;
public static final short STATUS_TWO_FOUND = (short) 3;
public static final short STATUS_THREE_FOUND = (short) 4;
public static final short STATUS_FOUR_FOUND = (short) 5;
public static final short STATUS_FIVE_FOUND = (short) 6;
public static final short STATUS_SIX_FOUND = (short) 7;
public static final short STATUS_ERROR = (short) 0x8000;
public static final short STATUS_HELLO = (short) 0x8001;
public static final short STATUS_GOODBYE = (short) 0x8002;
/** The size of the buffer for MoePi, in bytes. */
public static final int BUFFER_SIZE = 246;
public static final double CENTER_X = 0.40;
private double currentRobotHeading, lastRobotHeading;
private DeepSpaceVisionTarget centerTarget;
private int lastID;
private DatagramSocket socket;
private volatile ArrayList<Box> boxVector;
private volatile ArrayList<DeepSpaceVisionTarget> targetVector;
public final String Name;
public final int Port;
private final TankDrive Drive;
/**
* Constructs a new <code>MoePiClient</code>.
* @throws SocketException if the socket could not be opened,
* or the socket could not bind to the specified local port
*/
public MoePiClient(TankDrive drive) throws SocketException {
this("MoePi", DEFAULT_UDP_PORT, drive);
}
/**
* Constructs a new <code>MoePiClient</code>.
* @param name the name of this specific <code>MoePiClient</code>
* @param port the port to retrieve UDP data from
* @throws SocketException if the socket could not be opened,
* or the socket could not bind to the specified local port
*/
public MoePiClient(String name, int port, TankDrive drive) throws SocketException {
this.Name = name;
this.Port = port;
this.Drive = drive;
socket = new DatagramSocket(port);
boxVector = new ArrayList<Box>();
targetVector = new ArrayList<>();
new Thread(this).start();
}
/**
* <p>Continuously updates MoePi telemetry.</p>
* {@inheritDoc}
*/
@Override
public void run() {
ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
DatagramPacket packet = new DatagramPacket(buf.array(), buf.limit());
while(true) {
try {
buf.position(0);
packet.setLength(buf.limit());
socket.receive(packet);
final int id = buf.getInt();
final int status = buf.getShort();
if(status == STATUS_HELLO) {
lastID = id;
continue;
}
if(id <= lastID) {
continue;
}
lastID = id;
final int boxAmnt = status - 1;
synchronized(this) {
boxVector.clear();
for(int n = 0; n < boxAmnt; n++) {
boxVector.add(readBox(buf));
}
lastRobotHeading = currentRobotHeading;
currentRobotHeading = Drive.getHeading();
this.updateCenterTarget();
}
} catch (Exception ex) {
ex.printStackTrace();
break;
}
}
socket.close();
}
/**
* Reads a box from the <code>ByteBuffer</code>.
* @param buf the <code>ByteBuffer</code> to read from
* @return the next box in the <code>ByteBuffer</code>
*/
private Box readBox(ByteBuffer buf) {
double x = buf.getDouble();
double y = buf.getDouble();
double w = buf.getDouble();
double h = buf.getDouble();
double type = buf.getDouble();
return new Box((x + w / 2), (y + h / 2), w, h, type);
}
public synchronized ArrayList<Box> getBoxes() {
return boxVector;
}
public synchronized ArrayList<DeepSpaceVisionTarget> getTargets() {
return targetVector;
}
public synchronized DeepSpaceVisionTarget getCenterTarget() {
return centerTarget;
}
public synchronized boolean hasTarget() {
return centerTarget != null;
}
public synchronized double getLastRobotHeading() {
return lastRobotHeading;
}
public synchronized double getRobotHeading() {
return currentRobotHeading;
}
/**
* Gets the angle offset of the most centered <code>DeepSpaceVisionTarget</code>
* and adds <code>offset</code> to it.
* @param offset the amount to add to {@link MoePiClient#getAngle()}
* @return the sum of {@link MoePiClient#getAngle()} and <code>offset</code>
* @see MoePiClient#getAngle()
*/
public synchronized double getAngle(double offset) {
return this.getAngle() + offset;
}
/**
* Gets the angle offset of the most centered <code>DeepSpaceVisionTarget</code>.
* @return the angle offset of the most centered <code>DeepSpaceVisionTarget</code>
* @see MoePiClient#updateCenterTarget()
* @see MoePiClient#getAngle(double)
*/
public synchronized double getAngle() {
try {
if(centerTarget == null) {
return 0;
}
return HORIZONTAL_FIELD_OF_VIEW*(centerTarget.x - 0.5);
} catch(Exception ex) {
ex.printStackTrace();
return 0;
}
}
/**
* Gets the distance of the most centered <code>DeepSpaceVisionTarget</code> in inches.
* @return the distance of the most centered <code>DeepSpaceVisionTarget</code> in inches
* @see MoePiClient#updateCenterTarget()
*/
public synchronized double getDistance() {
try {
if(centerTarget == null || (centerTarget != null && centerTarget.hasOnlyRight())) {
return 0;
}
double theta = HORIZONTAL_FIELD_OF_VIEW*Math.abs(centerTarget.left.x - centerTarget.right.x);
// splitting triangle in half to make a right triangle means:
// tan(theta/2) = width/2 / distance
// distance = width / 2*tan(theta/2)
return TARGET_WIDTH / (2 * Math.tan(Math.toRadians(theta / 2.0)));
} catch(Exception ex) {
ex.printStackTrace();
return 0;
}
}
/**
* Updates the most centered <code>DeepSpaceVisionTarget</code>.
* @see DeepSpaceVisionTarget
* @see MoePiClient#updateDeepSpaceTargets()
*/
private synchronized void updateCenterTarget() {
this.updateDeepSpaceTargets();
if(targetVector.isEmpty()) {
centerTarget = null;
}
else if(targetVector.size() == 1) {
centerTarget = targetVector.get(0);
}
else {
// start assuming first target is most centered
int centerBoxIndex = 0;
DeepSpaceVisionTarget closestCenterTarget = targetVector.get(centerBoxIndex);
double closestCenterXDiff = Math.abs(closestCenterTarget.x - CENTER_X);
for(int i = 1; i < targetVector.size(); i++) {
// check if this target is closer to the center
double boxCenterXDiff = Math.abs(targetVector.get(i).x - CENTER_X);
if(boxCenterXDiff < closestCenterXDiff) {
centerBoxIndex = i;
closestCenterTarget = targetVector.get(i);
closestCenterXDiff = boxCenterXDiff;
}
}
centerTarget = closestCenterTarget;
}
}
/**
* Updates all currently visible Deep Space vision targets.
* @see DeepSpaceVisionTarget
* @see MoePiClient#updateCenterTarget()
*/
private synchronized void updateDeepSpaceTargets() {
targetVector.clear();
if(boxVector.size() == 1) {
if(boxVector.get(0).type == Box.TargetType.RIGHT.value) {
targetVector.add(new DeepSpaceVisionTarget(null, boxVector.get(0)));
}
}
else if(boxVector.size() >= 2) {
// tbh not best way to do this/could be faster but max
// boxVector size is only six anyway
Box lastBox = boxVector.get(0);
for(int i = 1; i < boxVector.size(); i++) {
if(lastBox.type == Box.TargetType.LEFT.value && boxVector.get(i).type == Box.TargetType.RIGHT.value) {
targetVector.add(new DeepSpaceVisionTarget(lastBox, boxVector.get(i)));
}
lastBox = boxVector.get(i);
}
}
}
/**
* Prints all current MoePi telemetry.
*/
public synchronized void printData() {
try {
this.updateDeepSpaceTargets();
this.updateCenterTarget();
System.out.println("-------------------------------------------");
System.out.println("Found Boxes: " + !boxVector.isEmpty());
for(int i = 0; i < boxVector.size(); i++) {
System.out.println("Box " + (i+1) + ": " + boxVector.get(i));
}
System.out.println("Targets: " + targetVector);
System.out.println("Center Target: " + centerTarget);
System.out.println("Angle: " + this.getAngle() + " degrees");
System.out.println("Distance: " + this.getDistance() + " inches");
} catch(Exception ex) {
ex.printStackTrace();
}
}
/**
* Box for MoePi UDP Client.
* @see MoePiClient#readBox(ByteBuffer)
*/
public static class Box {
public final double x, y, w, h, area, type;
/**
* Constructs a new instance of <code>Box</code>.
* @param x the center x coordinate
* @param y the center y coordinate
* @param w the width of the box
* @param h the height of the box
* @param type the value of the <code>TargetType</code> of the box
* @see TargetType
*/
private Box(double x, double y, double w, double h, double type) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.area = w * h;
this.type = type;
}
/**
* <p>Representation: <code>type</code> <code>width</code>x<code>height</code> :: (<code>x</code>,<code>y</code>)</p>
* {@inheritDoc}
*/
@Override
public String toString() {
return typeToString(type) + " " + w + "x" + h + " :: (" + x + ", " + y + ")";
}
/**
* Returns <code>type</code> as a <code>String</code>.
* @param type the type as a <code>double</code>
* @return <code>type</code> as a <code>String</code>
*/
public String typeToString(double type) {
if(type == 1) {
return "NONE";
}
if(type == 2) {
return "LEFT";
}
if(type == 3) {
return "RIGHT";
}
return "UNKNOWN TYPE";
}
/**
* Target Type for Destination Deep Space 2019.
*/
public enum TargetType {
NONE(1.0d), LEFT(2.0d), RIGHT(3.0d);
public final double value;
private TargetType(double value) {
this.value = value;
}
}
}
/**
* Vision Target for Destination Deep Space 2019.
* @see Box
* @see MoePiClient#updateDeepSpaceTargets()
* @see MoePiClient#updateCenterTarget()
*/
public class DeepSpaceVisionTarget {
public final double x, y;
public final Box left;
public final Box right;
/**
* Constructs a new <code>DeepSpaceVisionTarget</code>.
* @param left the left target
* @param right the right target
*/
private DeepSpaceVisionTarget(Box left, Box right) {
this.left = left;
this.right = right;
if(left != null && right != null) {
this.x = (left.x + right.x) / 2.0;
this.y = (left.y + right.y) / 2.0;
}
else if(right != null) {
this.x = right.x;
this.y = right.y;
}
else {
this.x = this.y = 0;
}
}
/**
* Returns if there is only a right target to the pair. The purpose of this is the fact that our
* vision camera is mounted on the right side of the elevator (still in a fixed position, though)
* facing forward (meaning it's not centered). This means as we approach a target to score we (should)
* only see the right target (however, this is not until we are really, really close).
* @return <code>true</code> if there is only a right target to the pair,
* <code>false</code> if there is both a left/right target to the pair
*/
public boolean hasOnlyRight() {
return left == null;
}
/**
* <p>Representation: (x, y) [{<code>left.toString()</code>}, {<code>right.toString()</code>}]</p>
* {@inheritDoc}
*/
@Override
public String toString() {
return "(" + x + ", " + y + ") [{ " + left + " }, { " + right + " }]";
}
}
} | 28.251716 | 119 | 0.662887 |
8d7e97185ec0d70907322e4ef5a45785b9a1632b | 2,842 | package eu.bcvsolutions.idm.ic.impl;
import eu.bcvsolutions.idm.ic.api.IcConnectorKey;
/**
* Uniquely identifies a connector within an installation. Consists of the
* quadruple (icType, bundleName, bundleVersion, connectorName)
*/
public class IcConnectorKeyImpl implements IcConnectorKey {
private String framework;
private String bundleName;
private String bundleVersion;
private String connectorName;
public IcConnectorKeyImpl() {
super();
}
public IcConnectorKeyImpl(String framework, String bundleName, String bundleVersion, String connectorName) {
super();
this.framework = framework;
this.bundleName = bundleName;
this.bundleVersion = bundleVersion;
this.connectorName = connectorName;
}
@Override
public String getFramework() {
return framework;
}
public void setFramework(String framework) {
this.framework = framework;
}
@Override
public String getBundleName() {
return bundleName;
}
public void setBundleName(String bundleName) {
this.bundleName = bundleName;
}
@Override
public String getBundleVersion() {
return bundleVersion;
}
public void setBundleVersion(String bundleVersion) {
this.bundleVersion = bundleVersion;
}
@Override
public String getConnectorName() {
return connectorName;
}
public void setConnectorName(String connectorName) {
this.connectorName = connectorName;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bundleName == null) ? 0 : bundleName.hashCode());
result = prime * result + ((bundleVersion == null) ? 0 : bundleVersion.hashCode());
result = prime * result + ((connectorName == null) ? 0 : connectorName.hashCode());
result = prime * result + ((framework == null) ? 0 : framework.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IcConnectorKeyImpl other = (IcConnectorKeyImpl) obj;
if (bundleName == null) {
if (other.bundleName != null)
return false;
} else if (!bundleName.equals(other.bundleName))
return false;
if (bundleVersion == null) {
if (other.bundleVersion != null)
return false;
} else if (!bundleVersion.equals(other.bundleVersion))
return false;
if (connectorName == null) {
if (other.connectorName != null)
return false;
} else if (!connectorName.equals(other.connectorName))
return false;
if (framework == null) {
if (other.framework != null)
return false;
} else if (!framework.equals(other.framework))
return false;
return true;
}
@Override
public String toString() {
return "IcConnectorKeyImpl [framework=" + framework + ", bundleName=" + bundleName + ", bundleVersion="
+ bundleVersion + ", connectorName=" + connectorName + "]";
}
}
| 25.375 | 109 | 0.706545 |
30c888840c7712d43011c06cd5f31f57238b289e | 1,124 | package com.jww.common.mdb;
import com.jww.common.core.Constants;
import cn.hutool.core.util.StrUtil;
/**
* 数据源DbContextHolder
*
* @author wanyong
* @date 2017/11/17 13:31
*/
public class DbContextHolder {
private static final ThreadLocal<String> CONTEXTHOLDER = new ThreadLocal<String>();
/**
* 设置数据源
*
* @param dataSourceEnum
* @author wanyong
* @date 2017/11/17 19:46
*/
public static void setDbType(Constants.DataSourceEnum dataSourceEnum) {
CONTEXTHOLDER.set(dataSourceEnum.getName());
}
/**
* 取得当前数据源
*
* @return String
* @author wanyong
* @date 2017/11/17 19:46
*/
public static String getDbType() {
String dataSource = CONTEXTHOLDER.get();
// 如果没有指定数据源,使用默认数据源
if (StrUtil.isEmpty(dataSource)) {
DbContextHolder.setDbType(Constants.DataSourceEnum.MASTER);
}
return CONTEXTHOLDER.get();
}
/**
* 清除上下文数据
*
* @author wanyong
* @date 2017-12-11 19:46
*/
public static void clearDbType() {
CONTEXTHOLDER.remove();
}
}
| 21.615385 | 87 | 0.605872 |
3dbf271b87717309fc48066267f8bb9f5094cd22 | 229 | package de.simonlaux.survey;
import java.util.List;
public interface SurveyStore {
public int add(Survey inhalt);
public Survey getbyID(int id);
public List<Survey> getAll(int limit);
boolean close();
}
| 14.3125 | 40 | 0.689956 |
ebb109ba496cdce8b3464ee75723c27cdac5cf64 | 4,148 | /*
* 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 gestock.resources.views;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
/**
*
* @author Roger
*/
public class LicensesView extends GFrame implements ActionListener {
private HashMap<String, String> licenceText;
private JButton closeButton;
private JPanel panel;
private JPanel closePanel;
private JScrollPane scrollLicences;
private JTextPane licences;
public LicensesView() {
super("Gestock - Licences");
licences = new JTextPane();
licences.setEditable(false);
initText();
addText();
licences.setCaretPosition(0);
scrollLicences = new JScrollPane(licences);
closeButton = new JButton("Close");
closeButton.addActionListener(this);
closePanel = new JPanel();
closePanel.add(closeButton);
panel = new JPanel(new BorderLayout());
panel.add(scrollLicences, BorderLayout.CENTER);
panel.add(closePanel, BorderLayout.SOUTH);
setContentPane(panel);
setSize(600, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
this.dispose();
}
private void initText() {
this.licenceText = new HashMap<>();
this.licenceText.put("JSON in Java [package org.json]\n| (https://github.com/douglascrockford/JSON-java)", " Copyright (c) 2002 JSON.org\n\n"
+ " Permission is hereby granted, free of charge, to any person obtaining a copy\n"
+ " of this software and associated documentation files (the \"Software\"), to deal\n"
+ " in the Software without restriction, including without limitation the rights\n"
+ " to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n"
+ " copies of the Software, and to permit persons to whom the Software is\n"
+ " furnished to do so, subject to the following conditions:\n\n"
+ " The above copyright notice and this permission notice shall be included in all\n"
+ " copies or substantial portions of the Software.\n\n"
+ " The Software shall be used for Good, not Evil.\n\n"
+ " THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"
+ " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"
+ " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"
+ " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"
+ " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"
+ " OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n"
+ " SOFTWARE.");
this.licenceText.put("Icons made by Freepik (http://www.freepik.com)\n| (http://www.flaticon.com)",
"Licensed under CC BY 3.0 (Creative Commons BY 3.0)\nhttp://creativecommons.org/licenses/by/3.0/");
this.licenceText.put("JCalendar [package com.toedter.calendar]\n| (http://toedter.com/jcalendar/)",
"Licensed under a LGPL Licence\nhttps://www.gnu.org/licenses/lgpl.html");
}
private void addText() {
String text = "";
for (HashMap.Entry<String, String> entry : licenceText.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
text += "+------------------------------------------------------\n"
+ "| " + key + "\n"
+ "+------------------------------------------------------\n"
+ value + "\n\n\n";
}
this.licences.setText(text);
}
}
| 41.89899 | 149 | 0.603905 |
b2656a5696d97e0033f30ab7349b1daf932e8793 | 1,275 | package com.docomo.purchaserefund.refund;
import com.docomo.purchaserefund.exception.PurchaseRefundException;
import com.docomo.purchaserefund.model.Purchase;
import com.docomo.purchaserefund.model.Refund;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("api/refunds")
public class RefundController {
private RefundService refundService;
@Autowired
public RefundController(RefundService refundService) {
this.refundService = refundService;
}
@GetMapping
public List<Refund> getAllRefunds() throws PurchaseRefundException {
return refundService.getAllRefunds();
}
@GetMapping("{customerId}/customer-refunds")
public List<Refund> getRefundsForCustomer(@PathVariable(name = "customerId") Integer customerId) throws PurchaseRefundException {
return refundService.getRefundsForCustomer(customerId);
}
@PostMapping("{customerId}/refund")
public Integer refund(@PathVariable(name = "customerId") Integer customerId, @Valid @RequestBody Refund refund) throws PurchaseRefundException {
return refundService.addRefund(customerId, refund);
}
}
| 34.459459 | 148 | 0.774902 |
7a0d573ffc6ad95936120ee9fd02951dea3e3604 | 6,687 | /*
* Copyright (c) 2020 Georgios Damaskinos
* All rights reserved.
* @author Georgios Damaskinos <[email protected]>
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package apps.lr;
import android.util.Log;
import coreComponents.GradientGenerator;
import utils.Helpers;
import utils.MatrixOperation;
import utils.MyDataset;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.jblas.DoubleMatrix;
import Jama.Matrix;
public class LRGradientGenerator implements GradientGenerator {
private Kryo kryo;
private Matrix trainX;
private Matrix trainT;
private Matrix weights,biases;
private int trainN;
private double fetchMiniBatchTime;
private double fetchModelTime;
private double computeGradientsTime;
//model Fetch time: index 0, batch FetchTime: index 1, batch gradientComputeTime: index 2
private int featuresize, numlabels;
/**
* number of outer iterations of the model (how many times the model was trained on the whole trainingSet).
*/
int currEpoch;
/**
* total training time
*/
long trainTime;
private Matrix sE_delta_weights, sE_delta_biases;
private Matrix delta_weights, delta_biases;
public LRGradientGenerator(){
kryo = new Kryo();
}
public void fetch(Input in) {
double t = System.currentTimeMillis();
MyDataset miniBatch = kryo.readObject(in, MyDataset.class);
// Log.d("INFO", String.valueOf(miniBatch.Tset.columns));
fetchMiniBatchTime = System.currentTimeMillis() - t;
this.trainX = new Matrix(miniBatch.Xset.toArray2());
this.trainT = new Matrix(miniBatch.Tset.toArray2());
t = System.currentTimeMillis();
LRModelParams params = kryo.readObject(in, LRModelParams.class);
// Log.d("INFO", String.valueOf(params.w1.length));
weights = new Matrix(params.weights.toArray2());
biases = new Matrix(params.biases.toArray2());
trainTime = params.trainTime;
currEpoch = params.currEpoch;
fetchModelTime = System.currentTimeMillis() - t;
//System.out.println("Fetched w1: " + w1);
System.out.println("Epoch: "+currEpoch);
System.out.println("Mini-batch size: "+trainX.getRowDimension());
Log.d("INFO", "Total Bytes read: " + Helpers.humanReadableByteCount(in.total(), false));
}
public void computeGradient(Output output){
double t1 = System.currentTimeMillis();
kryo.register(Integer.class);
kryo.writeObject(output, currEpoch);
this.trainN = trainX.getRowDimension();
this.featuresize = trainX.getColumnDimension();
this.numlabels = trainT.getColumnDimension();
Matrix x, predicted, label, Tlabel, L;
int t, i, j, k;
double Fval;
// initialize E_delta params
sE_delta_weights = new Matrix(numlabels, featuresize);
delta_weights = new Matrix(numlabels, featuresize);
sE_delta_biases = new Matrix(numlabels,1);
delta_biases = new Matrix(1,numlabels);
//long total_time=0;
double responseTime;
//double eachLoopTime=0;
// compute over all the inputs the parameters
for (i = 0; i < trainN; i++) {
responseTime = System.currentTimeMillis();
// get the ith input example from the x_input vector of d dims
x = MatrixOperation.getRowAt(trainX, i);
label = MatrixOperation.getRowAt(trainT, i);
Matrix currentPredictY = x.times(weights.transpose()).plus(biases.transpose());
currentPredictY = Softmax(currentPredictY);
sE_delta_biases = label.minus(currentPredictY);
sE_delta_weights = sE_delta_biases.transpose().times(x);
//System.out.println("deltaW1: "+deltaW);
sE_delta_biases = colsum(sE_delta_biases);//.times(1/(double)trainN);
//sE_delta_weights.times(1/(double)trainN);
delta_weights = delta_weights.plus(sE_delta_weights);
delta_biases = delta_biases.plus(sE_delta_biases);
//eachLoopTime = (System.currentTimeMillis() - responseTime);
//System.out.println("Each loop time: "+eachLoopTime);
//total_time += eachLoopTime;
}
//System.out.println("Average time: "+ total_time/(double)trainN);
kryo.register(LRGradients.class);
LRGradients gradients = new LRGradients(new DoubleMatrix(delta_weights.getArray()),new DoubleMatrix(delta_biases.getArray()), trainN);
kryo.writeObject(output, gradients);
computeGradientsTime = System.currentTimeMillis() - t1;
Log.d("INFO", "Number of gradients: " + String.valueOf(gradients.delta_biases.length + gradients.delta_weights.length));
Log.d("INFO", "Total Bytes written: " + Helpers.humanReadableByteCount(output.total(), false));
}
public static Matrix colsum(Matrix m) {
int numRows = m.getRowDimension();
int numCols = m.getColumnDimension();
Matrix sum = new Matrix(1, numCols);
// loop through the rows and compute the sum
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
sum.set(0, j, sum.get(0, j) + m.get(i, j));
}
}
return sum;
}
/**
* The softmax method
* @param z
* @return
*/
private static Matrix Softmax(Matrix z) {
int zlength = z.getColumnDimension() * z.getRowDimension();
Matrix exp = new Matrix(1,zlength);
for(int i=0; i < zlength; i++){
exp.set(0,i,Math.exp(z.get(0,i)));
}
Matrix softmax = exp.times(1/ (double) sum(exp));
return softmax;
}
public static double sum(Matrix m) {
int numRows = m.getRowDimension();
int numCols = m.getColumnDimension();
double sum = 0;
// loop through the rows and compute the sum
for (int i=0; i<numRows; i++) {
for (int j=0; j<numCols; j++) {
sum += m.get(i,j);
}
}
return sum;
}
@Override
public int getSize() {
return trainN;
}
@Override
public double getFetchMiniBatchTime() {
return fetchMiniBatchTime;
}
@Override
public double getFetchModelTime() {
return fetchModelTime;
}
@Override
public double getComputeGradientsTime() {
return computeGradientsTime;
}
}
| 29.073913 | 142 | 0.632122 |
5587a7f74c06e37445c06aa5344ab2ca5a68d0a1 | 3,055 | package com.example.testmvpapp.sections.launcher;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.example.testmvpapp.R;
import com.example.testmvpapp.base.SimpleActivity;
import com.example.testmvpapp.sections.sign.SignInActivity;
import com.example.testmvpapp.ui.newfeature.LauncherHolderCreator;
import com.example.testmvpapp.util.storage.BFPreference;
import com.example.testmvpapp.util.storage.ConstantKey;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.OnClick;
/**
* 版本新特性
*/
public class NewFeaturesActivity extends SimpleActivity implements OnItemClickListener, ViewPager.OnPageChangeListener {
@BindView(R.id.convenientBanner)
ConvenientBanner<Integer> mConvenientBanner;
@BindView(R.id.btn_skip)
Button mButton;
private static final ArrayList<Integer> INTEGERS = new ArrayList<>();
@OnClick(R.id.btn_skip)
void skipButtonAction() {
BFPreference.setAppFlag(ConstantKey.IS_FIRST_LOAD, true);
Intent intent = new Intent(NewFeaturesActivity.this, SignInActivity.class);
startActivity(intent);
finish();
}
@Override
protected Object getLayout() {
return R.layout.activity_new_features;
}
@Override
protected void init() {
initBanner();
}
private void initBanner() {
// 数据清空,不然数据会重复添加
INTEGERS.clear();
INTEGERS.add(R.mipmap.launcher_01);
INTEGERS.add(R.mipmap.launcher_02);
INTEGERS.add(R.mipmap.launcher_03);
INTEGERS.add(R.mipmap.launcher_04);
INTEGERS.add(R.mipmap.launcher_05);
mConvenientBanner.setPages(new LauncherHolderCreator(), INTEGERS)
//设置两个点图片作为翻页指示器,不设置则没有指示器,可以根据自己需求自行配合自己的指示器,
// 不需要圆点指示器可用不设
.setPageIndicator(new int[]{R.drawable.dot_normal, R.drawable.dot_focus})
.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
.setOnPageChangeListener(this)
.setOnItemClickListener(this)
.setCanLoop(false);
// 设置数据刷新
// INTEGERS.remove(0);
// mConvenientBanner.notifyDataSetChanged();
}
@Override
public void onItemClick(int position) {
//如果点击的是最后一个
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (position == INTEGERS.size() - 1) {
mButton.setVisibility(View.VISIBLE);
// 是否显示指示器
mConvenientBanner.setPointViewVisible(false);
} else {
mButton.setVisibility(View.GONE);
mConvenientBanner.setPointViewVisible(true);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
| 28.820755 | 120 | 0.690998 |
5c77211c73425eca7248aeb1d6016abcca8f1b03 | 9,205 | package com.codes.common.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
/**
* 随机数据工具类
*
* @author zhangguangyong
*
* 2015年11月27日 下午6:28:22
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class Randoms {
static final Random RANDOM = new Random();
// 字符类型
static enum CharType {
Lower, Upper, Char, Num, CharAndNum
};
// 中文字符界限
static Character firstChineseChar = '\u4e00';
static Character lastChineseChar = '\u9fa5';
static int firstChineseNum = firstChineseChar;
static int lastChineseNum = lastChineseChar;
static final char[] LOWERCHAR = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
static final char[] UPPERCHAR = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
static final char[] CHARS = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
static final char[] NUMS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
static char[] CHARANDNUM = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9' };
public static String random(final int count, final boolean letters, final boolean numbers) {
return random(count, 0, 0, letters, numbers);
}
public static String random(final int count, final int start, final int end, final boolean letters,
final boolean numbers) {
return random(count, start, end, letters, numbers, null, RANDOM);
}
public static String random(final int count, final String chars) {
if (chars == null) {
return random(count, 0, 0, false, false, null, RANDOM);
}
return random(count, chars.toCharArray());
}
public static String random(final int count, final char... chars) {
if (chars == null) {
return random(count, 0, 0, false, false, null, RANDOM);
}
return random(count, 0, chars.length, false, false, chars, RANDOM);
}
public static String random(int count, int start, int end, final boolean letters, final boolean numbers,
final char[] chars, final Random random) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
if (chars != null && chars.length == 0) {
throw new IllegalArgumentException("The chars array must not be empty");
}
if (start == 0 && end == 0) {
if (chars != null) {
end = chars.length;
} else {
if (!letters && !numbers) {
end = Integer.MAX_VALUE;
} else {
end = 'z' + 1;
start = ' ';
}
}
} else {
if (end <= start) {
throw new IllegalArgumentException(
"Parameter end (" + end + ") must be greater than start (" + start + ")");
}
}
final char[] buffer = new char[count];
final int gap = end - start;
while (count-- != 0) {
char ch;
if (chars == null) {
ch = (char) (random.nextInt(gap) + start);
} else {
ch = chars[random.nextInt(gap) + start];
}
if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) {
if (ch >= 56320 && ch <= 57343) {
if (count == 0) {
count++;
} else {
// low surrogate, insert high surrogate after putting it
// in
buffer[count] = ch;
count--;
buffer[count] = (char) (55296 + random.nextInt(128));
}
} else if (ch >= 55296 && ch <= 56191) {
if (count == 0) {
count++;
} else {
// high surrogate, insert low surrogate before putting
// it in
buffer[count] = (char) (56320 + random.nextInt(128));
count--;
buffer[count] = ch;
}
} else if (ch >= 56192 && ch <= 56319) {
// private high surrogate, no effing clue, so skip it
count++;
} else {
buffer[count] = ch;
}
} else {
count++;
}
}
return new String(buffer);
}
/**
* 随机指定范围的一个数字
*
* @param min
* 范围最小值
* @param max
* 范围最大值
* @return
*/
public static Number random(Number min, Number max) {
double minVal = min.doubleValue() - 1;
double maxVal = max.doubleValue() + 1;
double ret = Math.random() * (maxVal - minVal) + minVal;
ret = Math.min(ret, max.doubleValue());
ret = Math.max(ret, min.doubleValue());
return ret;
}
/**
* 随机指定范围和长度的数字
*
* @param min
* @param max
* @param len
* @return
*/
public static List random(Number min, Number max, long len) {
return random(min, max, len, len);
}
/**
* 随机指定大小区间和长度区间的数字
*
* @param min
* 最小值
* @param max
* 最大值
* @param lenMin
* 最小长度
* @param lenMax
* 最大长度
* @return
*/
public static List random(Number min, Number max, long lenMin, long lenMax) {
long len = random(lenMin, lenMax).longValue();
if (len > 0) {
List ret = new ArrayList();
for (int i = 0; i < len; i++) {
ret.add(random(min, max));
}
return ret;
}
return null;
}
/**
* 随机小写字符
*
* @param len
* 随机的个数
* @return
*/
public static String randomLowerChar(int len) {
return random(CharType.Lower, len);
}
/**
* 随机大写字母
*
* @param len
* 随机的个数
* @return
*/
public static String randomUpperChar(int len) {
return random(CharType.Upper, len);
}
/**
* 随机字符
*
* @param len
* 随机的个数
* @return
*/
public static String randomChar(int len) {
return random(CharType.Char, len);
}
/**
* 随机数字
*
* @param len
* 随机的个数
* @return
*/
public static String randomNum(int len) {
return random(CharType.Num, len);
}
/**
* 随机字符和数字
*
* @param len
* 随机的个数
* @return
*/
public static String randomCharAndNum(int len) {
return random(CharType.CharAndNum, len);
}
/**
* 随机数组里面的一个值
*
* @param values
* @return
*/
public static <T> T randomOne(T... values) {
return (T) values[RANDOM.nextInt(values.length)];
}
/**
* 随机指定长度来数据来源的数据
*
* @param minLen
* @param maxLen
* @param values
* @return
*/
public static List random(long minLen, long maxLen, Object... values) {
long len = randomLong(minLen, maxLen);
if (len > 0) {
List ret = new ArrayList();
for (int i = 0; i < len; i++) {
ret.add(randomOne(values));
}
return ret;
}
return null;
}
/**
* 随机中文
*
* @param length
* @return
*/
public static String randomChinese(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append((char) random(firstChineseNum, lastChineseNum).intValue());
}
return sb.toString();
}
/**
* 随机指定范围的字符
*
* @param min
* @param max
* @return
*/
public static char randomChar(int min, int max) {
return (char) randomInteger(min, max);
}
/**
* 随机指定范围的整数
*
* @param min
* @param max
* @return
*/
public static int randomInteger(int min, int max) {
return random(min, max).intValue();
}
/**
* 随机指定范围的长整型数
*
* @param min
* @param max
* @return
*/
public static long randomLong(long min, long max) {
return random(min, max).longValue();
}
public static double randomDouble(double min, double max) {
return random(min, max).doubleValue();
}
private static String random(CharType type, long len) {
return random(type, len, len);
}
private static String random(CharType type, long minLen, long maxLen) {
long len = random(minLen, maxLen).longValue();
if (len <= 0) {
return null;
}
StringBuffer sb = new StringBuffer();
char[] cs = null;
switch (type) {
case Lower:
cs = LOWERCHAR;
break;
case Upper:
cs = UPPERCHAR;
break;
case Char:
cs = CHARS;
break;
case Num:
cs = NUMS;
break;
case CharAndNum:
cs = CHARANDNUM;
break;
}
for (int i = 0; i < len; i++) {
sb.append(cs[RANDOM.nextInt(cs.length)]);
}
return sb.toString();
}
public static Date randomDate(Date min, Date max) {
return randomDate(min.getTime(), max.getTime());
}
public static Date randomDate(long min, long max) {
return new Date(randomLong(min, max));
}
public static Date randomDate() {
return randomDate(System.currentTimeMillis() - Integer.MAX_VALUE,
System.currentTimeMillis() + Integer.MAX_VALUE);
}
}
| 24.096859 | 117 | 0.535361 |
8f80818a7a183cb72213cb8fc97f70c2808d3da1 | 3,461 | /*
* Copyright 2019 James Fenn
*
* 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.james.status.dialogs.picker;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.james.status.R;
import com.james.status.dialogs.PreferenceDialog;
import com.james.status.utils.WhileHeldListener;
import androidx.annotation.Nullable;
public class IntegerPickerDialog extends PreferenceDialog<Integer> {
private String unit;
@Nullable
private Integer min, max;
private TextView scale;
public IntegerPickerDialog(Context context, String unit) {
super(context);
this.unit = unit;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_integer_picker);
scale = findViewById(R.id.scale);
Integer preference = getPreference();
if (preference == null) {
preference = 0;
setPreference(preference);
}
scale.setText(String.valueOf(preference));
((TextView) findViewById(R.id.unit)).setText(unit);
findViewById(R.id.scaleUp).setOnTouchListener(new WhileHeldListener() {
@Override
public void onHeld() {
Integer preference = getPreference();
if (preference != null) {
preference++;
if (min != null) preference = Math.max(min, preference);
if (max != null) preference = Math.min(max, preference);
setPreference(preference);
scale.setText(String.valueOf(preference));
}
}
});
findViewById(R.id.scaleDown).setOnTouchListener(new WhileHeldListener() {
@Override
public void onHeld() {
Integer preference = getPreference();
if (preference != null) {
preference--;
if (min != null) preference = Math.max(min, preference);
if (max != null) preference = Math.min(max, preference);
setPreference(preference);
scale.setText(String.valueOf(preference));
}
}
});
findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cancel();
}
});
findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
confirm();
}
});
}
public IntegerPickerDialog setMinMax(@Nullable Integer min, @Nullable Integer max) {
this.min = min;
this.max = max;
return this;
}
}
| 30.359649 | 88 | 0.596359 |
d7a6b45b2d207b098a28ae988d8410be3256fef9 | 556 | package io.undertow.predicate;
import io.undertow.server.HttpServerExchange;
/**
* @author Stuart Douglas
*/
class OrPredicate implements Predicate {
private final Predicate[] predicates;
public OrPredicate(final Predicate... predicates) {
this.predicates = predicates;
}
@Override
public boolean resolve(final HttpServerExchange value) {
for (final Predicate predicate : predicates) {
if (predicate.resolve(value)) {
return true;
}
}
return false;
}
}
| 21.384615 | 60 | 0.633094 |
3ff800d0e32c30d2f23a7aa90853750dba67983e | 166 | package p;
class A{
class Inner{
Inner(){
}
Inner(int i){
}
}
}
class I2 extends A.Inner{
I2(){
new A().super();
}
I2(int i){
new A().super(i);
}
} | 9.222222 | 25 | 0.512048 |
65d38e2dd83b287770d31c2accddf2a4845ede3c | 1,127 |
package org.springframework.web.reactive.result.method.annotation;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.SyncHandlerMethodArgumentResolver;
import org.springframework.web.server.ServerWebExchange;
/**
* Resolver for a {@link SessionStatus} argument obtaining it from the
* {@link BindingContext}.
*
*
* @since 5.0
*/
public class SessionStatusMethodArgumentResolver implements SyncHandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return SessionStatus.class == parameter.getParameterType();
}
@Nullable
@Override
public Object resolveArgumentValue(
MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {
Assert.isInstanceOf(InitBinderBindingContext.class, bindingContext);
return ((InitBinderBindingContext) bindingContext).getSessionStatus();
}
}
| 30.459459 | 95 | 0.822538 |
89d705b43d96666c41b7c39ea0e70261c3a062b2 | 4,630 | package com.taopao.tiktok;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.taopao.rxtoast.RxToast;
import com.taopao.tiktok.ui.dialog.CommentBottomSheetDialogFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class VerVideoFragment extends Fragment {
@BindView(R.id.recyclerview)
RecyclerView mRecyclerview;
@BindView(R.id.swiperefreshlayout)
SwipeRefreshLayout mSwiperefreshlayout;
Unbinder unbinder;
private MyAdapter mAdapter;
public static VerVideoFragment newInstance() {
VerVideoFragment fragment = new VerVideoFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_ver_video, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView();
}
private void initView() {
PagerSnapHelper pagerSnapHelper = new PagerSnapHelper() {
// 在 Adapter的 onBindViewHolder 之后执行
@Override
public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
// TODO 找到对应的Index
Log.e("xiaxl: ", "---findTargetSnapPosition---");
int targetPos = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
Log.e("xiaxl: ", "targetPos: " + targetPos);
RxToast.show("滑到到 " + targetPos + "位置");
return targetPos;
}
// 在 Adapter的 onBindViewHolder 之后执行
@Nullable
@Override
public View findSnapView(RecyclerView.LayoutManager layoutManager) {
// TODO 找到对应的View
Log.e("xiaxl: ", "---findSnapView---");
View view = super.findSnapView(layoutManager);
Log.e("xiaxl: ", "tag: " + view.getTag());
return view;
}
};
pagerSnapHelper.attachToRecyclerView(mRecyclerview);
// ---布局管理器---
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
// 默认是Vertical (HORIZONTAL则为横向列表)
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//
mRecyclerview.setLayoutManager(linearLayoutManager);
ArrayList<String> strings = new ArrayList<>();
for (int i = 0; i < 20; i++) {
strings.add("");
}
mAdapter = new MyAdapter(strings);
mRecyclerview.setAdapter(mAdapter);
mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
@Override
public void onLoadMoreRequested() {
}
}, mRecyclerview);
//
}
class MyAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
public MyAdapter(@Nullable List<String> data) {
super(R.layout.recycle_item_video, data);
}
@Override
protected void convert(BaseViewHolder helper, String item) {
helper.getView(R.id.iv_comment).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CommentBottomSheetDialogFragment commentBottomSheetDialogFragment = new CommentBottomSheetDialogFragment();
commentBottomSheetDialogFragment.show(getChildFragmentManager(), "");
}
});
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
| 33.79562 | 127 | 0.65378 |
f697b601a71c9021b9b934ec6abc0d70f9f74fe7 | 2,643 | package com.plout.blockchain.listener;
import com.google.common.base.Optional;
import com.plout.blockchain.core.Block;
import com.plout.blockchain.event.BlockConfirmNumEvent;
import com.plout.blockchain.event.FetchNextBlockEvent;
import com.plout.blockchain.event.NewBlockEvent;
import com.plout.blockchain.utils.SerializeUtils;
import com.plout.blockchain.db.DBAccess;
import com.plout.blockchain.net.base.MessagePacket;
import com.plout.blockchain.net.base.MessagePacketType;
import com.plout.blockchain.net.client.AppClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* 区块事件监听器
* @author yangjian
* @since 18-4-19
*/
@Component
public class BlockEventListener {
@Autowired
private AppClient appClient;
@Autowired
private DBAccess dbAccess;
private static Logger logger = LoggerFactory.getLogger(BlockEventListener.class);
/**
* 挖矿事件监听
* @param event
*/
@EventListener(NewBlockEvent.class)
public void newBlock(NewBlockEvent event) {
logger.info("++++++++++++++ 开始广播新区块 +++++++++++++++++++++");
Block block = (Block) event.getSource();
MessagePacket messagePacket = new MessagePacket();
messagePacket.setType(MessagePacketType.REQ_NEW_BLOCK);
messagePacket.setBody(SerializeUtils.serialize(block));
appClient.sendGroup(messagePacket);
}
/**
* 同步下一个区块
* @param event
*/
@EventListener(FetchNextBlockEvent.class)
public void fetchNextBlock(FetchNextBlockEvent event) {
logger.info("++++++++++++++++++++++++++++++ 开始群发信息获取 next Block +++++++++++++++++++++++++++++++++");
Integer blockIndex = (Integer) event.getSource();
if (blockIndex == 0) {
Optional<Object> lastBlockIndex = dbAccess.getLastBlockIndex();
if (lastBlockIndex.isPresent()) {
blockIndex = (Integer) lastBlockIndex.get();
}
}
MessagePacket messagePacket = new MessagePacket();
messagePacket.setType(MessagePacketType.REQ_SYNC_NEXT_BLOCK);
messagePacket.setBody(SerializeUtils.serialize(blockIndex+1));
//群发消息,从群组节点去获取下一个区块
appClient.sendGroup(messagePacket);
}
@EventListener(BlockConfirmNumEvent.class)
public void IncBlockConfirmNum(BlockConfirmNumEvent event)
{
logger.info("++++++++++++++ 增加区块确认数 ++++++++++++++++++");
Integer blockIndex = (Integer) event.getSource();
MessagePacket messagePacket = new MessagePacket();
messagePacket.setType(MessagePacketType.REQ_INC_CONFIRM_NUM);
messagePacket.setBody(SerializeUtils.serialize(blockIndex));
//群发消息
appClient.sendGroup(messagePacket);
}
}
| 31.843373 | 102 | 0.746122 |
157477a1b20dd321d78789899154e46c18d69161 | 8,759 | package com.edusoft.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.edusoft.entity.Proyecto;
import com.edusoft.models.service.IProyectoService;
@Controller
@EnableAutoConfiguration
public class DisplayDownloadPDFController{
@Autowired
private IProyectoService proyectoService;
private static final String FILE_PATH = "C:/fileDownloadExample/";
@RequestMapping(value = "/ofertas/{id}", method = RequestMethod.GET)
public String getFile(HttpServletResponse response,@PathVariable(value = "id") Long id,Map<String, Object> model,RedirectAttributes redirectAttrs) throws IOException {
try {
Proyecto proyecto = proyectoService.findOne(id);
model.put("proyecto", proyecto);
File file = new File(FILE_PATH);
response.setContentType("application/pdf");
//Si se quiere descargar archivo
//response.setHeader("Content-Disposition", "attachment;filename=" + file.getName() +"/"+ proyecto.getOfertaPdf().toString());
BufferedInputStream inStrem = new BufferedInputStream(new FileInputStream(file + "/" + "Solicitudes/"+proyecto.getSolicitud()+"/" + proyecto.getOfertaPdf().toString()));
BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inStrem.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
inStrem.close();
}catch(IOException ex) {
System.err.println("An IOException was caught!");
ex.printStackTrace();
redirectAttrs
.addFlashAttribute("mensaje", "Error, no existe el archivo en el directorio.");
return "redirect:/";
}
return null;
}
@RequestMapping(value = "/albaranes/{id}", method = RequestMethod.GET)
public String getFileAlbaran(HttpServletResponse response,@PathVariable(value = "id") Long id,Map<String, Object> model,RedirectAttributes redirectAttrs) throws IOException {
try {
Proyecto proyecto = proyectoService.findOne(id);
model.put("proyecto", proyecto);
File file = new File(FILE_PATH);
response.setContentType("application/pdf");
//response.setHeader("Content-Disposition", "attachment;filename=" + file.getName() +"/"+ proyecto.getAlbaranPdf().toString());
BufferedInputStream inStrem = new BufferedInputStream(new FileInputStream(file + "/" + "Albaranes/"+proyecto.getNombreTaller()+"/" +proyecto.getAlbaranPdf().toString()));
BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inStrem.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
inStrem.close();
}catch(IOException ex) {
System.err.println("An IOException was caught!");
ex.printStackTrace();
redirectAttrs
.addFlashAttribute("mensaje", "Error, no existe el archivo en el directorio.");
return "redirect:/";
}
return null;
}
@RequestMapping(value = "/pedidos/{id}", method = RequestMethod.GET)
public String getFilePedido(HttpServletResponse response,@PathVariable(value = "id") Long id,Map<String, Object> model,RedirectAttributes redirectAttrs) throws IOException {
try {
Proyecto proyecto = proyectoService.findOne(id);
model.put("proyecto", proyecto);
File file = new File(FILE_PATH);
// if (proyecto.getPedidoPdf()!=null ) {
response.setContentType("application/pdf");
//response.setHeader("Content-Disposition", "attachment;filename=" + file.getName() +"/"+ proyecto.getPedidoPdf().toString());
BufferedInputStream inStrem = new BufferedInputStream(new FileInputStream(file + "/" + "Solicitudes/"+proyecto.getSolicitud()+"/" +proyecto.getPedidoPdf().toString()));
BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inStrem.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
inStrem.close();
}catch(IOException ex) {
System.err.println("An IOException was caught!");
ex.printStackTrace();
redirectAttrs
.addFlashAttribute("mensaje", "Error, no existe el archivo en el directorio.");
return "redirect:/";
}
return null;
}
@RequestMapping(value = "/solicitudesPdf/{id}", method = RequestMethod.GET)
public String getFileSolicitud(HttpServletResponse response,@PathVariable(value = "id") Long id,Map<String, Object> model,RedirectAttributes redirectAttrs) throws IOException {
try {
Proyecto proyecto = proyectoService.findOne(id);
model.put("proyecto", proyecto);
File file = new File(FILE_PATH);
//if (proyecto.getSolicitudPdf()!=null ) {
response.setContentType("application/pdf");
//response.setHeader("Content-Disposition", "attachment;filename=" + file.getName() +"/"+ proyecto.getSolicitudPdf().toString());
//Para subir pdf solicitudes (desactivado)
//BufferedInputStream inStrem = new BufferedInputStream(new FileInputStream(file + "/" + "Solicitudes/"+proyecto.getSolicitud()+"/" + proyecto.getSolicitudPdf().toString()));
BufferedInputStream inStrem = new BufferedInputStream(new FileInputStream(file + "/" + "Solicitudes/"+proyecto.getSolicitud()+"/" + proyecto.getSolicitud()+".pdf"));
BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inStrem.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
inStrem.close();
}catch(IOException ex) {
System.err.println("An IOException was caught!");
ex.printStackTrace();
redirectAttrs
.addFlashAttribute("mensaje", "Error, no existe el archivo en el directorio.");
return "redirect:/";
}
return null;
}
@RequestMapping(value = "/sscc/{id}", method = RequestMethod.GET)
public String getFileSscc(HttpServletResponse response,@PathVariable(value = "id") Long id,Map<String, Object> model,RedirectAttributes redirectAttrs) throws IOException {
try {
Proyecto proyecto = proyectoService.findOne(id);
model.put("proyecto", proyecto);
File file = new File(FILE_PATH);
//if (proyecto.getSsccPdf()!=null ) {
response.setContentType("application/pdf");
//response.setHeader("Content-Disposition", "attachment;filename=" + file.getName() +"/"+ proyecto.getSsccPdf().toString());
BufferedInputStream inStrem = new BufferedInputStream(new FileInputStream(file + "/" + "Solicitudes/"+proyecto.getSolicitud()+"/" +proyecto.getSsccPdf().toString()));
BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inStrem.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
inStrem.close();
}catch(IOException ex) {
System.err.println("An IOException was caught!");
ex.printStackTrace();
redirectAttrs
.addFlashAttribute("mensaje", "Error, no existe el archivo en el directorio.");
return "redirect:/";
}
return null;
}
}
| 41.316038 | 183 | 0.647106 |
57b49442d12b4c01f7d08d4c24237ee0ffa7500f | 802 |
package amat.occupy;
import java.util.Arrays;
import java.util.Collection;
import amat.antigen.Antigen;
import amat.antigen.AntigenPool;
/**
* Implements a follicular dendritic cell (FDC) occupation model in
* which exactly one antigen occupies an FDC surface site.
*
* The occupation probability for a given antigen is equal to its
* fractional concentration (its concentration divided by the total
* antigen concentration).
*/
public final class OneOccupationModel extends OccupationModel {
private OneOccupationModel() {}
/**
* The singleton instance.
*/
public static final OneOccupationModel INSTANCE = new OneOccupationModel();
@Override public Collection<Antigen> visit(int cycle, AntigenPool pool) {
return Arrays.asList(pool.select());
}
}
| 26.733333 | 79 | 0.739401 |
6c3cb8c525c176399836ed43c460741ad2e83c3a | 1,919 | /*
* Copyright (C) 2017 AutSoft Kft.
*
* 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 hu.axolotl.tasklib.base;
import hu.axolotl.tasklib.RxTaskMessage;
import hu.axolotl.tasklib.TaskAgent;
import hu.axolotl.tasklib.util.TaskLogger;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
public abstract class BaseRunTask<T, U> extends BaseTask<T, U> {
@Override
public final Flowable<RxTaskMessage<T, U>> createFlowable() {
return Flowable.create(new FlowableOnSubscribe<RxTaskMessage<T, U>>() {
@Override
public void subscribe(final FlowableEmitter<RxTaskMessage<T, U>> e) throws Exception {
TaskLogger.v(TAG, "subscribe start");
T innerResult = run(new TaskAgent<U>() {
@Override
public void publishProgress(U progressObject) {
TaskLogger.v(TAG, "onProgress");
e.onNext(RxTaskMessage.<T, U>createProgress(progressObject));
}
});
e.onNext(RxTaskMessage.<T, U>createResult(innerResult));
e.onComplete();
TaskLogger.v(TAG, "subscribe end");
}
}, BackpressureStrategy.ERROR);
}
protected abstract T run(TaskAgent<U> agent);
}
| 37.627451 | 98 | 0.656592 |
5b64a690a15295b26a25ad9c4d4d7cd05982bb07 | 622 | package org.acme.order_fulfillment;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.api.runtime.process.WorkItemManager;
public class RestMockWih implements WorkItemHandler {
public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
manager.abortWorkItem(workItem.getId());
}
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
String url = (String) workItem.getParameter("Url");
System.out.println("REST Web service executed at endpoint: " + url);
manager.completeWorkItem(workItem.getId(), null);
}
}
| 28.272727 | 74 | 0.786174 |
be944ec6f59b74203b4df3dabff7e42265ae1218 | 1,892 | /*
* 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.sirona.configuration;
import org.apache.sirona.configuration.ioc.IoCs;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class IoCsTest {
@Test
public void field() throws Exception {
assertEquals("field-value", IoCs.autoSet(new Field()).field);
}
@Test
public void method() throws Exception {
assertEquals("method-value", IoCs.autoSet(new Method()).value);
}
@Test
public void methodPreventField() throws Exception {
assertEquals("method-value-again", IoCs.autoSet(new MethodNotField()).methodNotField.value);
}
public static class Field {
private String field;
}
public static class Method {
private String value;
public void setMethod(final String v) {
value = v;
}
}
public static class MethodNotField {
private Method methodNotField = null;
public void setMethodNotField(final String v) {
methodNotField = new Method();
methodNotField.setMethod(v);
}
}
}
| 31.016393 | 100 | 0.69186 |
a0ac1640645a0696ab8e097c7d5740063d1f551a | 1,506 | package ch.goodrick.brewcontrol.button;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class FakeButtonTest {
FakeButton fb = new FakeButton();
@Test
public void testWithListener() {
final Set<Boolean> clicked = new HashSet<Boolean>();
ButtonChangeListener listener = new ButtonChangeListener() {
@Override
public void onStateChangedEvent(ButtonState event) {
clicked.add(true);
}
};
fb.addListener(listener);
fb.setState(ButtonState.ON);
assertTrue(fb.isOn());
assertFalse(fb.isOff());
assertEquals(fb.getState(), ButtonState.ON);
fb.notifyListeners();
assertTrue(clicked.contains(true));
fb.removeListener(listener);
fb.setState(ButtonState.OFF);
assertFalse(fb.isOn());
assertTrue(fb.isOff());
assertTrue(fb.isState(ButtonState.OFF));
assertEquals(fb.getState(), ButtonState.OFF);
}
@Test
public void testWithoutListener() {
final Set<Boolean> clicked = new HashSet<Boolean>();
ButtonChangeListener listener = new ButtonChangeListener() {
@Override
public void onStateChangedEvent(ButtonState event) {
clicked.add(true);
}
};
fb.setState(ButtonState.ON);
assertTrue(fb.isOn());
assertFalse(fb.isOff());
assertEquals(fb.getState(), ButtonState.ON);
fb.notifyListeners();
assertFalse(clicked.contains(true));
fb.removeListener(listener);
}
}
| 24.688525 | 62 | 0.731076 |
411c8be8aab502ccd10844b4663fe4deb73606d6 | 5,033 | package com.tinkerpop.blueprints;
/**
* A Graph is a container object for a collection of vertices and a collection edges.
*
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public interface Graph {
/**
* Get the particular features of the graph implementation.
* Not all graph implementations are identical nor perfectly implement the Blueprints API.
* The Features object returned contains meta-data about numerous potential divergences between implementations.
*
* @return the features of this particular Graph implementation
*/
public Features getFeatures();
/**
* Create a new vertex, add it to the graph, and return the newly created vertex.
* The provided object identifier is a recommendation for the identifier to use.
* It is not required that the implementation use this identifier.
*
* @param id the recommended object identifier
* @return the newly created vertex
*/
public Vertex addVertex(Object id);
/**
* Return the vertex referenced by the provided object identifier.
* If no vertex is referenced by that identifier, then return null.
*
* @param id the identifier of the vertex to retrieved from the graph
* @return the vertex referenced by the provided identifier or null when no such vertex exists
*/
public Vertex getVertex(Object id);
/**
* Remove the provided vertex from the graph.
* Upon removing the vertex, all the edges by which the vertex is connected must be removed as well.
*
* @param vertex the vertex to remove from the graph
*/
public void removeVertex(Vertex vertex);
/**
* Return an iterable to all the vertices in the graph.
* If this is not possible for the implementation, then an UnsupportedOperationException can be thrown.
*
* @return an iterable reference to all vertices in the graph
*/
public Iterable<Vertex> getVertices();
/**
* Return an iterable to all the vertices in the graph that have a particular key/value property.
* If this is not possible for the implementation, then an UnsupportedOperationException can be thrown.
* The graph implementation should use indexing structures to make this efficient else a full vertex-filter scan is required.
*
* @param key the key of vertex
* @param value the value of the vertex
* @return an iterable of vertices with provided key and value
*/
public Iterable<Vertex> getVertices(String key, Object value);
/**
* Add an edge to the graph. The added edges requires a recommended identifier, a tail vertex, an head vertex, and a label.
* Like adding a vertex, the provided object identifier may be ignored by the implementation.
*
* @param id the recommended object identifier
* @param outVertex the vertex on the tail of the edge
* @param inVertex the vertex on the head of the edge
* @param label the label associated with the edge
* @return the newly created edge
*/
public Edge addEdge(Object id, Vertex outVertex, Vertex inVertex, String label);
/**
* Return the edge referenced by the provided object identifier.
* If no edge is referenced by that identifier, then return null.
*
* @param id the identifier of the edge to retrieved from the graph
* @return the edge referenced by the provided identifier or null when no such edge exists
*/
public Edge getEdge(Object id);
/**
* Remove the provided edge from the graph.
*
* @param edge the edge to remove from the graph
*/
public void removeEdge(Edge edge);
/**
* Return an iterable to all the edges in the graph.
* If this is not possible for the implementation, then an UnsupportedOperationException can be thrown.
*
* @return an iterable reference to all edges in the graph
*/
public Iterable<Edge> getEdges();
/**
* Return an iterable to all the edges in the graph that have a particular key/value property.
* If this is not possible for the implementation, then an UnsupportedOperationException can be thrown.
* The graph implementation should use indexing structures to make this efficient else a full edge-filter scan is required.
*
* @param key the key of the edge
* @param value the value of the edge
* @return an iterable of edges with provided key and value
*/
public Iterable<Edge> getEdges(String key, Object value);
/**
* Generate a query object that can be used to fine tune which edges/vertices are retrieved from the graph.
*
* @return a graph query object with methods for constraining which data is pulled from the underlying graph
*/
public GraphQuery query();
/**
* A shutdown function is required to properly close the graph.
* This is important for implementations that utilize disk-based serializations.
*/
public void shutdown();
}
| 39.944444 | 129 | 0.693423 |
4fd28844e7dc47fcb5d5d8c243b18e4129d1f728 | 313 | package com.example.nhoxb.mytodo.data.local;
import com.example.nhoxb.mytodo.data.model.Item;
import java.util.List;
public interface DbDataSource {
List<Item> getAllItem();
void insertItem(Item item);
void updateItem(int id, Item item);
void deleteItem(int id);
long getItemCount();
}
| 17.388889 | 48 | 0.715655 |
8ea0bc67a484f28ad7e97186997014b66e31672e | 6,012 | /*
* This file or a portion of this file is licensed under the terms of
* the Globus Toolkit Public License, found in file GTPL, or at
* http://www.globus.org/toolkit/download/license.html. This notice must
* appear in redistributions of this file, with or without modification.
*
* Redistributions of this Software, with or without modification, must
* reproduce the GTPL in: (1) the Software, or (2) the Documentation or
* some other similar material which is provided with the Software (if
* any).
*
* Copyright 1999-2004 University of Chicago and The University of
* Southern California. All rights reserved.
*/
package org.griphyn.vdl.router;
import org.griphyn.vdl.classes.*;
/**
* Create a fully connected fake Diamond DAG exmample structure in
* memory using VDL classes.<p>
* <pre>
* C --<-- A
* |\ /|
* | \ _ / |
* V | L V
* | /\ |
* | / \ |
* | / \|
* D --<-- B
* </pre>
*
* @author Jens-S. Vöckler
* @version $Revision$
*/
public class CreateFullDiamond {
/**
* create a 4 node diamond DAG as in-memory data structures employing
* the VDL classes. This is a test module for some sample concrete planning
* modules.
*
* @return a list of Transformations and Derivations, encapsulated
* as Definitions.
*/
public static Definitions create()
{
// create result vector
Definitions result = new Definitions( "test", "1.0" );
try {
// create "generate" transformation
Transformation t1 = new Transformation( "generate" );
t1.addProfile( new Profile( "hints", "pfnHint",
new Text("keg.exe") ) );
t1.addDeclare( new Declare( "a", Value.SCALAR, LFN.OUTPUT ) );
t1.addArgument( new Argument( null, new Text("-a generate -o ") ) );
t1.addArgument( new Argument( null, new Use("a",LFN.OUTPUT) ) );
result.addDefinition( t1 );
// create "gobble" transformation
Transformation t2 = new Transformation( "take1" );
t2.addProfile( new Profile( "hints", "pfnHint",
new Text("keg.exe") ) );
t2.addDeclare( new Declare( "a", Value.SCALAR, LFN.INPUT ) );
t2.addDeclare( new Declare( "b", Value.SCALAR, LFN.OUTPUT ) );
Argument t2a1 = new Argument();
t2a1.addLeaf( new Text("-a ") );
t2a1.addLeaf( new Text("take1") );
t2.addArgument(t2a1);
Argument t2a2 = new Argument();
t2a2.addLeaf( new Text("-i ") );
t2a2.addLeaf( new Use( "a", LFN.INPUT ) );
t2.addArgument(t2a2);
t2.addArgument( new Argument( null, new Text("-o") ) );
t2.addArgument( new Argument( null, new Use("b",LFN.OUTPUT) ) );
result.addDefinition( t2 );
Transformation t3 = new Transformation( "take2" );
t3.addProfile( new Profile( "hints", "pfnHint",
new Text("keg.exe") ) );
t3.addDeclare( new Declare( "a", Value.SCALAR, LFN.INPUT ) );
t3.addDeclare( new Declare( "b", Value.SCALAR, LFN.INPUT ) );
t3.addDeclare( new Declare( "c", Value.SCALAR, LFN.OUTPUT ) );
// you can do it thus...
Argument t3a1 = new Argument();
t3a1.addLeaf( new Text("-a take2 -i ") );
t3a1.addLeaf( new Use("a",LFN.INPUT) );
t3.addArgument(t3a1);
// ...or thus...
// NOTE: the space is now unnecessary, since argumentSeparator
// defaults to one space. The argumentSeparator will be applied
// when constructing the commandline from two <argument> elements.
//// t3.addArgument( new Argument( null, new Text(" ") ) );
t3.addArgument( new Argument( null, new Use("b",LFN.INPUT) ) );
// ...or thus again
Argument t3a2 = new Argument();
t3a2.addLeaf( new Text("-o ") );
t3a2.addLeaf( new Use("c",LFN.OUTPUT) );
t3.addArgument(t3a2);
result.addDefinition( t3 );
Transformation t4 = new Transformation( "analyze" );
t4.addProfile( new Profile( "hints", "pfnHint",
new Text("keg.exe") ) );
t4.addDeclare( new Declare( "abc", Value.LIST, LFN.INPUT ) );
t4.addDeclare( new Declare( "d", Value.SCALAR, LFN.OUTPUT ) );
t4.addArgument( new Argument( null, new Text("-a analyze -i") ) );
t4.addArgument( new Argument( "files", new Use( "abc", "\"", " ", "\"" ) ) );
t4.addArgument( new Argument( null, new Text( "-o") ) );
t4.addArgument( new Argument( null, new Use( "d", LFN.OUTPUT ) ) );
result.addDefinition( t4 );
// create "top" node derivation of "generate"
Derivation d1 = new Derivation( "A", "generate" );
d1.addPass( new Pass( "a", new Scalar( new LFN("f.a",LFN.OUTPUT) ) ) );
result.addDefinition( d1 );
// create "left" node derivation of "findrange"
Derivation d2 = new Derivation( "B", "take1" );
d2.addPass( new Pass( "b", new Scalar( new LFN("f.b",LFN.OUTPUT) ) ) );
d2.addPass( new Pass( "a", new Scalar( new LFN("f.a",LFN.INPUT) ) ) );
result.addDefinition( d2 );
// create "right" node derivation of "findrange"
Derivation d3 = new Derivation( "C", "take2" );
d3.addPass( new Pass( "a", new Scalar( new LFN("f.a",LFN.INPUT) ) ) );
d3.addPass( new Pass( "b", new Scalar( new LFN("f.b",LFN.INPUT) ) ) );
d3.addPass( new Pass( "c", new Scalar( new LFN("f.c",LFN.OUTPUT) ) ) );
result.addDefinition( d3 );
// create "bottom" node derivation of "analyze"
Derivation d4 = new Derivation( "D", "analyze" );
List d4_list1 = new List();
d4_list1.addScalar( new Scalar( new LFN("f.a",LFN.INPUT) ) );
d4_list1.addScalar( new Scalar( new LFN("f.b",LFN.INPUT) ) );
d4_list1.addScalar( new Scalar( new LFN("f.c",LFN.INPUT) ) );
d4.addPass( new Pass( "abc", d4_list1 ) );
d4.addPass( new Pass( "d", new Scalar( new LFN("f.d",LFN.OUTPUT) ) ) );
result.addDefinition( d4 );
}
catch ( IllegalArgumentException iae ) {
System.err.println( iae.getMessage() );
System.exit(1);
}
// finally
return result;
}
}
| 39.552632 | 83 | 0.602794 |
82420421ab923359364f93df47bb2a92df87a7f9 | 1,517 | /*
* 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 com.hm.registropersonasclientjsf.bean;
import com.hm.registropersonabusiness.service.PersonaService;
import com.hm.registropersonaentities.entities.Persona;
import com.hm.registropersonasclientjsf.util.Utilidades;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import org.apache.log4j.Logger;
import org.primefaces.PrimeFaces;
/**
*
* @author HugoM
*/
@ManagedBean(name = "personaView")
public class PersonaView implements Serializable {
private static final Logger log = Logger.getLogger(PersonaView.class);
public PersonaView() {
}
private Persona persona = new Persona();
@EJB(mappedName = "PersonaService")
private PersonaService personaService;
public void reset() {
PrimeFaces.current().resetInputs("form:panel");
}
public void save() {
try {
personaService = (PersonaService) Utilidades.getEJBRemote("PersonaService", PersonaService.class.getName());
boolean response = personaService.insertPerson(persona);
} catch (Exception e) {
}
}
public Persona getPersona() {
return persona;
}
public void setPersona(Persona persona) {
this.persona = persona;
}
}
| 25.711864 | 120 | 0.694133 |
3bb569642e35f3a87e6c9e086811c56d24fb3640 | 4,477 | // Template Source: BaseEntityRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.SynchronizationSchema;
import com.microsoft.graph.models.extensions.ExpressionInputObject;
import com.microsoft.graph.models.extensions.AttributeDefinition;
import com.microsoft.graph.models.extensions.ParseExpressionResponse;
import com.microsoft.graph.models.extensions.FilterOperatorSchema;
import com.microsoft.graph.models.extensions.AttributeMappingFunctionSchema;
import com.microsoft.graph.requests.extensions.IDirectoryDefinitionCollectionRequestBuilder;
import com.microsoft.graph.requests.extensions.IDirectoryDefinitionRequestBuilder;
import com.microsoft.graph.requests.extensions.DirectoryDefinitionCollectionRequestBuilder;
import com.microsoft.graph.requests.extensions.DirectoryDefinitionRequestBuilder;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequestBuilder;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Synchronization Schema Request Builder.
*/
public class SynchronizationSchemaRequestBuilder extends BaseRequestBuilder implements ISynchronizationSchemaRequestBuilder {
/**
* The request builder for the SynchronizationSchema
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public SynchronizationSchemaRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions);
}
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the ISynchronizationSchemaRequest instance
*/
public ISynchronizationSchemaRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions) {
return buildRequest(getOptions(requestOptions));
}
/**
* Creates the request with specific requestOptions instead of the existing requestOptions
*
* @param requestOptions the options for this request
* @return the ISynchronizationSchemaRequest instance
*/
public ISynchronizationSchemaRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
return new com.microsoft.graph.requests.extensions.SynchronizationSchemaRequest(getRequestUrl(), getClient(), requestOptions);
}
public IDirectoryDefinitionCollectionRequestBuilder directories() {
return new DirectoryDefinitionCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("directories"), getClient(), null);
}
public IDirectoryDefinitionRequestBuilder directories(final String id) {
return new DirectoryDefinitionRequestBuilder(getRequestUrlWithAdditionalSegment("directories") + "/" + id, getClient(), null);
}
public ISynchronizationSchemaParseExpressionRequestBuilder parseExpression(final String expression, final ExpressionInputObject testInputObject, final AttributeDefinition targetAttributeDefinition) {
return new SynchronizationSchemaParseExpressionRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.parseExpression"), getClient(), null, expression, testInputObject, targetAttributeDefinition);
}
public ISynchronizationSchemaFilterOperatorsCollectionRequestBuilder filterOperators() {
return new SynchronizationSchemaFilterOperatorsCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.filterOperators"), getClient(), null);
}
public ISynchronizationSchemaFunctionsCollectionRequestBuilder functions() {
return new SynchronizationSchemaFunctionsCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("microsoft.graph.functions"), getClient(), null);
}
}
| 52.670588 | 216 | 0.774403 |
e328b2ea05339b9956f6c540959760ca9404708f | 1,923 |
/* 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.flowable.engine.common.impl.transaction;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.ibatis.session.TransactionIsolationLevel;
import org.apache.ibatis.transaction.jdbc.JdbcTransaction;
/**
* Extension of the regular {@link JdbcTransaction} of Mybatis. The main difference is that the threadlocal on {@link ConnectionHolder} gets set/cleared when the connection is opened/closed.
*
* This class will be used by the Process Engine when running in 'standalone' mode (i.e. Mybatis directly vs in a transaction managed environment).
*
* @author Joram Barrez
*/
public class ContextAwareJdbcTransaction extends JdbcTransaction {
protected boolean connectionStored;
public ContextAwareJdbcTransaction(Connection connection) {
super(connection);
}
public ContextAwareJdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
super(ds, desiredLevel, desiredAutoCommit);
}
protected void openConnection() throws SQLException {
super.openConnection();
if (!connectionStored) {
ConnectionHolder.setConnection(super.connection);
}
}
@Override
public void close() throws SQLException {
ConnectionHolder.clear();
super.close();
}
}
| 33.155172 | 190 | 0.73947 |
304f8652240d0c0ad453844f63bdb766c4d65866 | 1,475 | /**
* <p>Copyright (R) 2014 我是大牛软件股份有限公司。<p>
*/
package com.woshidaniu.wjdc.dao.entites;
import java.io.Serializable;
import java.util.List;
/**
* @author Penghui.Qu(445)
* 试题管理DAO
*
* @author :康康(1571)
* 整理,优化
* */
public class WjtjtjModel implements Serializable{
private static final long serialVersionUID = -515705226392456941L;
private String id;
private String name;
private String sjly;
private String key;
private String value;
private String type;
private List<?> itemList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSjly() {
return sjly;
}
public void setSjly(String sjly) {
this.sjly = sjly;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<?> getItemList() {
return itemList;
}
public void setItemList(List<?> itemList) {
this.itemList = itemList;
}
@Override
public String toString() {
return "WjtjtjModel [id=" + id + ", name=" + name + ", sjly=" + sjly + ", key=" + key + ", value=" + value
+ ", type=" + type + ", itemList=" + itemList + "]";
}
}
| 16.388889 | 108 | 0.64678 |
0d01eefe0614ccea2c38683e83db6e8e1581a43d | 6,137 | /*
Copyright [2011] [Yao Yuan([email protected])]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.yeaya.xixibase.xixiclient;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.yeaya.xixibase.xixiclient.network.SocketManager;
import com.yeaya.xixibase.xixiclient.network.XixiSocket;
public class CacheClientManagerTest {
static String[] serverlist;
static String servers;
static boolean enableSSL = false;
static {
servers = System.getProperty("hosts");
enableSSL = System.getProperty("enableSSL") != null && System.getProperty("enableSSL").equals("true");
if (servers == null) {
try {
InputStream in = CacheClientManagerTest.class.getResourceAsStream("/test.properties");
Properties p = new Properties();
p.load(in);
in.close();
servers = p.getProperty("hosts");
enableSSL = p.getProperty("enableSSL") != null && p.getProperty("enableSSL").equals("true");
} catch (IOException e) {
e.printStackTrace();
}
}
serverlist = servers.split(",");
}
@Before
public void setUp() throws Exception {
// CacheClientManager mgr1 = CacheClientManager.getInstance(managerName1);
// cc1 = mgr1.createClient();
}
@After
public void tearDown() throws Exception {
// assertNotNull(cc1);
// cc1.flush();
}
@Test
public void testInitialize() {
XixiClientManager mgr = XixiClientManager.getInstance();
assertNotNull(mgr);
assertEquals(mgr.getName(), "default");
assertEquals(mgr.getDefaultPort(), 7788);
assertEquals(mgr.getDefaultGroupId(), 0);
mgr.setDefaultGroupId(315);
mgr.setInitConn(2);
assertEquals(mgr.getInitConn(), 2);
mgr.setMaxActiveConn(7);
assertEquals(mgr.getMaxActiveConn(), 7);
mgr.setMaxBusyTime(10000);
assertEquals(mgr.getMaxBusyTime(), 10000);
mgr.setSocketConnectTimeout(15000);
assertEquals(mgr.getSocketConnectTimeout(), 15000);
mgr.setSocketTimeout(16000);
assertEquals(mgr.getSocketTimeout(), 16000);
mgr.setNoDelay(false);
assertEquals(mgr.isNoDelay(), false);
assertNotNull(mgr.getWeightMapper());
mgr.socketManager.setSocketWriteBufferSize(32 * 1024);
assertEquals(mgr.socketManager.getSocketWriteBufferSize(), 32 * 1024);
assertEquals(mgr.getDefaultGroupId(), 315);
assertFalse(mgr.isInitialized());
boolean ret = mgr.initialize(serverlist, enableSSL);
assertTrue(ret);
ret = mgr.initialize(serverlist, enableSSL);
assertFalse(ret);
assertTrue(mgr.isInitialized());
assertNotNull(mgr.getWeightMapper());
mgr.shutdown();
assertFalse(mgr.isInitialized());
assertNotNull(mgr.getServers());
}
@Test
public void testCreateSocket() {
SocketManager mgr = new SocketManager();
int size = mgr.getSocketWriteBufferSize();
assertEquals(32768, size);
mgr.setSocketWriteBufferSize(64 * 1024);
mgr.initialize(serverlist, enableSSL);
XixiSocket socket = mgr.createSocket(serverlist[0]);
assertNotNull(socket);
socket = mgr.createSocket("unknownhost");
assertNull(socket);
mgr.shutdown();
}
@Test
public void testGetHost() {
XixiClientManager mgr = XixiClientManager.getInstance();
mgr.initialize(serverlist, enableSSL);
String host = mgr.socketManager.getHost("xixi");
assertNotNull(host);
mgr.shutdown();
}
@Test
public void testGetSocketByHost() {
SocketManager mgr = new SocketManager();
mgr.initialize(serverlist, enableSSL);
XixiSocket socket = mgr.getSocketByHost(serverlist[0]);
assertNotNull(socket);
mgr.shutdown();
}
@Test
public void testMaintain() throws InterruptedException {
XixiClientManager mgr = XixiClientManager.getInstance("testMaintain");
int mi = mgr.getMaintainInterval();
int inactiveSocketTimeout = mgr.getInactiveSocketTimeout();
mgr.setMaintainInterval(1000);
mgr.setInactiveSocketTimeout(1000);
mgr.setMaxActiveConn(2);
mgr.setInitConn(5);
mgr.initialize(serverlist, enableSSL);
mgr.socketManager.setSocketWriteBufferSize(64 * 1024);
int serverCount = mgr.getServers().length;
int activeCount = mgr.socketManager.getActiveSocketCount();
int inactiveCount = mgr.socketManager.getInactiveSocketCount();
assertEquals(2 * serverCount, activeCount);
assertEquals(3 * serverCount, inactiveCount);
XixiClient cc = mgr.createClient(315);
cc.set("xixi", "0315");
activeCount = mgr.socketManager.getActiveSocketCount();
inactiveCount = mgr.socketManager.getInactiveSocketCount();
Thread.sleep(2000);
activeCount = mgr.socketManager.getActiveSocketCount();
inactiveCount = mgr.socketManager.getInactiveSocketCount();
assertEquals(2 * serverCount, activeCount);
assertTrue(inactiveCount < 3 * serverCount);
mgr.setMaintainInterval(mi);
mgr.setInactiveSocketTimeout(inactiveSocketTimeout);
mgr.shutdown();
}
@Test
public void testError() {
SocketManager mgr = new SocketManager();
boolean ret = mgr.initialize(null, enableSSL);
assertFalse(ret);
ret = mgr.initialize(new String[0], null, enableSSL);
assertFalse(ret);
String[] s = new String[1];
s[0] = "errorHost";
ret = mgr.initialize(s, enableSSL);
assertTrue(ret);
XixiSocket socket = mgr.getSocketByHost(serverlist[0]);
assertNull(mgr.getSocketByHost(null));
assertNull(mgr.getSocketByHost("unknownhost"));
assertNull(socket);
socket = mgr.getSocketByHost("errorHost");
assertNull(socket);
mgr.shutdown();
}
} | 32.470899 | 105 | 0.716311 |
6e20d37d561faee926a5f1027f510b2c5b18e2ef | 1,170 | package com.pinicius.android.cas2016.speaker.view.renderer;
import com.pedrogomez.renderers.Renderer;
import com.pedrogomez.renderers.RendererBuilder;
import com.pinicius.android.cas2016.speaker.view.presenter.SpeakersPresenter;
import com.pinicius.android.cas2016.speaker.view.viewmodel.SpeakerViewModel;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Created by pinicius on 29/11/16.
*/
public class SpeakerRendererBuilder extends RendererBuilder<SpeakerViewModel> {
private Map<Class, Class> renderingMapping = new HashMap<>();
public SpeakerRendererBuilder(SpeakersPresenter presenter) {
List<Renderer<SpeakerViewModel>> prototypes = new LinkedList<>();
prototypes.add(new SpeakerRenderer(presenter));
renderingMapping.put(SpeakerViewModel.class, SpeakerRenderer.class);
setPrototypes(prototypes);
}
@Override
protected Class getPrototypeClass(SpeakerViewModel content) {
if(content != null) {
return renderingMapping.get(content.getClass());
}
else
return super.getPrototypeClass(content);
}
}
| 32.5 | 79 | 0.742735 |
001125641efe35fc1bad90151289f19d944a36fe | 595 | package L7;
public class Sort012 {
public static void sort(int[] a) {
if(a.length <= 1) {
return;
}
int i = 0, nextZero = 0, nextTwo = a.length-1;
while(i <= nextTwo) {
if(a[i] == 0) {
int temp = a[i];
a[i] = a[nextZero];
a[nextZero] = temp;
i++;
nextZero++;
}
else if(a[i] == 2) {
int temp = a[i];
a[i] = a[nextTwo];
a[nextTwo] = temp;
nextTwo--;
}
else {
i++;
}
}
}
public static void main(String[] args) {
int a[] = {0,1,1,0,1,2,1,2,0,0,0,1};
sort(a);
for(int i : a) {
System.out.println(i);
}
}
}
| 14.875 | 48 | 0.477311 |
49230a4c5bc98489eccdccbf49544f0c038a5381 | 2,901 | package com.github.junlong.cmd;
import com.github.junlong.util.LogUtil;
import org.apache.commons.cli.Option;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* find file cmd
*
* @author junlong
* @version : FindCmd.java, v 0.1 2020年08月11日 9:52 PM junlong Exp $
*/
public class FindCmd implements Cmd {
private static final Logger LOGGER = LoggerFactory.getLogger(FindCmd.class);
/** path option */
private static final Option path =
Option.builder("p")
.longOpt("path")
.argName("path")
.numberOfArgs(1)
.hasArg(true)
.desc("the particular path to find target file.")
.build();
/** regex option */
private static Option expression =
Option.builder("e")
.longOpt("expression")
.argName("expression")
.numberOfArgs(1)
.hasArg(true)
.optionalArg(true)
.desc("regex to match the filename.")
.build();
/** regex pattern */
private Pattern pattern;
/** regex expression */
private String regexStr;
@Override
public void execute(Context context) {
Option pathOpt = context.getOption(path.getOpt());
if (pathOpt == null || StringUtils.isBlank(pathOpt.getValue())) {
throw new IllegalArgumentException("illegal option!");
}
File file = new File(StringUtils.trim(pathOpt.getValue()));
if (!file.exists()) {
LogUtil.error(LOGGER, "path=%s not exist!", pathOpt.getValue());
return;
}
Option expOpt = context.getOption(expression.getOpt());
if (expOpt != null) {
String str = StringUtils.trim(expOpt.getValue());
if (StringUtils.isNotBlank(str) && !StringUtils.equals(str, regexStr)) {
try {
pattern = Pattern.compile(str);
regexStr = StringUtils.trim(str);
} catch (Throwable e) {
LogUtil.error(LOGGER, e, "illegal regex=%s", regexStr);
return;
}
}
}
List<File> fileList = new LinkedList<File>();
listFiles(file, fileList);
context.setFileList(fileList);
}
/**
* list files
*
* @param f
* @param files
*/
private void listFiles(File f, List<File> files) {
if (f.isDirectory()) {
// list files
File[] list = f.listFiles();
for (File t : list) {
listFiles(t, files);
}
return;
}
if (pattern == null) {
files.add(f);
return;
}
Matcher m = pattern.matcher(f.getName());
if (m.find()) {
files.add(f);
} else {
LogUtil.debug(LOGGER, "regex,skip file src=%s", f.getAbsolutePath());
}
}
@Override
public Option[] options() {
return new Option[] {path, expression};
}
}
| 25.226087 | 78 | 0.606343 |
9fb612c272c84b8060ffc49e1101a3fc037fc98e | 285 | package org.dayatang.domain.internal.criterion;
/**
* 代表属性小于或等于指定值的查询条件
* @author yyang
*/
public class LeCriterion extends ValueCompareCriterion {
public LeCriterion(String propName, Comparable<?> value) {
super(propName, value);
setOperator(" <= ");
}
}
| 20.357143 | 62 | 0.680702 |
df6c0ce362a6a8d6a8a9711b8ec77ad6bf973437 | 395 | package com.bookshop.shoppingcartms.dto;
import java.math.BigDecimal;
import java.math.BigInteger;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class ProductDTO {
private String id;
private String title;
private String description;
private BigDecimal price;
private BigInteger quantity;
private String picUrl;
}
| 18.809524 | 40 | 0.812658 |
3c7bb84e29b71d2b47b88cb00419c239b9c637e1 | 6,640 | /*
* Copyright 2012 Sauce Labs
*
* 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.sebuilder.interpreter.step;
import com.sebuilder.interpreter.StepType;
import java.util.HashMap;
/**
* Factory to create a StepType object from the step's name. Each step can be
* loaded from a settable primary package or a secondary package. Thanks to this
* mechanism, steps can be easily overridden when needed.
*
* @author jkowalczyk
*/
public class StepTypeFactoryImpl implements com.sebuilder.interpreter.StepTypeFactory {
public static final String DEFAULT_PACKAGE = "com.sebuilder.interpreter.step";
/**
* Mapping of the names of step types to their implementing classes, lazily
* loaded through reflection. StepType classes must be either in the first
* package either in the second one and their name must be the capitalized
* name of their type. For example, the class for "getChainTo" is at
* com.sebuilder.interpreter.steptype.Get.
* <p>
* Assert/Verify/WaitFor/Store steps use "Getter" objects that encapsulate
* how to getChainTo the value they are about. Getters should be named e.g "Title"
* for "verifyTitle" and also be in the com.sebuilder.interpreter.steptype
* package.
*/
private final HashMap<String, StepType> typesMap = new HashMap<String, StepType>();
/**
* @param name
* @return a stepType instance for a given name
*/
@Override
public StepType getStepTypeOfName(String name) {
try {
if (!this.typesMap.containsKey(name)) {
String className = name.substring(0, 1).toUpperCase() + name.substring(1);
boolean rawStepType = true;
if (name.startsWith("assert")) {
className = className.substring("assert".length());
rawStepType = false;
}
if (name.startsWith("verify")) {
className = className.substring("verify".length());
rawStepType = false;
}
if (name.startsWith("waitFor")) {
className = className.substring("waitFor".length());
rawStepType = false;
}
if (name.startsWith("store") && !name.equals("store")) {
className = className.substring("store".length());
rawStepType = false;
}
if (name.startsWith("print") && !name.equals("print")) {
className = className.substring("print".length());
rawStepType = false;
}
if (name.startsWith("if")) {
className = className.substring("if".length());
rawStepType = false;
}
if (name.startsWith("retry")) {
className = className.substring("retry".length());
rawStepType = false;
}
Class<?> c;
if (className.equals("Loop")) {
c = Loop.class;
} else if (rawStepType) {
c = newStepType(name, className);
} else {
c = newGetter(name, className);
}
try {
Object o = c.getDeclaredConstructor().newInstance();
if (name.startsWith("assert")) {
this.typesMap.put(name, Getter.class.cast(o).toAssert());
} else if (name.startsWith("verify")) {
this.typesMap.put(name, Getter.class.cast(o).toVerify());
} else if (name.startsWith("waitFor")) {
this.typesMap.put(name, Getter.class.cast(o).toWaitFor());
} else if (name.startsWith("store") && !name.equals("store")) {
this.typesMap.put(name, Getter.class.cast(o).toStore());
} else if (name.startsWith("print") && !name.equals("print")) {
this.typesMap.put(name, Getter.class.cast(o).toPrint());
} else if (name.startsWith("if") && !name.equals("if")) {
this.typesMap.put(name, Getter.class.cast(o).toIf());
} else if (name.startsWith("retry") && !name.equals("retry")) {
this.typesMap.put(name, Getter.class.cast(o).toRetry());
} else {
this.typesMap.put(name, (StepType) o);
}
} catch (InstantiationException | IllegalAccessException ie) {
throw new RuntimeException(c.getName() + " could not be instantiated.", ie);
} catch (ClassCastException cce) {
throw new RuntimeException(c.getName() + " does not extend "
+ (rawStepType ? "StepType" : "Getter") + ".", cce);
}
}
return this.typesMap.get(name);
} catch (Exception e) {
throw new RuntimeException("Step type \"" + name + "\" is not implemented.", e);
}
}
protected Class<?> newGetter(String name, String className) {
final String errorMessage = "No implementation class for getter \"" + name + "\" could be found.";
final String subPackage = ".getter.";
return newInstance(className, errorMessage, subPackage);
}
protected Class<?> newStepType(String name, String className) {
final String errorMessage = "No implementation class for step type \"" + name + "\" could be found.";
final String subPackage = ".type.";
return newInstance(className, errorMessage, subPackage);
}
private Class<?> newInstance(String className, String errorMessage, String subPackage) {
Class<?> c = null;
try {
c = Class.forName(DEFAULT_PACKAGE + subPackage + className);
} catch (ClassNotFoundException cnfe) {
throw new RuntimeException(errorMessage, cnfe);
}
return c;
}
} | 45.170068 | 109 | 0.5625 |
a91f31340e1b5e4ba233d471c42c2cf2158d4dfd | 4,648 | package com.vlkan.log4j2.logstash.layout.resolver;
import com.fasterxml.jackson.core.JsonGenerator;
import com.vlkan.log4j2.logstash.layout.util.Throwables;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.LogEvent;
import java.io.IOException;
class ExceptionRootCauseResolver implements EventResolver {
private static final ExceptionInternalResolverFactory INTERNAL_RESOLVER_FACTORY =
new ExceptionInternalResolverFactory() {
@Override
EventResolver createClassNameResolver() {
return new EventResolver() {
@Override
public void resolve(LogEvent logEvent, JsonGenerator jsonGenerator) throws IOException {
Throwable exception = logEvent.getThrown();
if (exception == null) {
jsonGenerator.writeNull();
} else {
Throwable rootCause = Throwables.getRootCause(exception);
String rootCauseClassName = rootCause.getClass().getCanonicalName();
jsonGenerator.writeString(rootCauseClassName);
}
}
};
}
@Override
EventResolver createMessageResolver(final EventResolverContext context) {
return new EventResolver() {
@Override
public void resolve(LogEvent logEvent, JsonGenerator jsonGenerator) throws IOException {
Throwable exception = logEvent.getThrown();
if (exception != null) {
Throwable rootCause = Throwables.getRootCause(exception);
String rootCauseMessage = rootCause.getMessage();
boolean rootCauseMessageExcluded = context.isEmptyPropertyExclusionEnabled() && StringUtils.isEmpty(rootCauseMessage);
if (!rootCauseMessageExcluded) {
jsonGenerator.writeString(rootCauseMessage);
return;
}
}
jsonGenerator.writeNull();
}
};
}
@Override
EventResolver createStackTraceTextResolver(final EventResolverContext context) {
return new EventResolver() {
@Override
public void resolve(LogEvent logEvent, JsonGenerator jsonGenerator) throws IOException {
Throwable exception = logEvent.getThrown();
if (exception == null) {
jsonGenerator.writeNull();
} else {
Throwable rootCause = Throwables.getRootCause(exception);
StackTraceTextResolver.getInstance().resolve(rootCause, jsonGenerator);
}
}
};
}
@Override
EventResolver createStackTraceObjectResolver(final EventResolverContext context) {
return new EventResolver() {
@Override
public void resolve(LogEvent logEvent, JsonGenerator jsonGenerator) throws IOException {
Throwable exception = logEvent.getThrown();
if (exception == null) {
jsonGenerator.writeNull();
} else {
Throwable rootCause = Throwables.getRootCause(exception);
context.getStackTraceObjectResolver().resolve(rootCause, jsonGenerator);
}
}
};
}
};
private final EventResolver internalResolver;
ExceptionRootCauseResolver(EventResolverContext context, String key) {
this.internalResolver = INTERNAL_RESOLVER_FACTORY.createInternalResolver(context, key);
}
static String getName() {
return "exceptionRootCause";
}
@Override
public void resolve(LogEvent logEvent, JsonGenerator jsonGenerator) throws IOException {
internalResolver.resolve(logEvent, jsonGenerator);
}
}
| 45.568627 | 150 | 0.5142 |
3263c8d20ac1a9dd765ec0fa97bfc7c0fe8a0f4b | 691 | package com.alibaba.alink.pipeline.dataproc;
import org.apache.flink.ml.api.misc.param.Params;
import com.alibaba.alink.operator.batch.BatchOperator;
import com.alibaba.alink.operator.common.dataproc.AggLookupModelMapper;
import com.alibaba.alink.params.dataproc.AggLookupParams;
import com.alibaba.alink.pipeline.MapModel;
/**
* model for VectorMatch.
*/
public class AggLookup extends MapModel <AggLookup>
implements AggLookupParams <AggLookup> {
public AggLookup(Params params) {
super(AggLookupModelMapper::new, params);
}
public AggLookup() {
super(AggLookupModelMapper::new, new Params());
}
public BatchOperator <?> getVectors() {
return this.getModelData();
}
}
| 24.678571 | 71 | 0.775687 |
4f05ac0c2fafc27fe5af6d4907b0c3632d05a5d5 | 571 | package com.alibaba.oneagent.utils;
import java.io.File;
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
/**
*
* @author hengyunabc 2020-07-31
*
*/
public class JarUtils {
public static Attributes read(File jarFile) throws IOException {
JarFile jar = null;
Attributes attributes = null;
try {
jar = new JarFile(jarFile);
Manifest manifest = jar.getManifest();
attributes = manifest.getMainAttributes();
} finally {
IOUtils.close(jar);
}
return attributes;
}
}
| 17.84375 | 65 | 0.711033 |
f3caae05b06ed7804e9fefaf5d4d7f6dfef64b0a | 482 | package controller;
public class Error { // Class for error handling.
public static int count = 0; // Error count for current session.
private int errorID;
public Error() { // Default null constructor
this("general unspecified error");
}
public Error(String error_msg)
{
// this.errorID = date * 10 + ++count; // Move date all to the tens place before adding in the count. a date and a count makes up the UID
// write the error to file before closing stream
}
} | 26.777778 | 138 | 0.70332 |
764fe95b2aa3be45e610c282a57305bfdff51b40 | 3,938 | package com.ai.aspire.authentication;
import java.io.IOException;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ai.application.interfaces.IInitializable;
import com.ai.application.interfaces.RequestExecutionException;
import com.ai.application.utils.AppObjects;
import com.ai.servletutils.ServletUtils;
/**
* Take a request and response and implmment
* an http authenication method.
*
* Return a valid user once authenticated.
* Return a null if the user is not valid
*
* I suppose you can use request URI to see if
* the URI is a public or a private URI
*
* It is anticipated to have two types of methods at a high level
*
* 1. Basic Auth
* 2. Digest Auth
*
* May be more or a variation of each
*
*/
public class BaseAuthenticationMethod
implements IHttpAuthenticationMethod
,IInitializable
{
private IAuthentication2 authHandler = null;
//Initialize the auth handler
@Override
public void initialize(String requestName)
{
try
{
authHandler = (IAuthentication2)
AppObjects.getObject(IAuthentication.NAME, null);
}
catch(RequestExecutionException x)
{
throw new RuntimeException("Not able to get authentication object",x);
}
}
/*******************************************************************************
* String getUserIfValid(HttpServletRequest request )
* return null if the user authorization fails
* if no authorization is indicated then the user is returned as annonymous
*******************************************************************************
*/
public String getUserIfValid(HttpServletRequest request,
HttpServletResponse response )
throws AuthorizationException
{
AppObjects.info(this,"Inside Http Base Auth");
String auth = request.getHeader("Authorization");
String realm = authHandler.getRealm();
AppObjects.info(this,"Authorization :%1s", auth);
//set the header if the authroization for this url is missing
if (auth == null)
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-authenticate","Basic realm=\"" + realm + "\"");
//Indicate that authenticated user is null
//This will in turn return a null session
//The null session inturn forces the base servlet to return immediately
//with the unauthorized code set above.
return null;
}
String user = null;
boolean valid = false;
try
{
String userPassEncoded = auth.substring(6);
// decode the userPass
sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
String userPassDecoded = new String(dec.decodeBuffer(userPassEncoded));
AppObjects.secure(this,"Userid + password :%1s",userPassDecoded);
// Separate userid, password
StringTokenizer tokenizer = new StringTokenizer(userPassDecoded,":");
if (!tokenizer.hasMoreTokens()){ return null; }
user = tokenizer.nextToken();
String password = tokenizer.nextToken();
// See if this is the valid user
valid = ServletUtils.verifyPassword(user,password);
}
catch(IOException x)
{
AppObjects.log(x);
}
catch (IndexOutOfBoundsException x)
{
AppObjects.log(x);
}
catch(AuthorizationException x)
{
AppObjects.error(this,"Could not authorize user");
AppObjects.log(x);
}
finally
{
// valid user
if (valid) return user;
// Invalid user
AppObjects.warn(this,"Invalid user");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-authenticate","Basic realm=\"" + realm + "\"");
return null;
}
} // end-getUserIfValid
}//eof-class
| 32.278689 | 82 | 0.642204 |
a1d006f07dafcf6c8bd48228fc112dfa8afa77f1 | 2,428 | package guys;
import world.Object3D;
import linalg.Vec3;
import world.Simulatable;
import world.Directed;
import linalg.StatePair;
import common.CardinalDirection;
import java.lang.Math;
/**
* @brief Represents Homo Sapiens in this rude world
*/
public class Guy extends Object3D implements Directed, Simulatable {
/**
* @return String that expresses current ideas of the creature about the world
*/
public String describeSituation() {
if (Math.random() < .5)
return "Amma just a usual guy";
return "Life is not that bad";
}
/**
* @brief Position related life stats
* @return Life stats
*/
public String lifeStats() {
float height = position.getValue().getZ();
if (height > 1e5)
return "It's like vaccume here, imma dead :(";
else if (height > 1.5e4)
return "It's dead cold out there, my pants are full of ice";
else if (height > 1e3)
return "It's kinda cold out there";
else if (height > 5e2)
return "Cant's see anything because of clouds";
return "Everything looks beautiful!";
}
/**
* @param point Object in the world to look at
* @return Eye vector
*/
public Vec3 lookAt(Object3D point) {
return Vec3.sub(point.getPosition().getValue(), position.getValue());
}
@Override
public void tick(float dt) {
position.integrate(dt);
orientation.integrate(dt);
}
@Override
public CardinalDirection resolveDirection() {
Vec3 direction = orientation.getValue();
double heading = Math.atan2(direction.getY(), direction.getX());
heading /= Math.PI;
if (heading < .0) heading += 2.;
heading += .125;
heading *= 4.;
int headingIndex = (int)heading;
return CardinalDirection.fromIndex(headingIndex % 8);
}
@Override
public Vec3 resolveDirectionVector() {
return orientation.getValue();
}
@Override
public String toString() {
if (name != null)
return name;
if (Math.random() < .5)
return "Regular one";
return "Nobody";
}
/**
* @brief Default-initialized guy that looks at south and has random position and orientation
*/
public Guy() {
eyeDirection = new Vec3(1, 0, 0);
position = StatePair.makeRandom(-3.14f, 3.14f);
orientation = StatePair.makeRandom(-3.14f, 3.14f);
}
/**
* @brief Mostly not interesting, but named guy that looks at south and has random position and orientation
*/
public Guy(String name) {
this();
this.name = name;
}
private String name = null;
protected Vec3 eyeDirection;
}
| 22.691589 | 107 | 0.689456 |
e22adc9732a188de0364607b7a202f0478a3b4cf | 567 | // SPDX-FileCopyrightText: 2021 Falk Howar [email protected]
// SPDX-License-Identifier: Apache-2.0
// This file is part of the SV-Benchmarks collection of verification tasks:
// https://gitlab.com/sosy-lab/benchmarking/sv-benchmarks
package mock.sql;
public class Connection {
public void prepareStatement(String s) throws SQLException {
if (s.contains("<bad/>")) {
assert false;
}
}
public void close() throws SQLException{
}
public Statement createStatement() {
return new Statement();
}
}
| 23.625 | 75 | 0.671958 |
73d972e0536626774ecd52ff59854051ea6f12c6 | 1,078 | package com.ekam.utilities.excelwriter.base;
import java.util.HashMap;
import java.util.Map;
public final class WriteConfig {
public static final String CONFIG_OUTPUT_FILE_LOCATION = "CONFIG_FILE_LOCATION";
public static final String CONFIG_OUTPUT_FILE_NAME = "CONFIG_OUTPUT_FILE_NAME";
public static final String CONFIG_CURRENT_SHEET ="CONFIG_CURRENT_SHEET";
public static final String CONFIG_WORKBOOK = "CONFIG_WORKBOOK";
public static final String CONFIG_CURRENT_ROW_CELL_COUNTER ="CONFIG_CURRENT_ROW_CELL_COUNTER";
private Map<String, Object> data;
public WriteConfig() {
data = new HashMap<String, Object>();
}
public WriteConfig put(String key, Object value) {
data.put(key, value);
return this;
}
public String getString(String key){
return (String)data.get(key);
}
public <T> T get(String key, Class<T> type){
return type.cast(data.get(key));
}
public Object remove(String key) {
return data.remove(key);
}
public boolean containsKey(String key){
return data.containsKey(key);
}
}
| 25.666667 | 96 | 0.729128 |
ef1a3bc6cac82352ad9d76e5cb55826a176d2754 | 5,351 | /*
* Copyright (c) 2009-2015 farmafene.com
* 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 THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.farmafene.commons.j2ee.tools.jca;
import java.security.Principal;
import java.util.Map;
import java.util.Properties;
import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;
import javax.ejb.MessageDrivenContext;
import javax.ejb.TimerService;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
public class DefaultMessageDrivenContext implements MessageDrivenContext {
private UserTransaction userTransaction;
private Context context;
private Map<String, Object> contextData;
public DefaultMessageDrivenContext() {
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append("={");
sb.append("}");
return sb.toString();
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#getEJBHome()
*/
@Override
public EJBHome getEJBHome() {
throw new UnsupportedOperationException(this + ", Not supported!");
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#getEJBLocalHome()
*/
@Override
public EJBLocalHome getEJBLocalHome() {
throw new UnsupportedOperationException(this + ", Not supported!");
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#getEnvironment()
*/
@Override
public Properties getEnvironment() {
throw new UnsupportedOperationException(this + ", Not supported!");
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#getCallerIdentity()
*/
@Deprecated
@Override
public java.security.Identity getCallerIdentity() {
throw new UnsupportedOperationException(this + ", Not supported!");
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#getCallerPrincipal()
*/
@Override
public Principal getCallerPrincipal() {
throw new UnsupportedOperationException(this + ", Not supported!");
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#isCallerInRole(java.security.Identity)
*/
@Override
@Deprecated
public boolean isCallerInRole(java.security.Identity role) {
throw new UnsupportedOperationException(this + ", Not supported!");
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#isCallerInRole(java.lang.String)
*/
@Override
public boolean isCallerInRole(String roleName) {
throw new UnsupportedOperationException(this + ", Not supported!");
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#getUserTransaction()
*/
@Override
public UserTransaction getUserTransaction() throws IllegalStateException {
return userTransaction;
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#setRollbackOnly()
*/
@Override
public void setRollbackOnly() throws IllegalStateException {
try {
getUserTransaction().setRollbackOnly();
} catch (SystemException e) {
throw new IllegalStateException(e);
}
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#getRollbackOnly()
*/
@Override
public boolean getRollbackOnly() throws IllegalStateException {
try {
return Status.STATUS_MARKED_ROLLBACK == getUserTransaction()
.getStatus();
} catch (SystemException e) {
throw new IllegalStateException(e);
}
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#getTimerService()
*/
@Override
public TimerService getTimerService() throws IllegalStateException {
throw new UnsupportedOperationException(this + ", Not supported!");
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#lookup(java.lang.String)
*/
@Override
public Object lookup(String name) {
try {
return context.lookup(name);
} catch (NamingException e) {
throw new IllegalArgumentException(e);
}
}
/**
* {@inheritDoc}
*
* @see javax.ejb.EJBContext#getContextData()
*/
@Override
public Map<String, Object> getContextData() {
return contextData;
}
}
| 25.725962 | 76 | 0.680807 |
bb186004d8d2f09439c04305717fe7974d4ac66d | 5,939 | package com.theberge_stonis.game;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import com.theberge_stonis.entity.*;
import com.theberge_stonis.input.KeyInput;
import com.theberge_stonis.input.KeyListener;
import com.theberge_stonis.input.MouseInput;
import com.theberge_stonis.input.MouseListener;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
//import javafx.scene.layout.VBox;
//import javafx.scene.text.Text;
import javafx.stage.Stage;
/**
* The main game class.
*
* This class handles all entities, updating, drawing, and the
* application itself. Contains a main function to launch the
* application.
*
* @author Conner Theberge
*
*/
public final class Game extends Application {
public static void main(String args[]) {
launch(args);
}
private static Player player;
public static Player getPlayer() { return player; }
private static Room mainRoom = new Room();
public static void regen() { mainRoom.generate( System.currentTimeMillis() ); }
public static Room getRoom() { return mainRoom; }
public static final String RESOURCE_PATH = "File:Resources/";
private static LinkedList< KeyListener > allKeyListeners = new LinkedList< KeyListener >();
public static LinkedList< KeyListener > getKeyListeners() { return allKeyListeners; }
private static LinkedList< MouseListener > allMouseListeners = new LinkedList< MouseListener >();
public static LinkedList< MouseListener > getMouseListeners() { return allMouseListeners; }
public static void addKeyListener( KeyListener kl ) { allKeyListeners.add( kl ); }
public static void addMouseListener( MouseListener ml ) { allMouseListeners.add( ml ); }
/**
* The instance that handles event-driven key input
*/
public static KeyInput keyIn = new KeyInput();
public static KeyInput getKeyInput() { return keyIn; }
/**
* The instance that handles event-driven mouse input
*/
public static MouseInput mouseIn = new MouseInput();
public static MouseInput getMouseInput() { return mouseIn; }
private static Map< Class< ? extends Element >, LinkedList< Element > > allElements = new HashMap<>();
public static < T extends Element > LinkedList< T > getObjectList( Class< T > objectClass ) {
LinkedList< T > objects = new LinkedList<>();
if ( allElements.containsKey( objectClass ) ) {
for( Element e : allElements.get( objectClass ) ) {
objects.add( objectClass.cast( e ) );
}
}
return objects;
}
private static < T extends Element > void addObject( Class< ? extends Element > objClass, T object ) {
if ( !allElements.containsKey( objClass ) ) {
allElements.put( objClass, new LinkedList< Element >() );
}
allElements.get( objClass ).add( object );
}
private static < T extends Element > void deleteObject( Class< ? extends Element > objClass, T object ) {
if ( allElements.get( objClass ).contains( object ) ) {
allElements.get( objClass ).remove( object );
}
}
@SuppressWarnings("unchecked")
public static < T extends Element > void activateElement( T object ) {
Class< ? extends Element > curClass = object.getClass();
while( curClass != Element.class ) {
addObject( curClass, object );
curClass = ( Class<? extends Element> )curClass.getSuperclass();
}
addObject( Element.class, object );
}
@SuppressWarnings("unchecked")
public static < T extends Element > void deactivateElement( T object ) {
Class< ? extends Element > curClass = object.getClass();
while( curClass != Element.class ) {
deleteObject( curClass, object );
curClass = ( Class<? extends Element> )curClass.getSuperclass();
}
deleteObject( Element.class, object );
object.delete();
}
private static Window mainWindow = new Window();
public static Window getWindow() { return mainWindow; }
public static void pauseLoop() { gameLoop.stop(); }
public static void resumeLoop() { gameLoop.start(); }
@Override
public void start(Stage arg0) throws Exception {
//Init
Group g = new Group();
Scene scene = new Scene(g);
/*
* This object gets added to lists automatically in their constructor.
* However, I should change this to prevent warnings from being a problem.
*/
player = new Player(200,200,32,32,100);
activateElement(player);
g.getChildren().add(mainWindow.getMyPane());
arg0.setScene(scene);
arg0.show();
mainRoom.generate();
//Game Loop Run
gameLoop.start();
}
//GAME LOOP
private static AnimationTimer gameLoop = new AnimationTimer() {
@Override
public void handle(long now) {
//Game Loop
updateAll();
drawAll();
}
public void updateAll() {
while(Game.getKeyInput().hasNext()) {
KeyEvent e = Game.getKeyInput().getNextEvent();
for (KeyListener k : Game.getKeyListeners()) {
k.handleKey(e);
}
}
while(Game.getMouseInput().hasNext()) {
MouseEvent e = Game.getMouseInput().getNextEvent();
for (MouseListener m : Game.getMouseListeners()) {
m.handleMouse(e);
}
}
for (Element e : Game.getObjectList(Element.class)) { e.update(); }
}
public void drawAll() {
//Clear canvas
Game.getWindow().clearCanvases();
mainRoom.draw(Game.getWindow().getGraphics(Window.CANVAS_PLAY));
for (Element e : Game.getObjectList(Element.class)) { e.draw(); }
}
};
//GAME LOOP END
} | 24.044534 | 107 | 0.650615 |
e85c86e2a6503eaa133a75065b0045ba77355502 | 1,257 | package com.ruoyi.server.task;
import com.ruoyi.server.common.ConstantState;
import com.ruoyi.system.domain.SysCollectionPoint;
import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.service.ISysDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: wtao
* @Date: 2019-01-02 2:33
* @Version 1.0
*/
@Component
public class ScheduledSend {
@Autowired
ISysDeviceService deviceService;
@Scheduled(cron = "0 0/1 * * * *")
public void send() {
List<SysDevice> devices = deviceService.findAll();
List<SysDevice> devsOnline = new ArrayList<>();
Map<String, String> map = new HashMap<>();
synchronized (ConstantState.registeredCode) {
for (Map.Entry<String, String> entry : ConstantState.registeredCode.entrySet())
map.put(entry.getKey(), entry.getValue());
}
for (SysDevice device : devices) {
if (map.get(device.getCode()).equals("1"))
devsOnline.add(device);
}
}
}
| 29.928571 | 91 | 0.684169 |
c45127ad2f8bd63f44fdfe001aa37a51f2c55a57 | 659 | public class ExceptionExample {
private int x;
private Exception except;
public ExceptionExample() {
x = 0;
}
public void throwingMethod() throws Exception {
// throw calls native method - we can't summarise it
if(x==0) throw except;
}
public static void main(String[] args) {
ExceptionExample ex = new ExceptionExample();
ex.except = new Exception("An exception occurred.");
try {
ex.throwingMethod();
assert(false);
}catch(Exception e) {
System.out.println(e);
}
try {
ex.throwingMethod();
assert(false);
}catch(Exception e) {
System.out.println(e);
}
}
} | 19.969697 | 56 | 0.617602 |
6336ce9e801554f58049f11cd14b8d93abbfa846 | 202 | package com.github.ennoxhd.semver.api;
public interface Notation {
public String getSignFor(Component component, Type type);
public interface Component {
}
public interface Type {
}
}
| 13.466667 | 58 | 0.722772 |
Subsets and Splits