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
987dca7fa62f08dd032d5f0d835f597d70b1b6c4
1,958
package io.bootique.tools.release.controller; import com.fasterxml.jackson.databind.ObjectMapper; import io.bootique.tools.release.model.github.Organization; import io.bootique.tools.release.model.github.Repository; import io.bootique.tools.release.model.maven.Project; import io.bootique.tools.release.service.content.ContentService; import io.bootique.tools.release.service.git.GitService; import io.bootique.tools.release.service.github.GitHubApi; import io.bootique.tools.release.service.maven.MavenService; import io.bootique.tools.release.service.preferences.PreferenceService; import java.io.IOException; import java.util.List; import javax.inject.Inject; abstract class BaseController { @Inject PreferenceService preferences; @Inject GitHubApi gitHubApi; @Inject MavenService mavenService; @Inject ObjectMapper objectMapper; @Inject GitService gitService; @Inject ContentService contentService; List<Project> getSelectedProjects(String selectedProjects) throws IOException { List selectedProjectsId = objectMapper.readValue(selectedProjects, List.class); Organization organization = gitHubApi.getCurrentOrganization(); return mavenService.getProjects(organization, project -> selectedProjectsId.contains(project.getRepository().getName())); } List<Project> getAllProjects() { Organization organization = gitHubApi.getCurrentOrganization(); return mavenService.getProjects(organization, project -> true); } boolean haveMissingRepos(Organization organization) { for(Repository repository : organization.getRepositoryCollection().getRepositories()) { if (preferences.have(GitService.BASE_PATH_PREFERENCE)) { if(gitService.status(repository) == GitService.GitStatus.MISSING) { return true; } } } return false; } }
32.633333
95
0.73238
beb3fd2c801cd53a242795278d7153668ab521f3
23,178
/* The MIT License (MIT) Copyright (c) 2021 Pierre Lindenbaum 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.github.lindenb.jvarkit.tools.vcfvcf; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.OptionalDouble; import java.util.Set; import java.util.stream.Collectors; import com.beust.jcommander.Parameter; import com.github.lindenb.jvarkit.jcommander.OnePassVcfLauncher; import com.github.lindenb.jvarkit.jcommander.converter.FractionConverter; import com.github.lindenb.jvarkit.lang.StringUtils; import com.github.lindenb.jvarkit.util.JVarkitVersion; import com.github.lindenb.jvarkit.util.bio.DistanceParser; import com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter; import com.github.lindenb.jvarkit.util.jcommander.NoSplitter; import com.github.lindenb.jvarkit.util.jcommander.Program; import com.github.lindenb.jvarkit.util.log.Logger; import com.github.lindenb.jvarkit.util.log.ProgressFactory; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.util.CloseableIterator; import htsjdk.samtools.util.CloserUtil; import com.github.lindenb.jvarkit.variant.vcf.BufferedVCFReader; import com.github.lindenb.jvarkit.variant.vcf.VCFReaderFactory; import htsjdk.variant.vcf.VCFIterator; import htsjdk.variant.vcf.VCFReader; import htsjdk.variant.variantcontext.Allele; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.VariantContextBuilder; import htsjdk.variant.variantcontext.writer.VariantContextWriter; import htsjdk.variant.vcf.VCFConstants; import htsjdk.variant.vcf.VCFFilterHeaderLine; import htsjdk.variant.vcf.VCFHeader; import htsjdk.variant.vcf.VCFHeaderLineCount; import htsjdk.variant.vcf.VCFHeaderLineType; import htsjdk.variant.vcf.VCFInfoHeaderLine; /** BEGIN_DOC ALLELE_FREQUENCY_KEY END_DOC */ @Program(name="vcfpeekaf", description="Peek the AF from another VCF", keywords={"vcf","annotation","af"}, creationDate="20200624", modificationDate="20200904" ) public class VcfPeekAf extends OnePassVcfLauncher { private static final Logger LOG = Logger.build(VcfPeekAf.class).make(); @Parameter(names={"-F","--database","--tabix","--resource"},description="An indexed VCF file. Source of the annotations",required=true) private Path resourceVcfFile = null; @Parameter(names={"-T","--tag"},description="INFO tag to put found frequency. empty: no extra tag.") private String frequencyTag = ""; @Parameter(names={"-f","--filter"},description="soft FILTER the variant of this data if AF is not found or it greater > max-af or lower than min-af. If empty, just DISCARD the variant") private String filterStr = ""; @Parameter(names={"-b","--buffer-size"},converter=DistanceParser.StringConverter.class, description=BufferedVCFReader.OPT_BUFFER_DESC+" "+DistanceParser.OPT_DESCRIPTION,splitter=NoSplitter.class) private int buffer_size = 10_000; @Parameter(names={"-l","--list"},description="List available AF peekers and exit.",help=true) private boolean list_peekers = false; @Parameter(names={"-p","--peeker"},description="AF Peeker name. Use option --list to get a list of peekers.",required=true) private String peekerName = null; @Parameter(names={"-t","--treshold","--max-af"},description="AF max treshold. Variant is accepted is computed AF <= treshold.",converter=FractionConverter.class,required=true) private double af_maximum = 1.0; @Parameter(names={"--min-af"},description="AF min treshold. Variant is accepted is computed AF >= treshold.",converter=FractionConverter.class,required=false) private double af_minimum = 0.0; @Parameter(names={"--no-alt"},description="Do not look at the alternate alleles concordance") private boolean disable_alt_concordance = false; @Parameter(names={"-P","--peek-info"},description="Name of INFO tag in the vcf database to extract the AF value for exractor .'Custom'" ) private String custom_peek_info_name = null; @Parameter(names={"--peek-id"},description="Peek database variant ID if it is missing in the processed VCF." ) private boolean peek_variant_id=false; /* a class extracting the allele frequency from another VCF */ private abstract class AFPeeker { abstract String getName(); abstract String getDescription(); abstract void initialize(final VCFHeader h); @Override public String toString() { return getName(); } /** compare ctx with other variants found in database, ignoring ALT status */ abstract VariantContext applyAlt(final VariantContext ctx,final List<VariantContext> overlappers); /** compare ctx with other variants found in database, considering ALT status */ abstract VariantContext applyIgnoringAlt(final VariantContext ctx,final List<VariantContext> overlappers); final VariantContext apply(final VariantContext ctx,final List<VariantContext> overlappers) { return disable_alt_concordance ? applyIgnoringAlt(ctx,overlappers):applyAlt(ctx, overlappers); } /** simplify database variant */ abstract VariantContext sanitize(final VariantContext ctx); /** change variant in VCF, applying filters if needed . Return null if the variant is discarded. */ VariantContext addFilters3(final VariantContext ctx,final VariantContextBuilder vcb,boolean accept) { final Set<String> old_filters = new HashSet<>(ctx.getFilters()); if(!StringUtils.isBlank(VcfPeekAf.this.filterStr)) old_filters.remove(VcfPeekAf.this.filterStr); if(accept) { if(old_filters.isEmpty()) { vcb.passFilters(); } else { vcb.filters(old_filters); } return vcb.make(); } else { if(StringUtils.isBlank(VcfPeekAf.this.filterStr)) return null; old_filters.add(VcfPeekAf.this.filterStr); vcb.filters(old_filters); return vcb.make(); } } VariantContext addFiltersIgnoreAlt(final VariantContext ctx,final OptionalDouble optFreq) { final VariantContextBuilder vcb = new VariantContextBuilder(ctx); final boolean foundLt= !optFreq.isPresent() || (optFreq.getAsDouble() >= VcfPeekAf.this.af_minimum && optFreq.getAsDouble() <= VcfPeekAf.this.af_maximum); if(optFreq.isPresent() && !StringUtils.isBlank(VcfPeekAf.this.frequencyTag)) { vcb.attribute(VcfPeekAf.this.frequencyTag, optFreq.getAsDouble()); } return addFilters3(ctx, vcb, foundLt); } VariantContext addFilters(final VariantContext ctx,final Map<Allele,Double> alt2freq) { final VariantContextBuilder vcb = new VariantContextBuilder(ctx); final List<Double> af_vector = new ArrayList<>(alt2freq.size()); boolean foundLt=false; for(final Allele alt_allele: ctx.getAlternateAlleles()) { final double af; if(alt_allele.equals(Allele.SPAN_DEL)) { af=0; } else { af= alt2freq.getOrDefault(alt_allele, 0.0); if(VcfPeekAf.this.af_minimum <= af && af<=VcfPeekAf.this.af_maximum ) { foundLt=true; } } af_vector.add(af); } if(!StringUtils.isBlank(VcfPeekAf.this.frequencyTag)) vcb.attribute(VcfPeekAf.this.frequencyTag, af_vector); return addFilters3(ctx, vcb, foundLt); } } /** Use INFO/AC and INFO/AN to get frequency */ private class InfoAcAnPeeker extends AFPeeker { @Override String getName() { return "ACAN";} @Override String getDescription() { return "use : 'INFO/AC' divided by 'INFO/AN' to compute the Allele frequency";} @Override void initialize(final VCFHeader h) { if(h.getInfoHeaderLine(VCFConstants.ALLELE_COUNT_KEY)==null) { throw new IllegalArgumentException("Cannot find INFO="+VCFConstants.ALLELE_COUNT_KEY+" in "+resourceVcfFile); } if(h.getInfoHeaderLine(VCFConstants.ALLELE_NUMBER_KEY)==null) { throw new IllegalArgumentException("Cannot find INFO="+VCFConstants.ALLELE_NUMBER_KEY+" in "+resourceVcfFile); } } @Override final VariantContext sanitize(final VariantContext ctx) { final VariantContextBuilder vcb=new VariantContextBuilder(ctx); vcb.noGenotypes(); if(!peek_variant_id) vcb.noID(); vcb.unfiltered(); for(final String key:new HashSet<>(ctx.getAttributes().keySet())) { if(key.equals(VCFConstants.ALLELE_COUNT_KEY)) continue; if(key.equals(VCFConstants.ALLELE_NUMBER_KEY)) continue; vcb.rmAttribute(key); } return vcb.make(); } @Override VariantContext applyIgnoringAlt(final VariantContext ctx, final List<VariantContext> overlappers) { OptionalDouble optFreq = OptionalDouble.empty(); for(final VariantContext ctx2:overlappers) { if(!ctx2.hasAttribute(VCFConstants.ALLELE_COUNT_KEY)) { continue; } if(!ctx2.hasAttribute(VCFConstants.ALLELE_NUMBER_KEY)) { continue; } final double an = ctx2.getAttributeAsDouble(VCFConstants.ALLELE_NUMBER_KEY,0); if(an==0) { continue; } for(final Double ac:ctx2.getAttributeAsDoubleList(VCFConstants.ALLELE_COUNT_KEY,0.0)) { if(ac==null) continue; final double af = ac/an; if(!optFreq.isPresent()|| optFreq.getAsDouble()>af) { optFreq = OptionalDouble.of(af); } } } return addFiltersIgnoreAlt(ctx,optFreq); } @Override VariantContext applyAlt(final VariantContext ctx, final List<VariantContext> overlappers) { final List<Allele> alt_alleles = ctx.getAlternateAlleles(); final Map<Allele,Double> allele2freq = new HashMap<>(alt_alleles.size()); // loop over each ALT from this ctx for(int i=0;i< alt_alleles.size();++i) { final Allele ctx_alt= alt_alleles.get(i); if(ctx_alt.equals(Allele.SPAN_DEL)) { continue; } // loop over each variant from database for(final VariantContext ctx2:overlappers) { if(!ctx2.hasAllele(ctx_alt)) continue; if(!ctx2.hasAttribute(VCFConstants.ALLELE_COUNT_KEY)) { continue; } if(!ctx2.hasAttribute(VCFConstants.ALLELE_NUMBER_KEY)) { continue; } final double an = ctx2.getAttributeAsDouble(VCFConstants.ALLELE_NUMBER_KEY,0); if(an==0) { continue; } final int ref_idx = ctx2.getAlleleIndex(ctx_alt); if(ref_idx<1 /* 0 is ref */) { continue; }; final List<Double> ac2 = ctx2.getAttributeAsDoubleList(VCFConstants.ALLELE_COUNT_KEY, 1.0); if(ref_idx-1>=ac2.size()) { continue; }; final double alt2freq = ac2.get(ref_idx-1)/an; if(allele2freq.getOrDefault(ctx_alt,1.0) > alt2freq) { allele2freq.put(ctx_alt, alt2freq); } } } return addFilters(ctx,allele2freq); } } private abstract class AbstractAFInfoFieldPeeker extends AFPeeker { protected abstract String getPeekInfoTagName(); @Override void initialize(final VCFHeader h) { if(StringUtils.isBlank(getPeekInfoTagName())) { throw new IllegalStateException("No INFO tag was defined for extractor "+ this.getName()); } final VCFInfoHeaderLine hl= h.getInfoHeaderLine(getPeekInfoTagName()); if(hl==null) { throw new IllegalArgumentException("Cannot find INFO="+getPeekInfoTagName()+" in "+resourceVcfFile); } if(!hl.getCountType().equals(VCFHeaderLineCount.A)) { LOG.warn("Expected find INFO="+getPeekInfoTagName()+" Count="+VCFHeaderLineCount.A+" but got "+hl.getCountType()); } if(hl.getType().equals(VCFHeaderLineType.Float)) { throw new IllegalArgumentException("Expected find INFO="+getPeekInfoTagName()+" Type="+VCFHeaderLineType.Float+" but got "+hl.getType()); } } @Override final VariantContext sanitize(final VariantContext ctx) { final VariantContextBuilder vcb=new VariantContextBuilder(ctx); vcb.noGenotypes(); if(!peek_variant_id) vcb.noID(); vcb.unfiltered(); for(final String key:new HashSet<>(ctx.getAttributes().keySet())) { if(key.equals(getPeekInfoTagName())) continue; vcb.rmAttribute(key); } return vcb.make(); } @Override VariantContext applyIgnoringAlt(final VariantContext ctx,final List<VariantContext> overlappers) { final OptionalDouble optFreq = overlappers. stream(). filter(ctx2->ctx2.hasAttribute(getPeekInfoTagName())). flatMap(ctx2->ctx2.getAttributeAsDoubleList(getPeekInfoTagName(),0.0).stream()). mapToDouble(V->V.doubleValue()). min(); return addFiltersIgnoreAlt(ctx,optFreq); } @Override VariantContext applyAlt(final VariantContext ctx, final List<VariantContext> overlappers) { final List<Allele> alt_alleles = ctx.getAlternateAlleles(); final Map<Allele,Double> allele2freq = new HashMap<>(alt_alleles.size()); // loop over each ALT from this ctx for(int i=0;i< alt_alleles.size();++i) { final Allele ctx_alt= alt_alleles.get(i); if(ctx_alt.equals(Allele.SPAN_DEL)) { continue; } // loop over each variant from database for(final VariantContext ctx2:overlappers) { if(!ctx2.hasAllele(ctx_alt)) continue; if(!ctx2.hasAttribute(getPeekInfoTagName())) { continue; } final int ref_idx = ctx2.getAlleleIndex(ctx_alt); if(ref_idx<1 /* 0 is ref */) { continue; }; final List<Double> af_array = ctx2.getAttributeAsDoubleList(getPeekInfoTagName(), 1.0); if(ref_idx-1>=af_array.size()) { continue; }; final double alt2freq = af_array.get(ref_idx-1); if(allele2freq.getOrDefault(ctx_alt,1.0) > alt2freq) { allele2freq.put(ctx_alt, alt2freq); } } } return addFilters(ctx,allele2freq); } } private class InfoAfPeeker extends AbstractAFInfoFieldPeeker { @Override String getName() { return getPeekInfoTagName(); } @Override String getDescription() { return "use field 'INFO/AF' to extract the Allele frequency";} @Override protected String getPeekInfoTagName() { return VCFConstants.ALLELE_FREQUENCY_KEY; } } private class CustomInfoPeeker extends AbstractAFInfoFieldPeeker { @Override String getName() { return "Custom"; } @Override String getDescription() { return "use ratio INFO field defined with option -P to compute the Allele frequency";} @Override protected String getPeekInfoTagName() { return VcfPeekAf.this.custom_peek_info_name; } } private class GtPeeker extends AFPeeker { @Override String getName() { return "GT";} @Override String getDescription() { return "compute Allele frequency from the Genotypes";} @Override final VariantContext sanitize(final VariantContext ctx) { final VariantContextBuilder vcb = new VariantContextBuilder(ctx).unfiltered().attributes(Collections.emptyMap()); if(!peek_variant_id) vcb.noID(); return vcb.make(); } @Override void initialize(final VCFHeader h) { if(!h.hasGenotypingData()) { throw new IllegalArgumentException("No Genotype in "+resourceVcfFile); } } @Override VariantContext applyIgnoringAlt(VariantContext ctx, final List<VariantContext> overlappers) { OptionalDouble optFreq = OptionalDouble.empty(); for(final VariantContext ctx2:overlappers) { final double an= ctx2.getGenotypes().stream().filter(G->G.isCalled()).mapToInt(G->G.getAlleles().size()).sum(); if(an==0) { continue; } for(final Allele alt: ctx2.getAlternateAlleles()) { double ac= ctx2.getGenotypes().stream().filter(G->G.isCalled()).flatMap(G->G.getAlleles().stream()).filter(A->A.equals(alt)).count(); final double af = ac/an; if(!optFreq.isPresent() || optFreq.getAsDouble()>af) optFreq = OptionalDouble.of(af); } } return addFiltersIgnoreAlt(ctx,optFreq); } @Override VariantContext applyAlt(final VariantContext ctx, final List<VariantContext> overlappers) { final List<Allele> alt_alleles = ctx.getAlternateAlleles(); final Map<Allele,Double> allele2freq = new HashMap<>(alt_alleles.size()); // loop over each variant from database for(int i=0;i< alt_alleles.size();++i) { final Allele ctx_alt= alt_alleles.get(i); if(ctx_alt.equals(Allele.SPAN_DEL)) { continue; } for(final VariantContext ctx2:overlappers) { // loop over each ALT from this ctx if(!ctx2.hasAllele(ctx_alt)) continue; final double an= ctx2.getGenotypes().stream().filter(G->G.isCalled()).mapToInt(G->G.getAlleles().size()).sum(); if(an==0) { continue; } final double ac= ctx2.getGenotypes().stream().filter(G->G.isCalled()).flatMap(G->G.getAlleles().stream()).filter(A->A.equals(ctx_alt)).count(); final double alt2freq = ac/an; if(allele2freq.getOrDefault(ctx_alt,1.0) > alt2freq) { allele2freq.put(ctx_alt, alt2freq); } } } return addFilters(ctx,allele2freq); } } private BufferedVCFReader indexedVcfFileReader=null; private AFPeeker peeker; public VcfPeekAf() { } private List<VariantContext> getOverlappingBuffer( final String dbContig, final VariantContext userCtx ) { try(CloseableIterator<VariantContext> iter = this.indexedVcfFileReader.query(dbContig, userCtx.getStart(), userCtx.getEnd())) { return iter.stream().collect(Collectors.toList()); } } private boolean alleles_match_for_id(final VariantContext userCtx,final VariantContext databaseV) { if(userCtx.hasID()) return false; if(!databaseV.hasID()) return false; if(userCtx.getStart()!=databaseV.getStart()) return false; final Set<Allele> set1 = new HashSet<>(userCtx.getAlleles()); set1.remove(Allele.NO_CALL); set1.remove(Allele.SPAN_DEL); final Set<Allele> set2 = new HashSet<>(databaseV.getAlleles()); set2.remove(Allele.NO_CALL); set2.remove(Allele.SPAN_DEL); return set2.containsAll(set1); } @Override public int doVcfToVcf( final String inputName, final VCFIterator vcfIn, final VariantContextWriter out) { try { final VCFHeader h = vcfIn.getHeader(); final SAMSequenceDictionary dictDatabase = this.indexedVcfFileReader.getHeader().getSequenceDictionary(); final ContigNameConverter dbCtgConverter = dictDatabase==null || dictDatabase.isEmpty()? ContigNameConverter.getIdentity(): ContigNameConverter.fromOneDictionary(dictDatabase) ; final VCFHeader h2 = new VCFHeader(h); if(!StringUtils.isBlank(this.frequencyTag)) { final String msg="Allele Frequency found in "+resourceVcfFile+" with peeker: "+this.peeker.getName(); if(this.disable_alt_concordance) { h2.addMetaDataLine(new VCFInfoHeaderLine(this.frequencyTag,1,VCFHeaderLineType.Float,"Min "+msg)); } else { h2.addMetaDataLine(new VCFInfoHeaderLine(this.frequencyTag,VCFHeaderLineCount.A,VCFHeaderLineType.Float,msg)); } } if(!StringUtils.isBlank(this.filterStr)) { h2.addMetaDataLine(new VCFFilterHeaderLine(this.filterStr,"Allele Frequency found in "+resourceVcfFile+" with peeker failing the following state: "+ this.af_minimum + " <= "+ this.peeker.getName()+" <= "+this.af_maximum)); } JVarkitVersion.getInstance().addMetaData(this, h2); out.writeHeader(h2); final ProgressFactory.Watcher<VariantContext> progress = ProgressFactory.newInstance(). dictionary(h). logger(LOG). build() ; while(vcfIn.hasNext()) { final VariantContext ctx=progress.apply(vcfIn.next()); final String dbContig = dbCtgConverter.apply(ctx.getContig()); final List<VariantContext> overlappers; if(StringUtils.isBlank(dbContig)) { overlappers = Collections.emptyList(); } else { overlappers = this.getOverlappingBuffer(dbContig,ctx); } VariantContext ctx2 = this.peeker.apply(ctx,overlappers); if(ctx2==null) continue; /* peek variant ID */ if(this.peek_variant_id && !ctx2.hasID() && !overlappers.isEmpty()) { final VariantContext ctx2_final = ctx2; final String id = overlappers.stream(). filter(V-> alleles_match_for_id(ctx2_final,V)). map(V->V.getID()). findFirst(). orElse(null); if(!StringUtils.isBlank(id)) { ctx2 = new VariantContextBuilder(ctx).id(id).make(); } } out.add(ctx2); } progress.close(); return 0; } catch(final Throwable err) { LOG.error(err); return -1; } } @Override protected Logger getLogger() { return LOG; } @Override protected int beforeVcf() { final List<AFPeeker> all_peekers = new ArrayList<>(); all_peekers.add(new InfoAcAnPeeker()); all_peekers.add(new InfoAfPeeker()); all_peekers.add(new GtPeeker()); all_peekers.add(new CustomInfoPeeker()); this.indexedVcfFileReader = null; if(this.buffer_size<1) { LOG.error("bad buffer-size"); return -1; } try { if(this.list_peekers) { try(PrintWriter out=super.openPathOrStdoutAsPrintWriter(this.outputFile)) { for(final AFPeeker p:all_peekers) out.println(p.getName()+"\n\t"+p.getDescription()); out.flush(); } System.exit(0); } if(StringUtils.isBlank(this.peekerName)) { LOG.error("peeker name is empty"); return -1; } this.peeker = all_peekers.stream().filter(P->P.getName().equals(this.peekerName)).findFirst().orElse(null); if(this.peeker==null) { LOG.error("peeker "+this.peekerName+" not found in "+ all_peekers. stream(). map(P->P.getName()). collect(Collectors.joining(";"))); return -1; } final VCFReader reader0 = VCFReaderFactory.makeDefault().open(this.resourceVcfFile,true); this.indexedVcfFileReader = new BufferedVCFReader(reader0,this.buffer_size); this.peeker.initialize(this.indexedVcfFileReader.getHeader()); this.indexedVcfFileReader.setSimplifier(peeker::sanitize); return 0; } catch(final Throwable err) { LOG.error(err); return -1; } } @Override protected void afterVcf() { CloserUtil.close(this.indexedVcfFileReader); this.indexedVcfFileReader=null; } public static void main(final String[] args) throws IOException { new VcfPeekAf().instanceMainWithExit(args); } }
33.688953
196
0.711666
086358c5ee9d5a4a3e21202b3485611db1fef60e
916
package com.amyliascarlet.jsontest.bvt.issue_1100; import com.amyliascarlet.lib.json.JSON; import com.amyliascarlet.lib.json.JSONObject; import com.amyliascarlet.lib.json.JSONPath; import com.amyliascarlet.lib.json.TypeReference; import junit.framework.TestCase; import java.util.List; /** * Created by wenshao on 05/05/2017. */ public class Issue1177_3 extends TestCase { public void test_for_issue() throws Exception { String text = "[{\"x\":\"y\"},{\"x\":\"y\"}]"; List<Model> jsonObject = JSONObject.parseObject(text, new TypeReference<List<Model>>(){}); System.out.println(JSON.toJSONString(jsonObject)); String jsonpath = "$..x"; String value="y2"; JSONPath.set(jsonObject, jsonpath, value); assertEquals("[{\"x\":\"y2\"},{\"x\":\"y2\"}]", JSON.toJSONString(jsonObject)); } public static class Model { public String x; } }
30.533333
98
0.664847
5dde1259b5f356c676627770e6a558f6d4efd7dc
7,867
/* * Copyright 2007 The Depan Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.depan.matchers.eclipse.ui.widgets; import com.google.devtools.depan.graph.api.EdgeMatcher; import com.google.devtools.depan.graph.api.Relation; import com.google.devtools.depan.model.GraphEdgeMatcher; import com.google.devtools.depan.platform.PlatformResources; import com.google.devtools.depan.platform.eclipse.ui.widgets.Widgets; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import java.util.Collection; /** * A GUI tool to display an edge matcher, with a selector for forward * and backward directions. This is a editable table (directions are editable, * content and names are not). * * To use it, call {@link #getControl(Composite)} to retrieve the widget. * * @since 2015 Built from pieces of the legacy RelationshipPicker. * * @author ycoppel@google.com (Yohann Coppel) */ public class EdgeMatcherEditorControl extends Composite { ///////////////////////////////////// // UX Elements private EdgeMatcherTableControl editor; ///////////////////////////////////// // Public methods /** * return a {@link Control} for this widget, containing every useful buttons, * labels, table... necessary to use this component. * * @param parent the parent. * @return a {@link Control} containing this widget. */ public EdgeMatcherEditorControl(Composite parent) { super(parent, SWT.BORDER); setLayout(Widgets.buildContainerLayout(1)); Composite allRels = setupAllRelsButtons(this); allRels.setLayoutData(Widgets.buildHorzFillData()); editor = new EdgeMatcherTableControl(this); editor.setLayoutData(Widgets.buildGrabFillData()); Composite toggles = setupRelationToggles(this); toggles.setLayoutData(Widgets.buildHorzFillData()); } public void registerModificationListener( ModificationListener<Relation, Boolean> listener) { editor.registerModificationListener(listener); } public void unregisterModificationListener( ModificationListener<Relation, Boolean> listener) { editor.unregisterModificationListener(listener); } /** * Fill the list with {@link Relation}s. */ public void updateTable(Collection<Relation> relations) { editor.updateTableRows(relations); } public void updateEdgeMatcher(EdgeMatcher<String> edgeMatcher) { editor.updateEdgeMatcher(edgeMatcher); } public GraphEdgeMatcher buildEdgeMatcher() { return editor.buildEdgeMatcher(); } ///////////////////////////////////// // UX Setup private Composite setupAllRelsButtons(Composite parent) { Composite result = Widgets.buildGridContainer(parent, 3); Button clearAll = Widgets.buildGridPushButton(result, "Clear all lines"); clearAll.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.clearRelations(); } }); Button reverseAll = Widgets.buildGridPushButton(result, "Reverse all lines"); reverseAll.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.reverseRelations(); } }); Button invertAll = Widgets.buildGridPushButton(result, "Invert all lines"); invertAll.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.invertRelations(); } }); return result; } @SuppressWarnings("unused") private Composite setupRelationToggles(Composite parent) { Composite result = Widgets.buildGridContainer(parent, 1); Label optionsLabel = Widgets.buildCompactLabel(result, "For selected lines:"); Composite relOps = setupRelationOps(result); relOps.setLayoutData(Widgets.buildHorzFillData()); Composite toggles = setupToggleOps(result); toggles.setLayoutData(Widgets.buildHorzFillData()); return result; } private Composite setupRelationOps(Composite parent) { Composite result = Widgets.buildGridContainer(parent, 2); Button groupReverse = Widgets.buildGridPushButton(result, "Reverse"); groupReverse.setLayoutData(Widgets.buildHorzFillData()); Button groupInvert = Widgets.buildGridPushButton(result, "Invert"); groupInvert.setLayoutData(Widgets.buildHorzFillData()); groupReverse.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.reverseSelectedRelations(); } }); groupInvert.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.invertSelectedRelations(); } }); return result; } private Composite setupToggleOps(Composite parent) { Composite result = Widgets.buildGridContainer(parent, 8); Label forward = new Label(result, SWT.NONE); forward.setText("Forward"); forward.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); Button forwardAll = Widgets.buildGridPushButton(result); forwardAll.setImage(PlatformResources.IMAGE_ON); Button forwardNone = Widgets.buildGridPushButton(result); forwardNone.setImage(PlatformResources.IMAGE_OFF); Button forwardInvert = Widgets.buildGridPushButton(result, "Invert"); Label backward = new Label(result, SWT.NONE); backward.setText("Backward"); backward.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); Button backwardAll = Widgets.buildGridPushButton(result); backwardAll.setImage(PlatformResources.IMAGE_ON); Button backwardNone = Widgets.buildGridPushButton(result); backwardNone.setImage(PlatformResources.IMAGE_OFF); Button backwardInvert = Widgets.buildGridPushButton(result, "Invert"); // actions forwardAll.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.setForwardSelectedRelations(true); } }); forwardNone.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.setForwardSelectedRelations(false); } }); forwardInvert.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.invertForwardSelectedRelations(); } }); backwardAll.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.setReverseSelectedRelations(true); } }); backwardNone.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.setReverseSelectedRelations(false); } }); backwardInvert.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editor.invertReverseSelectedRelations(); } }); return result; } }
31.594378
82
0.718571
bd3c2f6e8332470097f077998087cddc2c9ca7f1
4,212
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_CASE_SENSITIVE; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import seedu.address.logic.commands.FindCommand; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.person.FindPredicate; import seedu.address.model.person.Name; import seedu.address.model.tag.Tag; /** * Parses input arguments and creates a new {@code FindCommand} object. */ public class FindCommandParser implements Parser<FindCommand> { /** * Parses the given {@code String} of arguments in the context of the {@code FindCommand} * and returns a {@code FindCommand} object for execution. * * @param args user input. * @return {@code FindCommand} which searches for contacts that fulfill the criteria. * @throws ParseException if the user input does not conform the expected format. */ public FindCommand parse(String args) throws ParseException { String trimmedArgs = args.trim(); if (trimmedArgs.isEmpty()) { throw new ParseException( String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } if (extractSearchTerms(args).contains("c/")) { throw new ParseException(FindCommand.CASE_SENSITIVE_FLAG_FORMAT_MESSAGE); } boolean isCaseSensitive = false; if (trimmedArgs.contains(PREFIX_CASE_SENSITIVE.toString())) { isCaseSensitive = true; } ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_NAME, PREFIX_TAG); if ((!arePrefixesPresent(argMultimap, PREFIX_NAME) && !arePrefixesPresent(argMultimap, PREFIX_TAG))) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } List<String> nameStringList = argMultimap.getAllValues(PREFIX_NAME); if (areBlanksPresent(nameStringList)) { String nameFormatRequirementMessage = "There should not be any blanks in name.\n" + "For example, " + "if you are " + "searching for " + "'n/John Doe', split them into 'n/John' " + "and 'n/Doe' instead."; throw new ParseException(nameFormatRequirementMessage); } List<String> tagStringList = argMultimap.getAllValues(PREFIX_TAG); List<Name> nameKeywords; List<Tag> tagList; try { nameKeywords = nameStringList.stream().map(Name::new).collect(Collectors.toList()); tagList = tagStringList.stream().map(Tag::new).collect(Collectors.toList()); } catch (IllegalArgumentException e) { throw new ParseException(e.getMessage()); } FindPredicate findpredicate = new FindPredicate(nameKeywords, tagList, isCaseSensitive); return new FindCommand(findpredicate); } /** * Returns true if none of the prefixes contains empty {@code Optional} values in the given * {@code ArgumentMultimap}. */ private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent()); } private static boolean areBlanksPresent(List<String> stringList) { for (String s : stringList) { if (s.contains(" ")) { return true; } } return false; } private static String extractSearchTerms(String args) { int indexOfN = args.indexOf("n/"); int indexOfT = args.indexOf("t/"); int finalIndex; if (indexOfN == -1) { finalIndex = indexOfT; } else if (indexOfT == -1) { finalIndex = indexOfN; } else { finalIndex = Math.min(indexOfN, indexOfT); } return args.substring(finalIndex); } }
38.642202
111
0.665717
80df7676a636c2d41276ab2c9c7745c71fb9eaf4
11,716
package com.knaus.sampleweatherapp; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONObject; import java.util.Locale; public class WeatherFragment extends Fragment { private static final String TAG = "WeatherFragment"; Typeface weatherFont; TextView locationText; TextView lastUpdatedText; TextView detailsText; TextView currentTempText; TextView weatherIcon; LinearLayout forecastLayout; Handler handler; public WeatherFragment() { handler = new Handler(); } public static WeatherFragment newInstance() { WeatherFragment fragment = new WeatherFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // set weather font typeface to display weather icon and fahrenheit symbol weatherFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/weathericons.ttf"); updateWeatherData(new LocationPreference(getActivity()).getLocation()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_weather, container, false); locationText = (TextView) view.findViewById(R.id.location_text); lastUpdatedText = (TextView) view.findViewById(R.id.last_update_text); detailsText = (TextView) view.findViewById(R.id.details_text); currentTempText = (TextView) view.findViewById(R.id.current_temp_text); weatherIcon = (TextView) view.findViewById(R.id.weather_icon); forecastLayout = (LinearLayout) view.findViewById(R.id.forecastLayout); currentTempText.setTypeface(weatherFont); weatherIcon.setTypeface(weatherFont); return view; } /** * Retrieve weather data and update the UI * @param location */ private void updateWeatherData(final String location) { new Thread() { public void run() { // get weather information as JSONObject final JSONObject json = GetWeather.getJSON(getActivity(), location); if (json != null) { // if we have data then render the UI handler.post(new Runnable() { @Override public void run() { renderWeather(json); } }); } else { handler.post(new Runnable() { @Override public void run() { Toast.makeText(getActivity(), getActivity().getString(R.string.location_not_found), Toast.LENGTH_LONG).show(); } }); } } }.start(); } /** * Update the layout with the weather JSON object * @param json */ private void renderWeather(JSONObject json) { try { JSONObject channel = json.getJSONObject("query").getJSONObject("results").getJSONObject("channel"); JSONObject location = channel.getJSONObject("location"); JSONObject units = channel.getJSONObject("units"); JSONObject atmosphere = channel.getJSONObject("atmosphere"); JSONObject item = channel.getJSONObject("item"); JSONObject condition = item.getJSONObject("condition"); JSONArray forecast = item.getJSONArray("forecast"); locationText.setText(location.getString("city").toUpperCase(Locale.US) + ", " + location.getString("region")); detailsText.setText(String.format("%s \nHumidity: %d%% \nPressure: %d %s", condition.getString("text"), atmosphere.getInt("humidity"), atmosphere.getInt("pressure"), units.getString("pressure"))); String tempUnit = units.getString("temperature").equals("F") ? getActivity().getString(R.string.weather_fahrenheit) : getActivity().getString(R.string.weather_celsius); currentTempText.setText(String.format("%d %s", condition.getInt("temp"), tempUnit)); lastUpdatedText.setText("As of " + channel.getString("lastBuildDate")); weatherIcon.setText(getWeatherIcon(item.getJSONObject("condition").getInt("code"))); addForecastData(forecast); } catch (Exception e) { Log.e(TAG, "Error rendering weather: " + e.getMessage()); } } /** * Add each forecast item as WeatherForecastFragment to HorizontalScrollView */ private void addForecastData(JSONArray forecast) { forecastLayout.removeAllViews(); for(int i = 0; i < forecast.length(); i++) { try { JSONObject item = forecast.getJSONObject(i); WeatherForecast fc = new WeatherForecast(item.getString("date"), item.getInt("high"), item.getInt("low"), getWeatherIcon(item.getInt("code")), item.getString("text")); WeatherForecastFragment wff = WeatherForecastFragment.newInstance(fc); getActivity().getSupportFragmentManager().beginTransaction().add(R.id.forecastLayout, wff, String.format("forecast_%d", i)).commit(); } catch (Exception e) { Log.e(TAG, "Error adding forecast fragments: " + e.getMessage()); } } } /* * Gets weather icon based on response condition code * see also condition codes at https://developer.yahoo.com/weather/documentation.html */ private String getWeatherIcon(int id){ String icon = ""; switch(id) { case 0 : icon = getActivity().getString(R.string.weather_tornado); break; case 1 : icon = getActivity().getString(R.string.weather_tropical_storm); break; case 2 : icon = getActivity().getString(R.string.weather_hurricane); break; case 3 : icon = getActivity().getString(R.string.weather_severe_thunderstorms); break; case 4 : icon = getActivity().getString(R.string.weather_thunderstorms); break; case 5 : icon = getActivity().getString(R.string.weather_mixed_rain_and_snow); break; case 6 : icon = getActivity().getString(R.string.weather_mixed_rain_and_sleet); break; case 7 : icon = getActivity().getString(R.string.weather_mixed_snow_and_sleet); break; case 8 : icon = getActivity().getString(R.string.weather_freezing_drizzle); break; case 9 : icon = getActivity().getString(R.string.weather_drizzle); break; case 10 : icon = getActivity().getString(R.string.weather_freezing_rain); break; case 11 : icon = getActivity().getString(R.string.weather_showers); break; case 12 : icon = getActivity().getString(R.string.weather_showers2); break; case 13 : icon = getActivity().getString(R.string.weather_snow_flurries); break; case 14 : icon = getActivity().getString(R.string.weather_light_snow_shower); break; case 15 : icon = getActivity().getString(R.string.weather_blowing_snow); break; case 16 : icon = getActivity().getString(R.string.weather_snow); break; case 17 : icon = getActivity().getString(R.string.weather_hail); break; case 18 : icon = getActivity().getString(R.string.weather_sleet); break; case 19 : icon = getActivity().getString(R.string.weather_dust); break; case 20 : icon = getActivity().getString(R.string.weather_foggy); break; case 21 : icon = getActivity().getString(R.string.weather_haze); break; case 22 : icon = getActivity().getString(R.string.weather_smoky); break; case 23 : icon = getActivity().getString(R.string.weather_blustery); break; case 24 : icon = getActivity().getString(R.string.weather_windy); break; case 25 : icon = getActivity().getString(R.string.weather_cold); break; case 26 : icon = getActivity().getString(R.string.weather_cloudy); break; case 27 : icon = getActivity().getString(R.string.weather_mostly_cloudy_night); break; case 28 : icon = getActivity().getString(R.string.weather_mostly_cloudy_day); break; case 29 : icon = getActivity().getString(R.string.weather_partly_cloudy_night); break; case 30 : icon = getActivity().getString(R.string.weather_partly_cloudy_day); break; case 31: icon = getActivity().getString(R.string.weather_clear_night); break; case 32: icon = getActivity().getString(R.string.weather_sunny); break; case 33 : icon = getActivity().getString(R.string.weather_fair_night); break; case 34 : icon = getActivity().getString(R.string.weather_fair_day); break; case 35 : icon = getActivity().getString(R.string.weather_mixed_rain_and_hail); break; case 36 : icon = getActivity().getString(R.string.weather_hot); break; case 37 : icon = getActivity().getString(R.string.weather_isolated_thuderstorms); break; case 38 : icon = getActivity().getString(R.string.weather_scattered_thunderstorms); break; case 39 : icon = getActivity().getString(R.string.weather_scattered_thunderstorms2); break; case 40 : icon = getActivity().getString(R.string.weather_scattered_showers); break; case 41 : icon = getActivity().getString(R.string.weather_heavy_snow); break; case 42 : icon = getActivity().getString(R.string.weather_scattered_snow_showers); break; case 43 : icon = getActivity().getString(R.string.weather_heavy_snow2); break; case 44 : icon = getActivity().getString(R.string.weather_partly_cloudy); break; case 45 : icon = getActivity().getString(R.string.weather_thundershowers); break; case 46 : icon = getActivity().getString(R.string.weather_snow_showers); break; case 47 : icon = getActivity().getString(R.string.weather_isolated_thundershowers); break; default: icon = getActivity().getString(R.string.weather_not_available); } return icon; } public void changeLocation(String location) { updateWeatherData(location); } }
45.587549
209
0.592352
82e65cde9de4316a315a1e5aab3684f5c742a48f
4,073
package com.shcem.database; import com.alibaba.druid.pool.DruidDataSource; import lombok.Getter; import lombok.Setter; import java.util.Properties; @Setter @Getter public class DruidDataSourceProperties { private String url; private String username; private String password; private String driverClassName; private String dbType; private Boolean testWhileIdle = true; private Boolean testOnBorrow; private String validationQuery = "SELECT 1"; private Boolean useGlobalDataSourceStat; private String filters; private Long timeBetweenLogStatsMillis; private Integer maxSize; private Boolean clearFiltersEnable; private Boolean resetStatEnable; private Integer notFullTimeoutRetryCount; private Integer maxWaitThreadCount; private Boolean failFast; private Boolean phyTimeoutMillis; private Long minEvictableIdleTimeMillis = 300000L; private Long maxEvictableIdleTimeMillis; private Integer initialSize = 5; private Integer minIdle = 5; private Integer maxActive = 20; private Long maxWait = 60000L; private Long timeBetweenEvictionRunsMillis = 60000L; private Boolean poolPreparedStatements = true; private Integer maxPoolPreparedStatementPerConnectionSize = 20; private Properties connectionProperties = new Properties() {{ put("druid.stat.mergeSql", "true"); put("druid.stat.slowSqlMillis", "5000"); }}; public Properties toProperties() { Properties properties = new Properties(); notNullAdd(properties, "testWhileIdle", this.testWhileIdle); notNullAdd(properties, "testOnBorrow", this.testOnBorrow); notNullAdd(properties, "validationQuery", this.validationQuery); notNullAdd(properties, "useGlobalDataSourceStat", this.useGlobalDataSourceStat); notNullAdd(properties, "filters", this.filters); notNullAdd(properties, "timeBetweenLogStatsMillis", this.timeBetweenLogStatsMillis); notNullAdd(properties, "stat.sql.MaxSize", this.maxSize); notNullAdd(properties, "clearFiltersEnable", this.clearFiltersEnable); notNullAdd(properties, "resetStatEnable", this.resetStatEnable); notNullAdd(properties, "notFullTimeoutRetryCount", this.notFullTimeoutRetryCount); notNullAdd(properties, "maxWaitThreadCount", this.maxWaitThreadCount); notNullAdd(properties, "failFast", this.failFast); notNullAdd(properties, "phyTimeoutMillis", this.phyTimeoutMillis); notNullAdd(properties, "minEvictableIdleTimeMillis", this.minEvictableIdleTimeMillis); notNullAdd(properties, "maxEvictableIdleTimeMillis", this.maxEvictableIdleTimeMillis); notNullAdd(properties, "initialSize", this.initialSize); notNullAdd(properties, "minIdle", this.minIdle); notNullAdd(properties, "maxActive", this.maxActive); notNullAdd(properties, "maxWait", this.maxWait); notNullAdd(properties, "timeBetweenEvictionRunsMillis", this.timeBetweenEvictionRunsMillis); notNullAdd(properties, "poolPreparedStatements", this.poolPreparedStatements); notNullAdd(properties, "maxPoolPreparedStatementPerConnectionSize", this.maxPoolPreparedStatementPerConnectionSize); return properties; } /** * 生成一个Druid连接 * @param * @return */ public DruidDataSource build(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.configFromPropety(this.toProperties()); druidDataSource.setDbType(this.dbType); druidDataSource.setUrl(this.url); druidDataSource.setDriverClassName(this.driverClassName); druidDataSource.setUsername(this.username); druidDataSource.setPassword(this.password); druidDataSource.setConnectProperties(this.connectionProperties); return druidDataSource; } private void notNullAdd(Properties properties, String key, Object value) { if (value != null) { properties.setProperty("druid." + key, value.toString()); } } }
43.329787
124
0.733366
e14d52786875416b45353c43f8822b9fa7d2ba53
8,115
package com.devsmart.ubjson; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Random; import static org.junit.Assert.*; public class UBWriterTest { @Test public void testWriteNull() throws IOException { UBValue value; ByteArrayOutputStream out = new ByteArrayOutputStream(); UBWriter writer = new UBWriter(out); value = UBValueFactory.createNull(); writer.write(value); byte[] array = out.toByteArray(); assertEquals(1, array.length); assertEquals('Z', array[0]); } @Test public void testWriteBool() throws IOException { UBValue value; ByteArrayOutputStream out; UBWriter writer; byte[] array; out = new ByteArrayOutputStream(); writer = new UBWriter(out); value = UBValueFactory.createBool(true); writer.write(value); array = out.toByteArray(); assertEquals(1, array.length); assertEquals('T', array[0]); out = new ByteArrayOutputStream(); writer = new UBWriter(out); value = UBValueFactory.createBool(false); writer.write(value); array = out.toByteArray(); assertEquals(1, array.length); assertEquals('F', array[0]); } @Test public void testWriteChar() throws IOException { UBValue value; ByteArrayOutputStream out; UBWriter writer; byte[] array; out = new ByteArrayOutputStream(); writer = new UBWriter(out); value = UBValueFactory.createChar('t'); writer.write(value); array = out.toByteArray(); assertEquals(2, array.length); assertEquals('C', array[0]); assertEquals('t', array[1]); } @Test public void testWriteInt() throws IOException { UBValue value; ByteArrayOutputStream out; UBWriter writer; byte[] array; out = new ByteArrayOutputStream(); writer = new UBWriter(out); value = UBValueFactory.createInt(255); writer.write(value); array = out.toByteArray(); assertEquals(2, array.length); assertEquals('U', array[0]); assertEquals(255, (short)(0xFF & array[1])); out = new ByteArrayOutputStream(); writer = new UBWriter(out); value = UBValueFactory.createInt(-1); writer.write(value); array = out.toByteArray(); assertEquals(2, array.length); assertEquals('i', array[0]); assertEquals(255, (short)(0xFF & array[1])); out = new ByteArrayOutputStream(); writer = new UBWriter(out); value = UBValueFactory.createInt(29753); writer.write(value); array = out.toByteArray(); assertEquals(3, array.length); assertEquals('I', array[0]); assertEquals(0x74, (short)(0xFF & array[1])); assertEquals(0x39, (short)(0xFF & array[2])); } @Test public void testWriteLongInt() throws IOException { UBValue value; ByteArrayOutputStream out; UBWriter writer; byte[] array; long longValue = Long.valueOf("1456707337000"); out = new ByteArrayOutputStream(); writer = new UBWriter(out); value = UBValueFactory.createInt(longValue); writer.write(value); array = out.toByteArray(); assertEquals(9, array.length); assertEquals('L', array[0]); assertEquals(0x28, (short)(0xFF & array[8])); assertEquals(0xFB, (short)(0xFF & array[7])); assertEquals(0x85, (short)(0xFF & array[6])); assertEquals(0x2A, (short)(0xFF & array[5])); assertEquals(0x53, (short)(0xFF & array[4])); assertEquals(0x01, (short)(0xFF & array[3])); assertEquals(0x00, (short)(0xFF & array[2])); assertEquals(0x00, (short)(0xFF & array[1])); } @Test public void testWriteArray() throws IOException { UBValue value; ByteArrayOutputStream out; UBWriter writer; byte[] array; out = new ByteArrayOutputStream(); writer = new UBWriter(out); value = UBValueFactory.createArray(new byte[]{ 0x3, 0x4}); writer.write(value); array = out.toByteArray(); assertEquals('[', array[0]); if(array[1] == '$') { assertTrue(array[2] == 'i' || array[2] == 'U'); assertEquals('#', array[3]); assertTrue(array[4] == 'i' || array[4] == 'U'); assertEquals(2, array[5]); assertEquals(0x3, array[6]); assertEquals(0x4, array[7]); assertEquals(8, array.length); } else if(array[1] == '#') { assertTrue(array[2] == 'i' || array[2] == 'U'); assertEquals(2, array[3]); } else { assertTrue(array[2] == 'i' || array[2] == 'U'); assertEquals(3, array[3]); assertTrue(array[4] == 'i' || array[4] == 'U'); assertEquals(4, array[5]); assertEquals(']', array[6]); } } @Test public void testWriteObject() throws Exception { ByteArrayOutputStream out; UBWriter writer; byte[] array; UBObject obj = UBValueFactory.createObject(); obj.put("hello", UBValueFactory.createString("world")); obj.put("array", UBValueFactory.createArray(new int[] {1,2,3})); out = new ByteArrayOutputStream(); writer = new UBWriter(out); writer.write(obj); array = out.toByteArray(); assertEquals('{', array[0]); } @Test public void testWriteStringArray() throws Exception { ByteArrayOutputStream out; UBWriter writer; byte[] array; out = new ByteArrayOutputStream(); writer = new UBWriter(out); writer.write(UBValueFactory.createArray(new String[]{"a", "b", "c"})); array = out.toByteArray(); assertEquals('[', array[0]); assertEquals('$', array[1]); assertEquals('S', array[2]); assertEquals('#', array[3]); assertEquals('U', array[4]); assertEquals(0x3, array[5]); assertEquals('U', array[6]); assertEquals(0x1, array[7]); assertEquals('a', array[8]); assertEquals('U', array[9]); assertEquals(0x1, array[10]); assertEquals('b', array[11]); assertEquals('U', array[12]); assertEquals(0x1, array[13]); assertEquals('c', array[14]); assertEquals(15, array.length); } @Test public void testWriteByteArray() throws Exception { byte[] data = new byte[30]; Random r = new Random(1); r.nextBytes(data); UBValue value = UBValueFactory.createArray( UBValueFactory.createArray(data) ); ByteArrayOutputStream out; UBWriter writer; out = new ByteArrayOutputStream(); writer = new UBWriter(out); writer.write(value); ByteArrayInputStream input = new ByteArrayInputStream(out.toByteArray()); UBReader reader = new UBReader(input); UBValue outputValue = reader.read(); assertTrue(outputValue.isArray()); assertEquals(1, outputValue.asArray().size()); assertEquals(30, outputValue.asArray().get(0).asByteArray().length); } @Test public void testWriteData() throws Exception { ByteArrayOutputStream out; UBWriter writer; byte[] array; out = new ByteArrayOutputStream(); writer = new UBWriter(out); byte[] data = new byte[10000]; Random r = new Random(1); r.nextBytes(data); writer.writeData(data.length, new ByteArrayInputStream(data)); array = out.toByteArray(); assertEquals('I', array[0]); assertEquals(39, array[1]); assertEquals(16, array[2]); byte[] actual = new byte[10000]; System.arraycopy(array, 3, actual, 0, 10000); assertArrayEquals(data, actual); } }
28.573944
87
0.578312
32acc67eb669e6a3e4d0cc89ad0d1c2290e67732
2,351
package com.fitmgr.common.security.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClientsConfiguration; /** * @author Fitmgr * @date 2018/9/5 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @EnableFeignClients public @interface EnableFitmgrFeignClients { /** * Alias for the {@link #basePackages()} attribute. Allows for more concise * annotation declarations e.g.: {@code @ComponentScan("org.my.pkg")} instead of * {@code @ComponentScan(basePackages="org.my.pkg")}. * * @return the array of 'basePackages'. */ String[] value() default {}; /** * Base packages to scan for annotated components. * <p> * {@link #value()} is an alias for (and mutually exclusive with) this * attribute. * <p> * Use {@link #basePackageClasses()} for a type-safe alternative to String-based * package names. * * @return the array of 'basePackages'. */ String[] basePackages() default { "com.fitmgr" }; /** * Type-safe alternative to {@link #basePackages()} for specifying the packages * to scan for annotated components. The package of each class specified will be * scanned. * <p> * Consider creating a special no-op marker class or interface in each package * that serves no purpose other than being referenced by this attribute. * * @return the array of 'basePackageClasses'. */ Class<?>[] basePackageClasses() default {}; /** * A custom <code>@Configuration</code> for all feign clients. Can contain * override <code>@Bean</code> definition for the pieces that make up the * client, for instance {@link feign.codec.Decoder}, * {@link feign.codec.Encoder}, {@link feign.Contract}. * * @see FeignClientsConfiguration for the defaults */ Class<?>[] defaultConfiguration() default {}; /** * List of classes annotated with @FeignClient. If not empty, disables classpath * scanning. * * @return */ Class<?>[] clients() default {}; }
31.77027
84
0.671629
f35f825095883bc9cbe12c6221b1f0d4fc0c3a5b
504
/* * 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 rs.etf.teststudent.utils; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class LoginData { private String email; private String password; }
21
79
0.781746
f4e3b563c155a43e45a0bbd8728c98ac42dec7cf
181
class Test { void h(int i, String[] s, String[] t) { <selection>System.out.println(t[i]); final String s1 = s[t[i].length()];</selection> System.out.println(s1); } }
25.857143
51
0.596685
e5c2fbd87506b06eace2ae19893efffbd3f5bf72
1,593
package org.fabiomsr.mitaller.module.receipt.add.adapter.holder; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import org.fabiomsr.mitaller.R; import org.fabiomsr.mitaller.app.base.adapter.BaseViewHolder; import org.fabiomsr.mitaller.app.base.adapter.OnRecycleViewItemClickListener; import org.fabiomsr.mitaller.domain.ReceiptConcept; import butterknife.Bind; import butterknife.ButterKnife; public class ReceiptConceptViewHolder extends BaseViewHolder<ReceiptConcept> { @Bind(R.id.receipt_concept_description) TextView mDescriptionView; @Bind(R.id.receipt_concept_count) TextView mCountView; @Bind(R.id.receipt_concept_total) TextView mTotalView; @Bind(R.id.remove_concept) ImageView mRemoveConceptView; private ReceiptConcept mReceiptConcept; public ReceiptConceptViewHolder(View itemView, OnRecycleViewItemClickListener<ReceiptConcept> listener) { super(itemView, listener); ButterKnife.bind(this, itemView); mRemoveConceptView.setOnClickListener(v -> listener.onRecycleViewItemClick(v, mReceiptConcept, getAdapterPosition())); } public void update(ReceiptConcept concept){ mReceiptConcept = concept; mDescriptionView.setText(mReceiptConcept.concept()); Context context = itemView.getContext(); mCountView.setText(context.getString(R.string.receipt_item_count_format, mReceiptConcept.count(), mReceiptConcept.amount())); mTotalView.setText(context.getString(R.string.receipt_total_format, mReceiptConcept.totalAmount())); } }
34.630435
107
0.800377
3a98bb65e02f48d69fffb0ad8fb243dcadbb597c
759
package com.alibaba.alink.operator.batch.source; import org.apache.flink.types.Row; import com.alibaba.alink.testutil.AlinkTestBase; import org.junit.Assert; import org.junit.Test; public class NumSeqSourceBatchOpTest extends AlinkTestBase { @Test public void testConstructorFromTo() { NumSeqSourceBatchOp numSeqSourceBatchOp = new NumSeqSourceBatchOp(0, 1); Assert.assertArrayEquals(numSeqSourceBatchOp.collect().toArray(new Row[0]), new Row[] {Row.of(0L), Row.of (1L)}); } @Test public void testConstructorParams() { NumSeqSourceBatchOp numSeqSourceBatchOp = new NumSeqSourceBatchOp() .setFrom(0) .setTo(1); Assert.assertArrayEquals(numSeqSourceBatchOp.collect().toArray(new Row[0]), new Row[] {Row.of(0L), Row.of (1L)}); } }
28.111111
107
0.757576
2f0669e98c106b6587f1ad35dae5a6d4a8ec3105
1,520
package pl.umk.mat.fastSDA.SDA; import pl.umk.mat.fastSDA.image.Image; import pl.umk.mat.fastSDA.image.Image2D; import pl.umk.mat.fastSDA.image.Shape3D; import pl.umk.mat.fastSDA.procesUtils.Messenger; import pl.umk.mat.fastSDA.procesUtils.PikoProgress; import pl.umk.mat.fastSDA.sdaUtils.ImageRewriters; import pl.umk.mat.fastSDA.values.SDA_Params; import java.util.ArrayList; import java.util.List; public class Sda3DAbstract extends SdaAbstract{ final Image image; Shape3D shape3D; int deep; List<Image2D> image2DList = new ArrayList<>(); List<int[][]> bufferList = new ArrayList<>(); public Sda3DAbstract(Image image, SDA_Params params, PikoProgress pbar, Messenger messenger) { super(image.getScale(),image.getShape2D(), params, pbar, messenger); this.image = image; shape3D = image.getShape3D(); deep = shape3D.getZ(); for (int z = 0; z < deep; z++) { Image2D slice = image.getSlice(z); image2DList.add(slice); bufferList.add(new int[shape2D.getX()][shape2D.getY()]); } // overWhite = IntStream // .range(0,deep) // .map(z->getMaxColor(image.getSlice(z))) // .max() // .orElse(0); // log.info("OverWhite set on "+overWhite); } void copyNewImage() { for (int z = 0; z < deep; z++) ImageRewriters.putBufferIntoImage2D( image2DList.get(z), scale, shape2D, bufferList.get(z), log ); } }
33.777778
98
0.628947
3d64d7ee1dbfbd8f499d9352c77ba00218dbebc4
2,108
/** * PSA7A.java * * Created by: Zac Bolick, Huy Ha * * Date: 04/23/18 * * */ import java.util.Scanner; import java.awt.Color; public class PSA7A { public static void main(String[] args) { /* Connecting a Scanner object to the keyboard */ Scanner keyboard = new Scanner(System.in); Color[] boxColors = {Color.RED, Color.GREEN, Color.BLUE}; /* Choosing a picture and initializing variables. */ Picture pic = new Picture(FileChooser.pickAFile()); int x, y, width, height; pic.show(); int pictureWidth = pic.getWidth(); int pictureHeight = pic.getHeight(); System.out.println("Picture loaded - width: " + pictureWidth +" height: "+ pictureHeight); // Attempt to draw 3 boxes int boxesDrawn = 0; while (boxesDrawn < 3) { /* Prompting the user for coordinates. */ String prompt = "Please enter the upper left corner (first x, then y) of "; String prompt2 = "the box to draw."; System.out.println(prompt + prompt2); /* Converting coordinates to ints. */ x = keyboard.nextInt(); y = keyboard.nextInt(); /* Prompting the user for width and height. */ System.out.println("Please enter the width of the box to flip."); width = keyboard.nextInt(); System.out.println("Please enter the height of the box to flip."); height = keyboard.nextInt(); // Check if input is within bounds before drawing if (x < pictureWidth && y < pictureHeight && x + width < pictureWidth && y + height < pictureHeight && x + width > 0 && y + height > 0 && x > 0 && y > 0) { pic.drawBoxAtOffset (x, y, width, height, boxColors[boxesDrawn]); /* Repainting the picture with the box drawn. */ pic.repaint(); // Draw the box boxesDrawn++; } else { String error = "ERROR: Range is out of bound. Please choose a range that is within (0,0) and "; System.out.println(error + "(" + pictureWidth + ", " + pictureHeight + ")" + "!!!"); } } } }
30.550725
105
0.586812
750129cbb0bf8ca783ba4ab881c654e077858d4f
875
package cn.eggnetech.eggnetechmybatis.dao.impl; import cn.eggnetech.eggnetechmybatis.dao.UserDao; import cn.eggnetech.eggnetechmybatis.pojo.User; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * @name: * @description: Created by Benny Zhou on 2020/3/30 */ @Repository("userDao") public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { @Autowired @Override public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); } @Override public List<User> list() { return getSqlSession().selectList("cn.eggnetech.eggnetechmybatis.user.mapper.list"); } }
29.166667
92
0.777143
38de8d3d1e907b29668387960e73be1aad47a255
5,047
/* * Copyright (c) 2009, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ package se.sics.cooja.plugins.skins; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.Observable; import java.util.Observer; import org.apache.log4j.Logger; import se.sics.cooja.ClassDescription; import se.sics.cooja.Mote; import se.sics.cooja.Simulation; import se.sics.cooja.SimEventCentral.MoteCountListener; import se.sics.cooja.interfaces.Position; import se.sics.cooja.plugins.Visualizer; import se.sics.cooja.plugins.VisualizerSkin; /** * Visualizer skin for mote positions. * * Paints the three dimensional mote position on the right-hand side of the mote. * * @author Fredrik Osterlind */ @ClassDescription("Positions") public class PositionVisualizerSkin implements VisualizerSkin { private static Logger logger = Logger.getLogger(PositionVisualizerSkin.class); private Simulation simulation = null; private Visualizer visualizer = null; private Observer positionObserver = new Observer() { public void update(Observable obs, Object obj) { visualizer.repaint(); } }; private MoteCountListener simObserver = new MoteCountListener() { public void moteWasAdded(Mote mote) { Position p = mote.getInterfaces().getPosition(); if (p != null) { p.addObserver(positionObserver); } } public void moteWasRemoved(Mote mote) { Position p = mote.getInterfaces().getPosition(); if (p != null) { p.deleteObserver(positionObserver); } } }; public void setActive(Simulation simulation, Visualizer vis) { this.simulation = simulation; this.visualizer = vis; simulation.getEventCentral().addMoteCountListener(simObserver); for (Mote m: simulation.getMotes()) { simObserver.moteWasAdded(m); } } public void setInactive() { simulation.getEventCentral().removeMoteCountListener(simObserver); for (Mote m: simulation.getMotes()) { simObserver.moteWasRemoved(m); } } public Color[] getColorOf(Mote mote) { return null; } public void paintBeforeMotes(Graphics g) { } public void paintAfterMotes(Graphics g) { g.setColor(Color.BLACK); /* Paint position coordinates right of motes */ Mote[] allMotes = simulation.getMotes(); for (Mote mote: allMotes) { Position pos = mote.getInterfaces().getPosition(); Point pixel = visualizer.transformPositionToPixel(pos); String msg = ""; String posString; String[] parts; /* X */ posString = String.valueOf(pos.getXCoordinate()) + "000"; parts = posString.split("\\."); if (parts[0].length() >= 4) { msg += parts[0]; } else { msg += posString.substring(0, 5); } /* Y */ msg += ", "; posString = String.valueOf(pos.getYCoordinate()) + "000"; parts = posString.split("\\."); if (parts[0].length() >= 4) { msg += parts[0]; } else { msg += posString.substring(0, 5); } /* Z */ if (pos.getZCoordinate() != 0) { msg += ", "; posString = String.valueOf(pos.getZCoordinate()) + "000"; parts = posString.split("\\."); if (parts[0].length() >= 4) { msg += parts[0]; } else { msg += posString.substring(0, 5); } } g.drawString(msg, pixel.x + Visualizer.MOTE_RADIUS + 4, pixel.y + 4); } } public Visualizer getVisualizer() { return visualizer; } }
31.742138
81
0.678027
15932f16fa436532661662647162b38aec20d51e
3,274
package com.moqi.data; import com.moqi.tool.Tool; /** * @author moqi * On 2/27/20 09:43 */ public class Data { public static final String TEXT_01_TXT = Tool.getStringFromFile("test01.txt"); public static final String TEXT_02_TXT = Tool.getStringFromFile("test02.txt"); public static final String TEXT_03_TXT = Tool.getStringFromFile("test03.txt"); public static final String TEXT_04_TXT = Tool.getStringFromFile("test04.txt"); public static final String TEXT_05_TXT = Tool.getStringFromFile("test05.txt"); public static final String TEXT_06_TXT = Tool.getStringFromFile("test06.txt"); public static final String TEXT_07_TXT = Tool.getStringFromFile("test07.txt"); public static final String TEXT_08_TXT = Tool.getStringFromFile("test08.txt"); public static final String TEXT_09_TXT = Tool.getStringFromFile("test09.txt"); public static final String TEXT_10_TXT = Tool.getStringFromFile("test10.txt"); public static final String TEXT_11_TXT = Tool.getStringFromFile("test11.txt"); public static final String TEXT_12_TXT = Tool.getStringFromFile("test12.txt"); public static final String TEXT_13_TXT = Tool.getStringFromFile("test13.txt"); public static final String TEXT_14_TXT = Tool.getStringFromFile("test14.txt"); public static final String TEXT_15_TXT = Tool.getStringFromFile("test15.txt"); public static final String TEXT_16_TXT = Tool.getStringFromFile("test16.txt"); public static final String TEXT_17_TXT = Tool.getStringFromFile("test17.txt"); public static final String TEXT_18_TXT = Tool.getStringFromFile("test18.txt"); public static final String TEXT_19_TXT = Tool.getStringFromFile("test19.txt"); public static final String TEXT_20_TXT = Tool.getStringFromFile("test20.txt"); public static final String TEXT_21_TXT = Tool.getStringFromFile("test21.txt"); public static final String TEXT_22_TXT = Tool.getStringFromFile("test22.txt"); public static final String TEXT_23_TXT = Tool.getStringFromFile("test23.txt"); public static final String TEXT_24_TXT = Tool.getStringFromFile("test24.txt"); public static final String TEXT_25_TXT = Tool.getStringFromFile("test25.txt"); public static final String TEXT_26_TXT = Tool.getStringFromFile("test26.txt"); public static final String TEXT_27_TXT = Tool.getStringFromFile("test27.txt"); public static final String TEXT_28_TXT = Tool.getStringFromFile("test28.txt"); public static final String TEXT_29_TXT = Tool.getStringFromFile("test29.txt"); public static final String TEXT_30_TXT = Tool.getStringFromFile("test30.txt"); public static final String TEXT_31_TXT = Tool.getStringFromFile("test31.txt"); public static final String TEXT_32_TXT = Tool.getStringFromFile("test32.txt"); public static final String TEXT_33_TXT = Tool.getStringFromFile("test33.txt"); public static final String TEXT_34_TXT = Tool.getStringFromFile("test34.txt"); public static final String TEXT_35_TXT = Tool.getStringFromFile("test35.txt"); public static final String TEXT_36_TXT = Tool.getStringFromFile("test36.txt"); public static final String TEXT_37_TXT = Tool.getStringFromFile("test37.txt"); public static final String TEXT_38_TXT = Tool.getStringFromFile("test38.txt"); }
64.196078
82
0.76573
6bb84c9ce68faef87eba1f02f4b35d11e9f9996c
748
package connect.ui.activity.set.bean; /** * Created by Administrator on 2016/12/7. */ public class GcmBean { private String iv; private String aad; private String tag; private String ciphertext; public String getIv() { return iv; } public void setIv(String iv) { this.iv = iv; } public String getAdd() { return aad; } public void setAdd(String add) { this.aad = add; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getCiphertext() { return ciphertext; } public void setCiphertext(String ciphertext) { this.ciphertext = ciphertext; } }
17
50
0.580214
5b6b02cafc423c4517f5d5fa59596bf83d7fe74d
1,658
package com.bbn.serif.theories; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.util.AbstractList; import java.util.List; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public final class GornAddress extends AbstractList<Integer> { public GornAddress(Iterable<Integer> address) { this.address = ImmutableList.copyOf(address); checkArgument(!this.address.isEmpty()); checkArgument(this.address.get(0) == 0, "First element of Gorn address must be 0"); } private static final Pattern VALID_GORN_ADDRESS = Pattern.compile("0(.\\d+)*"); private static final Splitter SPLIT_ON_DOTS = Splitter.on("."); public static GornAddress fromString(final String gornAddress) { checkNotNull(gornAddress); checkArgument(!gornAddress.isEmpty()); checkArgument(VALID_GORN_ADDRESS.matcher(gornAddress).matches(), String.format("Invalid Gorn address: %s", gornAddress)); List<Integer> ret = Lists.newArrayList(); for (final String part : SPLIT_ON_DOTS.split(gornAddress)) { ret.add(Integer.valueOf(part)); } return new GornAddress(ret); } private static Joiner dottedJoiner = Joiner.on("."); public String toDottedString() { return dottedJoiner.join(this); } private final List<Integer> address; @Override public Integer get(int idx) { return address.get(idx); } @Override public int size() { return address.size(); } }
27.633333
87
0.733414
9816e7bcbd08714617ae79282b0c5efc2daa10f7
1,062
package br.com.zupacademy.armando.transaction.listeners.transaction; import br.com.zupacademy.armando.transaction.entities.Transaction; import br.com.zupacademy.armando.transaction.repositories.TransactionRepository; import org.springframework.context.annotation.Bean; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.support.converter.JsonMessageConverter; import org.springframework.stereotype.Component; @Component public class ListenerTransaction { private TransactionRepository transactionRepository; public ListenerTransaction(TransactionRepository transactionRepository) { this.transactionRepository = transactionRepository; } @Bean JsonMessageConverter jsonMessageConverter() { return new JsonMessageConverter(); } @KafkaListener(topics = "${spring.kafka.topic.transactions}") public void listen(EventTransaction eventTransaction) { Transaction newTransaction =eventTransaction.toModel(); transactionRepository.save(newTransaction); } }
35.4
80
0.801318
f8474ba0c1ccb7a24a8b332082c33f11464560bf
2,984
/** LEGACY CODE * * This was salvaged in part or in whole from the Legacy System. It will be heavily refactored or removed. */ package gov.dot.its.jpo.sdcsdw.websocketsfragment.mongo; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import org.apache.log4j.Logger; import gov.dot.its.jpo.sdcsdw.websocketsfragment.server.WebSocketEventListener; import gov.dot.its.jpo.sdcsdw.websocketsfragment.server.WebSocketServer; public class MongoQueryEventListener implements WebSocketEventListener { private static final Logger logger = Logger.getLogger(MongoQueryEventListener.class .getName()); private final static String QUERY_TAG = "QUERY:"; private final static String SYSTEM_NAME = "systemQueryName"; private List<MongoConfig> mongoConfigs; private Map<String, MongoQueryRunner> queryRunnerMap = new HashMap<String, MongoQueryRunner>(); public MongoQueryEventListener(List<MongoConfig> mongoConfigs) { this.mongoConfigs = mongoConfigs; } public void connect() { for (MongoConfig config: mongoConfigs) { MongoQueryRunner queryRunner = new MongoQueryRunner(config); queryRunner.connect(); queryRunnerMap.put(config.systemName, queryRunner); } } public void close() { logger.debug("Query runner is closing"); for (MongoQueryRunner queryRunner: queryRunnerMap.values()) { queryRunner.close(); } queryRunnerMap.clear(); } public void onMessage(String websocketID, String message) { if (message.startsWith(QUERY_TAG)) { logger.info("Received query message " + message + " from websocket " + websocketID); message = message.substring(QUERY_TAG.length()).trim(); JSONObject json = (JSONObject)JSONSerializer.toJSON(message); if (json.containsKey(SYSTEM_NAME)) { String systemName = json.getString(SYSTEM_NAME); if (queryRunnerMap.containsKey(systemName)) { queryRunnerMap.get(systemName).runQuery(websocketID, json, message); logger.info( String.format("Processed query for websocketID %s, query %s", websocketID, json.toString())); } else { String errorMsg = "Invalid systemQueryName: " + systemName + ", not one of the supported systemQueryName: " + queryRunnerMap.keySet().toString(); logger.error(errorMsg); WebSocketServer.sendMessage(websocketID, "ERROR: " + errorMsg); } } else { String errorMsg = "Query message missing required systemQueryName field"; logger.error(errorMsg); WebSocketServer.sendMessage(websocketID, "ERROR: " + errorMsg); } } else { logger.debug("Query runner ignoring: " + message); } } public void onOpen(String websocketID) { // do nothing } public void onClose(String websocketID) { /*for (MongoQueryRunner queryRunner: queryRunnerMap.values()) { queryRunner.killRunningQueries(websocketID); }*/ } }
34.697674
107
0.713807
941246be24aff99c4b6f28cbbaef8b943deb23cf
68
package me.swaro32; public class Time { public int unixtime; }
11.333333
24
0.705882
c92d08238064d39818a5e21520346acd103654de
2,834
/* * Copyright 2008 Stichting JoiningTracks, The Netherlands * 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.apache.wicket.security.examples.springsecurity; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.wicket.spring.injection.annot.SpringComponentInjector; import org.apache.wicket.spring.test.ApplicationContextMock; /** * Test the HomePage and follow up pages. * * @author Olger Warnier */ public class HomePageTest extends AbstractSecureTestPage { protected static final Log log = LogFactory.getLog(HomePageTest.class); @Override protected void setUp() throws Exception { super.setUp(); ApplicationContextMock appctx = new ApplicationContextMock(); application.addComponentInstantiationListener(new SpringComponentInjector(application, appctx, true)); } /** * Test Login to the application. This makes use of a mock login page as the * application is based upon Spring Security authentication. */ public void testLogin() { loginToApp("test"); logoutOfApp(); } public void testStartFirstSecure() { /* * mock.startPage(MockLoginPage.class); mock.setupRequestAndResponse(); * assertTrue(mock.getWicketSession().isTemporary()); * mock.processRequestCycle(MockLoginPage.class); // loginpage, else the homepage * will be used which will trigger a bind // because a throw * restartResponseAtInterceptPageexception will trigger // a session.bind * SwarmFormTester form = mock.newFormTester("form"); form.setValue("username", * "test"); form.submit(); mock.assertRenderedPage(MockHomePage.class); * mock.setupRequestAndResponse(); assertFalse(Session.get().isTemporary()); * mock.processRequestCycle(MockLoginPage.class); */ ApplicationContextMock appctx = new ApplicationContextMock(); // appctx.putBean("patientService", patientService); application.addComponentInstantiationListener(new SpringComponentInjector(application, appctx, true)); loginToApp("user"); // first link is the create patient link // have to set the proper controls in order to proceed. mock.assertRenderedPage(HomePage.class); // mock.clickLink("to_firstsecure"); // Page thePage = mock.getLastRenderedPage(); // mock.assertRenderedPage(FirstSecurePage.class); logoutOfApp(); } }
32.574713
88
0.757234
448b39e137ab77011dd46593970f5129f1edfd3e
1,924
package com.work; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Work01 { public static void main(String[] args) { //1.先设置一个总窗口 Frame frame = new Frame("作业窗口"); //2.通过表格布局把总窗口分成上下两个面板 frame.setLayout(new GridLayout(2,1)); //3.把上面版p1设置成东西南北中布局, Panel p1 = new Panel(new BorderLayout()); //然后在上面版中间内嵌一个面板p2,通过表格布局把p2分成上下两个小面板 Panel p2 = new Panel(new GridLayout(2,1)); //4.把下面版p3也设置成东西南北中布局, Panel p3 = new Panel(new BorderLayout()); //然后在下面版中间内嵌一个面板p4,通过表格布局把p2分成四个小面板 Panel p4 = new Panel(new GridLayout(2,2)); frame.setBounds(300,300,400,400); //在上面版p1左右两边各设置一个按钮,用东西南北中布局 p1.add(new Button("East-1"),BorderLayout.EAST); p1.add(new Button("West-1"),BorderLayout.WEST); //在上中面版p2上下各设置一个按钮,用表格布局 p2.add(new Button("btn1")); p2.add(new Button("btn2")); //在下面版p2左右两边各设置一个按钮,用东西南北中布局 p3.add(new Button("East-2"),BorderLayout.EAST); p3.add(new Button("West-2"),BorderLayout.WEST); //在下中面版p4上下各设置一个按钮,用表格布局 p4.add(new Button("btn-3")); p4.add(new Button("btn-4")); p4.add(new Button("btn-5")); p4.add(new Button("btn-6")); //也可以用for循环来设置四个按钮 // for (int i = 0; i < 4; i++) { // p4.add(new Button("btn-"+i)); // } //把p2,p4放进p1,p2中间区域 p1.add(p2,BorderLayout.CENTER); p3.add(p4,BorderLayout.CENTER); frame.add(p1); frame.add(p3); frame.setVisible(true); //监听事件,监听窗口关闭事件 System.exit(0)强制结束 //适配器模式 frame.addWindowListener(new WindowAdapter() { //点击窗口关闭要做的事情 @Override public void windowClosing(WindowEvent e) { //结束程序 System.exit(0); } }); } }
26.356164
55
0.565489
e3222ed868050de1497d81100fa5202fd44b4514
5,964
/* * Licensed to GraphHopper and Peter Karich under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.util; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; /** * @author Peter Karich */ public class Downloader { public static void main( String[] args ) throws IOException { new Downloader("GraphHopper Downloader").downloadAndUnzip("http://graphhopper.com/public/maps/0.1/europe_germany_berlin.ghz", "somefolder", new ProgressListener() { @Override public void update( long val ) { System.out.println("progress:" + val); } }); } private String referrer = "http://graphhopper.com"; private final String userAgent; private String acceptEncoding = "gzip, deflate"; private int timeout = 4000; public Downloader( String userAgent ) { this.userAgent = userAgent; } public Downloader setTimeout( int timeout ) { this.timeout = timeout; return this; } public Downloader setReferrer( String referrer ) { this.referrer = referrer; return this; } /** * This method initiates a connect call of the provided connection and returns the response * stream. It only returns the error stream if it is available and readErrorStreamNoException is * true otherwise it throws an IOException if an error happens. Furthermore it wraps the stream * to decompress it if the connection content encoding is specified. */ public InputStream fetch( HttpURLConnection connection, boolean readErrorStreamNoException ) throws IOException { // create connection but before reading get the correct inputstream based on the compression and if error connection.connect(); InputStream is; if (readErrorStreamNoException && connection.getResponseCode() >= 400 && connection.getErrorStream() != null) is = connection.getErrorStream(); else is = connection.getInputStream(); if (is == null) throw new IOException("Stream is null. Message:" + connection.getResponseMessage()); // wrap try { String encoding = connection.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) is = new GZIPInputStream(is); else if (encoding != null && encoding.equalsIgnoreCase("deflate")) is = new InflaterInputStream(is, new Inflater(true)); } catch (IOException ex) { } return is; } public InputStream fetch( String url ) throws IOException { return fetch((HttpURLConnection) createConnection(url), false); } public HttpURLConnection createConnection( String urlStr ) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Will yield in a POST request: conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(true); conn.setRequestProperty("Referrer", referrer); conn.setRequestProperty("User-Agent", userAgent); // suggest respond to be gzipped or deflated (which is just another compression) // http://stackoverflow.com/q/3932117 conn.setRequestProperty("Accept-Encoding", acceptEncoding); conn.setReadTimeout(timeout); conn.setConnectTimeout(timeout); return conn; } public void downloadFile( String url, String toFile ) throws IOException { HttpURLConnection conn = createConnection(url); InputStream iStream = fetch(conn, false); int size = 8 * 1024; BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(toFile), size); InputStream in = new BufferedInputStream(iStream, size); try { byte[] buffer = new byte[size]; int numRead; while ((numRead = in.read(buffer)) != -1) { writer.write(buffer, 0, numRead); } } finally { Helper.close(writer); Helper.close(in); } } public void downloadAndUnzip( String url, String toFolder, final ProgressListener progressListener ) throws IOException { HttpURLConnection conn = createConnection(url); final int length = conn.getContentLength(); InputStream iStream = fetch(conn, false); new Unzipper().unzip(iStream, new File(toFolder), new ProgressListener() { @Override public void update( long sumBytes ) { progressListener.update((int) (100 * sumBytes / length)); } }); } public String downloadAsString( String url, boolean readErrorStreamNoException ) throws IOException { return Helper.isToString(fetch((HttpURLConnection) createConnection(url), readErrorStreamNoException)); } }
35.712575
147
0.642186
099a63314b460eadaa9dc3e553d0d9e78098e351
23,629
/* Copyright 2018 Case Western Reserve University * * 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 edu.cwru.pp4j.recode.proteins; import java.util.regex.Matcher; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.concurrent.LinkedBlockingQueue; /** * Encapsulates the necessary information and algorithms to iteratively create * a set of peptides from a protein sequence using a defined protease. The * peptides can be "streamed" in that once the object is created and initialized * they are returned by calling getNext() on the object until it returns an * empty array. This class was developed for use in sequential processing algorithms * that need to generate numbers of peptides too large to store in memory * all at once.<br><br> * * The rules by which Proteases cleave protein sequences are complex, but to * understand this algorithm you only need to know:<br> * <ol> * <li> A single cleavage event may cut the protein sequence more than once. </li> * <li> Cleavages are likely to happen but not guaranteed (termed as a "missed cleavage").</li> * </ol> * * For the first item, we search along a protein sequence until we find the next * cut site and then return an array containing the peptides that were created * by cleaving at that site. Subsequent searched start from the last site * and move toward the end of the protein.<br><br> * * For the second item, the number of missed cleavages sets a sort of * sliding window on what peptides can be generated. If the user specifies * N missed cleavages, the implementation allocates N+1 queues to hold peptide * sequences. The order in which peptides are added and removed from the queues * simulates a sliding window that encapsulates the generation of peptides with * missed cleavages.<br><br> * * Pseudocode: * <pre> * queues[] &lt;- queues up to number of missed cleavages + 1 * * <strong>while</strong> there are cleave sites remaining * peptides[] &lt;- peptides from next cleave event * <strong>for</strong> i=0 to number of peptides - 1 * <strong>for</strong> j=0 to number of missed cleavages * queues[j].add(peptides[i]); * <strong>endfor</strong> * <strong>for</strong> j=0 to the number of full queues -1 * output queues[j] as string * queues[j].remove() * <strong>endfor</strong> * <strong>endfor</strong> * <strong>endwhile</strong> * </pre> * * Example: * <pre> * Protease: Trypsin (cleaves after R and K) * Peptide: AKTRL * Missed Cleavages: 2 * * queues = [[],[],[]] * First Call to GetNext() * peptides = ["AK"] * queues = [["AK"],["AK"]] * output : "AK" * * Second Call to GetNext() * peptides = ["TR"] * queues = [["TR"],["AK","TR"]] * output : "TR" * output : "AKTR" * * Third Call to GetNext() * peptides = ["L"] * queues = [["L"],["TR","L"],["AK","TR","L"]] * output : "L" * output : "TRL" * output : "AKTRL" * </pre> * * @author Sean Maxwell */ public class PeptideFactory { private final HashMap<String,Protease> proteases; private Matcher m; private String seq = ""; private String pro = ""; private int start = 0; private String message = "OK"; private LinkedBlockingQueue[] peptides; private long found = 0; private int count = 0; private int nmiss = 0; private int search = 0; private Protease prot; /** * Constructor creates a new peptide factory with a database of available * proteases configured. * * @param strict Indicates if the proteases should use Expasy rules verbatim * or use a more relaxed approach of cleaving predictably on single amino * acid codes. * */ public PeptideFactory(boolean strict) { /* Create the lookup table of Protease deffinitions */ proteases = new HashMap<>(); proteases.put("AspN", new Protease("D",0)); proteases.put("AspN/N->D", new Protease("[DE]",0)); proteases.put("Chymotrypsin", new Protease("[FYW]",1)); proteases.put("GluC", new Protease("[E]",1)); proteases.put("LysC", new Protease("K",1)); proteases.put("Pepsin, pH=1.3", new Protease("[FL]",0)); proteases.put("Pepsin, pH=2.0", new Protease("[FLWY]",0)); proteases.put("Trypsin", new Protease("[RK]",1)); proteases.put("Non-specific", new Protease(".",1)); /* If we are being strict, create site matchers and exclusions for * relevant proteases. */ if(strict) { /* Add site matchers */ ((Protease)proteases.get("Chymotrypsin" )).addMatcher("([FY][^P])|(W[^MP])" , 0, 1, 1); /* It is suggested in the Expasy documentation that the Glutamyl * endopeptidase is inhibited form cleaving when Proline(P) appears * 2 postions before E, after E or 2 amino acids after E, and that * Asp (D) immediately after E has a similar affect. However, in * in testing this does not seem to be enforced on the PeptideCutter * interface and cleavage happens predictably on all E ((Protease)proteases.get("GluC" )).addMatcher("[^P]..[E][^DP][^P]" , 0, 1, 1); */ ((Protease)proteases.get("Pepsin, pH=1.3")).addMatcher("[^HKR][^P][^R][FL][^P]", 3, 1, 0); ((Protease)proteases.get("Pepsin, pH=1.3")).addMatcher("[^HKR][^P][FL].[^P]" , 2, 2, 1); ((Protease)proteases.get("Pepsin, pH=2.0")).addMatcher("[^HKR][^P][^R][FLWY][^P]" , 3, 1, 0); ((Protease)proteases.get("Pepsin, pH=2.0")).addMatcher("[^HKR][^P][FLWY].[^P]" , 2, 2, 1); ((Protease)proteases.get("Trypsin" )).addMatcher("(WKP)|(MRP)|[KR][^P]" , 1, 1, 1); /* Add site exclusions */ ((Protease)proteases.get("Trypsin" )).addExclusion("([CD]KD)|(CK[HY])|(CRK)|(RR[HR])", 1, 1); } else { /* Pepsin cuts both before and after the cut site, so add the secondary * cut sites now */ ((Protease)proteases.get("Pepsin, pH=1.3")).addMatcher("[FL]" , 0, 0, 0); ((Protease)proteases.get("Pepsin, pH=2.0")).addMatcher("[FLWY]" , 0, 0, 0); ((Protease)proteases.get("Pepsin, pH=1.3")).addMatcher("[FL]" , 0, 0, 1); ((Protease)proteases.get("Pepsin, pH=2.0")).addMatcher("[FLWY]" , 0, 0, 1); } } /** * Stores the argument amino acid sequence in the factory for * use when generating peptides. * * @param s The sequence string to associate with this object. * */ public void setSequence(String s) { this.seq = s.toUpperCase(); } /** * Returns the sequence String stored in the factory. * * @return The internal sequence String. * */ public String getSequence() { return this.seq; } /** * Configures the protease the factory will use to generate peptides. * * @param protease String name of the desired protease. * * @return true for success and false if the requested protease is invalid. * */ public boolean setProtease(String protease) { if(this.proteases.get(protease) != null) { this.pro = protease; return true; } else { this.message = "The requested protease is not contained in this object"; return false; } } /** * Adds a custom protease to the factory that can be used for * generating peptides. * * @param name String name of the protease * @param reg String regular expression that defines the cleavage rule(s) * @param co Cut offset from match position. 0 is left of, 1 is right of. * * @return true for success and false for failure. * */ public boolean addProtease(String name, String reg, int co) { try { this.proteases.put(name, new Protease(reg, co)); return true; } catch(Exception e) { this.message = e.toString(); return false; } } public boolean addCleavageSiteMatcher(String name, String reg, int left, int right, int co) { Protease protease = (Protease)proteases.get(name); if(protease == null) { this.message="Protease does not exist"; return false; } if(((Protease)proteases.get(name)).addMatcher(reg , left, right, co)) { return true; } else { return false; } } public boolean addCleavageSiteExclusion(String name, String reg, int left, int right) { Protease protease = (Protease)proteases.get(name); if(protease == null) { this.message="Protease does not exist"; return false; } if(protease.addExclusion(reg , left, right)) { return true; } else { return false; } } /** * Returns the String name of the configured protease. * * @return Protease name * */ public String getProteaseName() { return this.pro; } /** * Returns the configured Protease object for the factory. * @return The protease configured for the factory */ public Protease getProtease() { return this.proteases.get(this.pro); } /** * Set the number of missed cleavages to allow when generating peptides. * * @param missed The number of missed cleavages */ public void setMissedCleavages(int missed) { this.nmiss = missed; } /** * Retrieve the current setting for missed cleavages. * * @return The number of missed cleavages the object is using */ public int getMissedCleavages() { return this.nmiss; } /** * Retrieve how many peptides have been found up to now. The value is * updated every time GetNext() is called. * * @return The number of peptides generated thus far */ public long peptideCount() { return this.found; } /** * Retrieves the internal message String for the last operation. * * @return String message. * */ public String getMessage() { return this.message; } /** * Initializes the factory to sequentially generate peptides. * * @return true for success and false when an error occurs. * * @see #GetNext * @see #getMessage * */ public boolean start() { int i; try { this.peptides = new LinkedBlockingQueue[this.nmiss+1]; /* Initialize the peptide stacks for missed cleavages */ for(i=0;i<this.nmiss+1;i++) { peptides[i] = new LinkedBlockingQueue(); } /* initialize the internal reference to the requested protease */ this.prot = (Protease)this.proteases.get(this.pro); /* Set the matcher to the configured protease pattern matcher */ this.m = this.prot.getMatcher(this.seq); //cutters.matcher(this.seq); /* Set start position (the position to cut from) to 0 */ this.start = 0; this.found = 0; this.count = 0; this.search = 0; return true; } catch(Exception e) { this.message = e.toString(); return false; } } /** * Trim a Peptide array to the argument length. * * @param array Array to trim * @param length New array length * * @return Trimmed array */ private PeptideSimple[] TrimPeptideArray(PeptideSimple[] array, int length) { PeptideSimple[] pa = new PeptideSimple[length]; int i; for(i=0;i<length;i++) { pa[i] = array[i]; } return pa; } /** * Generates an array of peptides from an amino acid sequence, a cleavage * site position and an array of offsets from the site position at which to * cleave the sequence. * * @param seq The full protein sequence * @param offsets The offsets from the cut site to cleave at * @param site The cut site * * @return The array of peptides */ private PeptideSimple[] CutPeptide(String seq, int[] offsets, int site) { int j; int k; int n_offsets = 0; PeptideSimple r[]; /* Get the number of offsets */ for(j=0;j<offsets.length;j++) { if(offsets[j] != -1) { n_offsets++; } } /* Allocate return array */ r = new PeptideSimple[n_offsets]; /* Extract the peptides */ k = 0; for(j=0;j<offsets.length;j++) { if(offsets[j] != -1) { /* If the pepetide would be empty because multiple cuts happened * in the same place, skip it because we don't want empty * strings to be returned in the array. */ if((site+offsets[j])-this.start > 0) { r[k] = new PeptideSimple(seq.substring(this.start,site+offsets[j]), this.start); k++; } /* Move the start pointer to the next cut-from position */ this.start = site+offsets[j]; } } /* Trim any null elements off the end of the array. They appear there * when empty strings were skipped in the loop. */ return this.TrimPeptideArray(r,k); } /** * Returns the next set if peptides from the factory. * * @param onlyPeptidesWithThisManyMissedCleavages Dictates that the factory * only return peptides with exactly this many missed cleavages. * * @return Peptides while the end of the sequence has not been reached, and * null otherwise. * * @see #start() * */ public List<Peptide> GetNext(int onlyPeptidesWithThisManyMissedCleavages) { PeptideSimple[] r; String pep; Object[] peps; List<Peptide> rpeps = new ArrayList<>(); int i; int j; int k; int t; int nres = 0; int cut_sites; int[] cut_pos = new int[5]; int res_count = 0; int r_start; /* If we reached the end of the sequence, return null */ if(this.start == -1) { return null; } /* If our search parameter is beyond the end of the string */ if(this.search > this.seq.length()) { return null; } /* Extract the next peptide */ if(this.m.find(this.search)) { cut_sites = 0; /* The maximum window for cut sites is 5 base pairs, so the cut * position array is a static 5 elements and we reset it on every * iteration of the loop. If we ever have to increase the window for * a new protease we will want to increase this length. */ cut_pos[0] = -1; cut_pos[1] = -1; cut_pos[2] = -1; cut_pos[3] = -1; cut_pos[4] = -1; /* Check for exceptions to cut site */ for(i=0;i<this.prot.excluderCount();i++) { /* If the candidate cut position is in a region that matches one * of the configured exceptions to the cut rules for the * protease, move the search pointer one position forward, and * continue searching using recursion. */ if(this.prot.isExclusion(i, seq, this.m.start())) { this.search = this.m.start()+1; return this.GetNext(onlyPeptidesWithThisManyMissedCleavages); } } /* If the candidate cut site was not rejected by an exception, we * need to test each cut rule for the protease to determine how many * positions will cleave in the region */ for(i=0;i<this.prot.matcherCount();i++) { cut_pos[i] = this.prot.isCleaveSite(i, seq, this.m.start()); if(cut_pos[i] != -1) { cut_sites++; } } /* If all the cut rules failed to find a cleave site, move the * search position one character forward and continue using * recursion */ if(this.prot.matcherCount() > 0 && cut_sites == 0) { this.search = this.m.start()+1; return this.GetNext(onlyPeptidesWithThisManyMissedCleavages); } /* If there were no cut rules to use, because the protease cleaves * predictably on a single amino acid, use the offset from the * protease object for the cut position */ else if(this.prot.matcherCount() == 0) { cut_pos[0] = this.prot.offset(); cut_sites = 1; } /* Cut the peptide on all cut sites. This uses, and updates the * private member "start" so that at completion, it is positioned * at the last cut site. */ r = this.CutPeptide(this.seq, cut_pos, this.m.start()); /* If a situation occured where no cuts were made */ if(r.length == 0) { System.err.printf("Strange no-cleave with sites for %s (%d:%d)\nThis is not necessarily an error, but you may want to manually verify that the last few peptides of the protein are being cleaved as expected\n",this.seq,cut_sites,this.m.start()); this.search = this.m.start()+1; return this.GetNext(onlyPeptidesWithThisManyMissedCleavages); } /* Update the search parameter so that searching continues just past * the last candidate cleave site */ this.search = this.m.start()+1; /* Update the found counter to include all the cleavages found for * this candidate site */ this.found += r.length; } /* Otherwise, we reached the end of the sequence. Extract the final * peptide if there is anything left */ else { if(this.start < this.seq.length()) { r = new PeptideSimple[1]; r[0] = new PeptideSimple(this.seq.substring(this.start, this.seq.length()), this.start); this.found++; } else { r = new PeptideSimple[0]; } this.start = -1; this.search = this.seq.length()-1; } /* Loop over the returned peptides */ for(j=0;j<r.length;j++) { /* nres controls how many stacks we pop when generating peptides to * return. nres is equal to the number of fully populated stacks, * where a stack is fully populated when its size is equal to its * index+1 */ nres=0; for(i=0;i<this.nmiss+1;i++) { this.peptides[i].add(r[j]); if(this.peptides[i].size() == i+1) { nres++; //System.out.printf("%d is full: %s\n",nres,this.peptides[i].toString()); } } /* Loop over the number of stacks that have been fully populated. A * stack is fully populated when there are the same number of * elements in the stack as the value of it's index in the array. * This is equivalent to the number of missed cleavages represented * by the stack */ for(i=0;i<nres;i++) { pep = ""; /* Add each peptides on the stack to the temporary string */ peps = this.peptides[i].toArray(); r_start = ((PeptideSimple)peps[0]).start(); for(k=0;k<peps.length;k++) { pep += ((PeptideSimple)peps[k]).sequence(); } /* Add the result to the return array */ if(onlyPeptidesWithThisManyMissedCleavages == -1 || onlyPeptidesWithThisManyMissedCleavages == i) { //System.out.printf("%d Adding %s\n",nres,pep); rpeps.add(new PeptideSimple(pep,r_start)); res_count++; /* Update the count of how many peptides were generated */ this.count++; } /* Remove the oldest peptide from this queue */ this.peptides[i].remove(); } } return rpeps; } /** * Removes the N-terminus amino acid residue from a peptide. This is * intended to be used for cleaving N-terminus methionine, but no explicit * check is made to restrict removal of other amino acids. * * @param p Peptide to remove N-Terminus residue from * @return A peptide derived by removing the N-terminus amino acid from the * argument peptide, and incrementing the start position by 1. */ public static Peptide cleaveNTerm(Peptide p) { return new PeptideSimple(p.sequence().substring(1),p.start()+1); } /** * Calculates how many peptides will be generated by this factory during * a full run. * * @param onlyPeptidesWithThisManyMissedCleavages Dictates that the factory * only count peptides with exactly this many missed cleavages. * * @return How many peptides the object will create */ public int howMany(int onlyPeptidesWithThisManyMissedCleavages) { boolean status; List<Peptide> peptide; int n = 0; status = this.start(); if(status == false) { return 0; } peptide = this.GetNext(onlyPeptidesWithThisManyMissedCleavages); while(peptide != null) { n += peptide.size(); peptide = this.GetNext(onlyPeptidesWithThisManyMissedCleavages); } return n; } }
36.074809
260
0.567354
4aa16c7bbe4cd6c2f2cdc1eee9da085256ab98bb
1,549
package org.example.compiler; import javax.tools.*; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringSourceCompiler { /** 使用Pattern 获取类名 */ private static Pattern CLASS_PATTERN = Pattern.compile("class\\s+([$_a-zA-Z][$_a-zA-Z0-9]*)\\s*"); public static byte[] compile(String source, DiagnosticCollector<JavaFileObject> compileCollector) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavaFileManager javaFileManager = new StringJavaFileManager( compiler.getStandardFileManager(compileCollector, null, null)); // 从源码字符串中匹配类名 Matcher matcher = CLASS_PATTERN.matcher(source); String className; if (matcher.find()) { className = matcher.group(1); } else { throw new IllegalArgumentException("No valid class"); } JavaFileObject javaFileObject = new StringJavaFileObject(className, source); boolean result = compiler.getTask( null, javaFileManager, compileCollector, null, null, Collections.singletonList(javaFileObject)).call(); JavaFileObject byteFileObject = StringJavaFileManager.getFileObjectMap().get(className); if (result && byteFileObject != null) { byte[] classBytes = ((StringJavaFileObject) byteFileObject).getCompiledBytes(); return classBytes; } return null; } }
36.880952
104
0.641704
928d79f2aefbc0958030ce475094ed02f95616d7
1,401
package com.samuelchowi.intercorpretail.custom; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.util.AttributeSet; import com.samuelchowi.intercorpretail.R; import com.samuelchowi.intercorpretail.common.TypeFontUtils; import androidx.appcompat.widget.AppCompatTextView; public class IRTextView extends AppCompatTextView { public IRTextView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray array = context.getTheme().obtainStyledAttributes( attrs, R.styleable.IRTextStyle, 0, 0); int fontType; try { fontType = array.getInteger(R.styleable.IRTextStyle_customFont, 0); } finally { array.recycle(); } setTypeface(getCustomTypeFace(fontType)); } private Typeface getCustomTypeFace(int fontType) { switch (fontType) { case 0: return TypeFontUtils.loadHelveticaNormal(getContext().getAssets()); case 1: return TypeFontUtils.loadHelveticaBold(getContext().getAssets()); case 2: return TypeFontUtils.loadHelveticaNeueMedium(getContext().getAssets()); default: return TypeFontUtils.loadOmmnesSemiBold(getContext().getAssets()); } } }
31.133333
87
0.655246
375603538f2f11c42da7c5616c1cd674414a344f
3,432
public class Student_Runner_Boxcar { public static void main(String[] args) { // Testing various required behaviors of the Boxcar constructor System.out.println("Testing Boxcar constructors:"); Boxcar car1 = new Boxcar(); System.out.println("Printing Boxcar():\n" + car1 + "\n"); Boxcar car2 = new Boxcar("widgets", 7, false); System.out.println("Printing Boxcar(\"widgets\", 7, false):\n" + car2 + "\n"); Boxcar car3 = new Boxcar("WaDGeTs", 7, true); System.out.println("Testing lowercase cargo and setting cargo to 0 if in repair.\n"); System.out.println("Printing Boxcar(\"WaDGeTs\", 7, true):\n" + car3 + "\n"); Boxcar car4 = new Boxcar("OtherStuff", 7, false); System.out.println("Testing cargo other than accepted values.\n"); System.out.println("Printing Boxcar(\"OtherStuff\", 7, true):\n" + car4 + "\n"); // car2 is not burnt out. Lets call callForRepair on car2 and make sure it // gets marked for repair and set to 0 units. System.out.println("Testing callForRepair:"); car2.callForRepair(); System.out.println("Printing Boxcar called for repair:\n" + car2 + "\n"); // Let's test the loadCargo() method. We'll make a new Boxcar with 7 gadgets, // then load cargo until it reaches maximum capacity. Boxcar car5 = new Boxcar("gadgets", 7, false); car5.loadCargo(); // car5 should print out with 8 gadgets System.out.println("Printing Boxcar with 8 gadgets:\n" + car5 + "\n"); // now let's load cargo three more times. This should put the car over maximum // capacity and should keep the cargo size at 10. car5.loadCargo(); car5.loadCargo(); car5.loadCargo(); System.out.println("Printing Boxcar with 10 gadgets, tried to overload:\n" + car5 + "\n"); // lastly, let's test to make sure we can't load cargo onto a Boxcar that is in // repair, using car2. car2.loadCargo(); System.out.println("Printing Boxcar in repair, can't load (0 cargo):\n" + car2 + "\n"); System.out.println("Testing isFull:"); // Let's test a full car and a non-full car to make sure they return true and // false, respectively. Boxcar car6 = new Boxcar("gizmos", 10, false); Boxcar car7 = new Boxcar("widgets", 7, false); System.out.println("Printing isFull on full car:\n" + car6.isFull() + "\n"); System.out.println("Printing isFull on non-full car:\n" + car7.isFull() + "\n"); System.out.println("Testing getCargo:"); // Let's make sure car7 returns "widgets" as its cargo. System.out.println("Printing getCargo on a \"widgets\" car:\n" + car7.getCargo() + "\n"); System.out.println("Testing setCargo:"); // Making sure it can set cargo to "gadgets" car7.setCargo("gadgets"); System.out.println("Setting cargo to gadgets:\n" + car7 + "\n"); // Testing it will convert cargo to lowercase car7.setCargo("WADGetS"); System.out.println("Testing lowercase conversion (WADGetS -> wadgets):\n" + car7 + "\n"); // Testing it will set cargo to "gizsmos" if a nonvalid cargo is entered car7.setCargo("onions"); System.out.println("Testing invalid cargo type sets to gizmos (onions -> gizmos):\n" + car7 + "\n"); } }
52.8
108
0.617716
61fefe583f268255805099ff4d1b6d7e84b5e0f7
311
package vn.edu.uit.realestate.Relational.Repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import vn.edu.uit.realestate.Relational.Model.Job; public interface JobRepository extends JpaRepository<Job, Long>{ public Optional<Job> findByName(String name); }
25.916667
64
0.819936
bf47d711483aa164dc5a2b79207ccd167edf308f
476
package no.sikt.oai.exception; public class OaiException extends Exception { private final String errorCode; private final String errorText; public OaiException(String errorCode, String errorText) { super(errorCode + " " + errorText); this.errorCode = errorCode; this.errorText = errorText; } public String getErrorCode() { return errorCode; } public String getErrorText() { return errorText; } }
19.833333
61
0.653361
63c7d484628eb7a7ce5d31c9edd7b899c7bebadd
1,535
package learners; import main.InputRow; /*** * Represents a decider with a percentage of confidence known that is not 0 or 1. * This is used to distinguish a pair only. */ public class ConfidenceDecider extends LanguageDecision implements Decider { private final String languageOne, languageTwo; private final double fractionOne; /** * Creates a LanguageDecision based on the confidence between the two langauges. * @param languageOne The first language * @param languageTwo The second language * @param fractionOne The fraction that is the first language (in range [0.0, 1.0]) */ public ConfidenceDecider(String languageOne, String languageTwo, double fractionOne) { this.languageOne = languageOne; this.languageTwo = languageTwo; this.fractionOne = fractionOne; } @Override public LanguageDecision decide(InputRow row) { return this; } @Override public String representation(int numSpaces) { return "return " + languageOne + " with " + fractionOne + ", languageTwo with " + (1 - fractionOne); } @Override public double confidenceForLanguage(String language) { if (language.equals(languageOne)) { return fractionOne; } else if (language.equals(languageTwo)){ return 1 - fractionOne; } else { return 0; } } @Override public String mostConfidentLanguage() { return fractionOne > 0.5 ? languageOne : languageTwo; } }
29.519231
108
0.662541
0f05fa60db73e3d3dd86122475ff42735d136580
872
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.aws; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.HostName; import com.yahoo.config.provision.zone.ZoneApi; import com.yahoo.config.provision.zone.ZoneId; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * @author olaa */ public class MockResourceTagger implements ResourceTagger { Map<ZoneId, Map<HostName, ApplicationId>> values = new HashMap<>(); @Override public int tagResources(ZoneApi zone, Map<HostName, ApplicationId> ownerOfHosts) { values.put(zone.getId(), ownerOfHosts); return 0; } public Map<ZoneId, Map<HostName, ApplicationId>> getValues() { return values; } }
29.066667
112
0.737385
77f92fcc927d9904d73d36e662e0b01c50c20d07
1,564
/** * Copyright 2015 SPeCS. * * 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. under the License. */ package pt.up.fe.specs.xstreamplus; import java.io.File; import pt.up.fe.specs.library.IoUtils; import com.thoughtworks.xstream.XStream; public class XStreamUtils { /** * Helper method for XStream 'fromXML'. This version is unsafe, if the output class is not the same as the file * being read, throws an exception (ClassCastException?). * * @param file * @return */ @SuppressWarnings("unchecked") public static <T> T read(File file) { return (T) new XStream().fromXML(file); } /** * Converts an object to XML and then writes it to a file. * * @param file * @return */ public static void write(Object contents, File file) { IoUtils.write(toString(contents), file); } /** * Helper method for XStream 'toXML'. * * @param contents * @return */ public static String toString(Object contents) { return new XStream().toXML(contents); } }
28.436364
118
0.673913
07ad68a0b01270408c41bee449c6062166f2fe8b
13,932
package tests.restapi.proddevsplit; import java.io.IOException; import org.apache.wink.json4j.JSONException; import org.apache.wink.json4j.JSONObject; import org.apache.wink.json4j.JSONArray; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import tests.com.ibm.qautils.FileUtils; import tests.restapi.AirlockUtils; import tests.restapi.FeaturesRestApi; import tests.restapi.ProductsRestApi; import tests.restapi.RuntimeDateUtilities; import tests.restapi.RuntimeRestApi; import tests.restapi.SeasonsRestApi; public class CreateNewSeasonFromExistingSeason { protected String seasonID; protected String seasonID2; protected String mtxID1; protected String mtxID2; protected String featureID1; protected String featureID2; protected String featureID3; protected String featureID4; protected String featureID5; protected String configID1; protected String filePath; protected FeaturesRestApi f; protected ProductsRestApi p; protected SeasonsRestApi s; private AirlockUtils baseUtils; protected String productID; protected String m_url; private String sessionToken = ""; @BeforeClass @Parameters({"url", "analyticsUrl", "translationsUrl", "configPath", "sessionToken", "userName", "userPassword", "appName", "productsToDeleteFile"}) public void init(String url, String analyticsUrl, String translationsUrl, String configPath, String sToken, String userName, String userPassword, String appName, String productsToDeleteFile) throws Exception{ m_url = url; filePath = configPath ; p = new ProductsRestApi(); p.setURL(m_url); s = new SeasonsRestApi(); f = new FeaturesRestApi(); s.setURL(m_url); f.setURL(m_url); baseUtils = new AirlockUtils(url, analyticsUrl, translationsUrl, configPath, sToken, userName, userPassword, appName, productsToDeleteFile); sessionToken = baseUtils.sessionToken; productID = baseUtils.createProduct(); baseUtils.printProductToFile(productID); seasonID = baseUtils.createSeason(productID); } @Test (description="Create an mtx group in production under ROOT") public void createFirstMTX() throws JSONException, IOException, InterruptedException{ String dateFormat = f.setDateFormat(); String productionChangedOriginal = RuntimeDateUtilities.getProductionChangedFile(m_url, productID, seasonID, sessionToken); String mtx = FileUtils.fileToString(filePath + "feature-mutual.txt", "UTF-8", false); mtxID1 = f.addFeature(seasonID, mtx, "ROOT", sessionToken); String feature1 = FileUtils.fileToString(filePath + "feature1.txt", "UTF-8", false); JSONObject json1 = new JSONObject(feature1); json1.put("stage", "PRODUCTION"); featureID1 = f.addFeature(seasonID, json1.toString(), mtxID1, sessionToken); String feature2 = FileUtils.fileToString(filePath + "feature2.txt", "UTF-8", false); JSONObject json2 = new JSONObject(feature2); json2.put("stage", "PRODUCTION"); featureID2 = f.addFeature(seasonID, json2.toString(), mtxID1, sessionToken); //check if files were changed f.setSleep(); RuntimeRestApi.DateModificationResults responseDev = RuntimeDateUtilities.getDevelopmentFileDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(responseDev.code ==200, "Runtime development feature file was not updated"); RuntimeRestApi.DateModificationResults responseProd = RuntimeDateUtilities.getProductionFileDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(responseProd.code ==200, "Runtime production feature file was not changed"); RuntimeRestApi.DateModificationResults prodChanged = RuntimeDateUtilities.getProductionChangedDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(prodChanged.code ==200, "productionChanged.txt file was not changed"); String productionChangedNew = RuntimeDateUtilities.getProductionChangedFile(m_url, productID, seasonID, sessionToken); Assert.assertFalse(RuntimeDateUtilities.ifProductionChangedContent(productionChangedOriginal, productionChangedNew), "productionChanged.txt content was not changed"); } @Test (dependsOnMethods = "createFirstMTX", description="Create an mtx group in development under ROOT") public void createSecondMTX() throws JSONException, IOException, InterruptedException{ String dateFormat = f.setDateFormat(); String productionChangedOriginal = RuntimeDateUtilities.getProductionChangedFile(m_url, productID, seasonID, sessionToken); String mtx = FileUtils.fileToString(filePath + "feature-mutual.txt", "UTF-8", false); mtxID2 = f.addFeature(seasonID, mtx, featureID1, sessionToken); String feature1 = FileUtils.fileToString(filePath + "feature3.txt", "UTF-8", false); JSONObject json1 = new JSONObject(feature1); json1.put("stage", "PRODUCTION"); featureID3 = f.addFeature(seasonID, json1.toString(), mtxID2, sessionToken); String feature2 = FileUtils.fileToString(filePath + "feature4.txt", "UTF-8", false); JSONObject json2 = new JSONObject(feature2); json1.put("stage", "PRODUCTION"); featureID4 = f.addFeature(seasonID, json2.toString(), mtxID2, sessionToken); //check if files were changed f.setSleep(); RuntimeRestApi.DateModificationResults responseDev = RuntimeDateUtilities.getDevelopmentFileDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(responseDev.code ==200, "Runtime development feature file was not updated"); RuntimeRestApi.DateModificationResults responseProd = RuntimeDateUtilities.getProductionFileDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(responseProd.code ==200, "Runtime production feature file was not changed"); RuntimeRestApi.DateModificationResults prodChanged = RuntimeDateUtilities.getProductionChangedDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(prodChanged.code ==200, "productionChanged.txt file was not changed"); String productionChangedNew = RuntimeDateUtilities.getProductionChangedFile(m_url, productID, seasonID, sessionToken); Assert.assertFalse(RuntimeDateUtilities.ifProductionChangedContent(productionChangedOriginal, productionChangedNew), "productionChanged.txt content was not changed"); //check development file content JSONObject root = RuntimeDateUtilities.getFeaturesList(responseDev.message); JSONArray features = root.getJSONArray("features"); JSONArray mtx1 = features.getJSONObject(0).getJSONArray("features"); JSONArray mtx2 = mtx1.getJSONObject(0).getJSONArray("features"); Assert.assertTrue(mtx2.size()==1, "The inner mtx group is not under the parent feature"); } @Test (dependsOnMethods = "createSecondMTX", description="Create a sub configuration in production") public void createSubConfiguration() throws JSONException, IOException, InterruptedException{ String dateFormat = f.setDateFormat(); String productionChangedOriginal = RuntimeDateUtilities.getProductionChangedFile(m_url, productID, seasonID, sessionToken); String config = FileUtils.fileToString(filePath + "configuration_rule1.txt", "UTF-8", false); JSONObject json1 = new JSONObject(config); json1.put("stage", "PRODUCTION"); configID1 = f.addFeature(seasonID, json1.toString(), featureID2, sessionToken); Assert.assertFalse(configID1.contains("error"), "Test should pass, but instead failed: " + configID1 ); String config2 = FileUtils.fileToString(filePath + "configuration_rule2.txt", "UTF-8", false); JSONObject json2 = new JSONObject(config2); json2.put("stage", "PRODUCTION"); String configID2 = f.addFeature(seasonID, json2.toString(), configID1, sessionToken); Assert.assertFalse(configID2.contains("error"), "Test should pass, but instead failed: " + configID2 ); //check if files were changed f.setSleep(); RuntimeRestApi.DateModificationResults responseDev = RuntimeDateUtilities.getDevelopmentFileDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(responseDev.code ==200, "Runtime development feature file was not updated"); RuntimeRestApi.DateModificationResults responseProd = RuntimeDateUtilities.getProductionFileDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(responseProd.code ==200, "Runtime production feature file was not changed"); RuntimeRestApi.DateModificationResults prodChanged = RuntimeDateUtilities.getProductionChangedDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(prodChanged.code ==200, "productionChanged.txt file was not changed"); String productionChangedNew = RuntimeDateUtilities.getProductionChangedFile(m_url, productID, seasonID, sessionToken); Assert.assertFalse(RuntimeDateUtilities.ifProductionChangedContent(productionChangedOriginal, productionChangedNew), "productionChanged.txt content was not changed"); //check development file content JSONObject root = RuntimeDateUtilities.getFeaturesList(responseProd.message); JSONArray features = root.getJSONArray("features").getJSONObject(0).getJSONArray("features"); Assert.assertTrue(getNumberOfConfigurations(features, featureID2)==1, "Incorrect subconfiguration in the production file"); } @Test (dependsOnMethods = "createSubConfiguration", description="Create a new season") public void createSecondSeason() throws InterruptedException, JSONException, IOException { String dateFormat = f.setDateFormat(); String productionChangedOriginal = RuntimeDateUtilities.getProductionChangedFile(m_url, productID, seasonID, sessionToken); String season2 = FileUtils.fileToString(filePath + "season2.txt", "UTF-8", false); seasonID2 = s.addSeason(productID, season2, sessionToken); Assert.assertFalse(seasonID2.contains("error"), "Second season was not created: " + seasonID2); f.setSleep(); RuntimeRestApi.DateModificationResults responseDev = RuntimeDateUtilities.getDevelopmentFileDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(responseDev.code ==200, "Runtime development feature file was not created"); RuntimeRestApi.DateModificationResults responseProd = RuntimeDateUtilities.getDevelopmentFileDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(responseProd.code ==200, "Runtime production feature file was not created"); RuntimeRestApi.DateModificationResults prodChanged = RuntimeDateUtilities.getProductionChangedDateModification(m_url, productID, seasonID, dateFormat, sessionToken); Assert.assertTrue(prodChanged.code ==200, "productionChanged.txt file was not created"); String productionChangedNew = RuntimeDateUtilities.getProductionChangedFile(m_url, productID, seasonID, sessionToken); Assert.assertFalse(RuntimeDateUtilities.ifProductionChangedContent(productionChangedOriginal, productionChangedNew), "productionChanged.txt content was not changed"); //check development file content JSONObject root = RuntimeDateUtilities.getFeaturesList(responseDev.message); JSONArray features = root.getJSONArray("features"); JSONArray mtx1 = features.getJSONObject(0).getJSONArray("features"); JSONArray mtx2 = mtx1.getJSONObject(0).getJSONArray("features"); Assert.assertTrue(mtx2.size()==1, "The inner mtx group is not under the parent feature"); String response = f.getFeature(featureID2, sessionToken); JSONObject json = new JSONObject(response); Assert.assertTrue(getNumberOfConfigurationsByName(mtx1, json.getString("name"))==1, "Incorrect subconfiguration in the development file"); //check production file content //check development file content root = RuntimeDateUtilities.getFeaturesList(responseProd.message); features = root.getJSONArray("features"); mtx1 = features.getJSONObject(0).getJSONArray("features"); mtx2 = mtx1.getJSONObject(0).getJSONArray("features"); Assert.assertTrue(mtx2.size()==1, "The inner mtx group is not under the parent feature"); Assert.assertTrue(getNumberOfConfigurations(mtx1, featureID2)==1, "Incorrect subconfiguration in the production file"); } private int getNumberOfConfigurations(JSONArray features, String featureUniqueId) throws JSONException{ JSONArray subConfigurations = new JSONArray(); boolean updated = false; for(int i=0; i<features.size(); i++){ if (features.getJSONObject(i).getString("uniqueId").equals(featureUniqueId)) { JSONObject item = features.getJSONObject(i); JSONArray configurations = item.getJSONArray("configurationRules"); JSONObject configuration = configurations.getJSONObject(0); subConfigurations = configuration.getJSONArray("configurationRules"); updated = true; } } if (updated) return subConfigurations.size(); else return -1; } private int getNumberOfConfigurationsByName(JSONArray features, String featureName) throws JSONException{ JSONArray subConfigurations = new JSONArray(); boolean updated = false; for(int i=0; i<features.size(); i++){ if (features.getJSONObject(i).getString("name").equals(featureName)) { JSONObject item = features.getJSONObject(i); JSONArray configurations = item.getJSONArray("configurationRules"); JSONObject configuration = configurations.getJSONObject(0); subConfigurations = configuration.getJSONArray("configurationRules"); updated = true; } } if (updated) return subConfigurations.size(); else return -1; } @AfterTest private void reset(){ baseUtils.reset(productID, sessionToken); } }
54.210117
210
0.776342
d993de473db2bec54eb1d8d33bf6e4c2b275ae6b
4,352
package com.globaledgesoft.eventmanagerges; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import Config.Register; public class LoginActivity extends Activity { private static final String TAG = LoginActivity.class.getSimpleName(); private Button btn_login; private Button btn_signup; private DatabaseReference DatabaseRef; private ValueEventListener ValueRef; private EditText editText_user_name; private EditText editText_password; private String txt_userName; private String txt_password; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); btn_login = (Button)findViewById(R.id.btn_login); btn_signup = (Button)findViewById(R.id.btn_signup); DatabaseRef = FirebaseDatabase.getInstance().getReference().child("register"); editText_user_name = (EditText)findViewById(R.id.input_email); editText_password = (EditText)findViewById(R.id.input_password); progressDialog = new ProgressDialog(this); progressDialog.setMessage("Authenticationg ..."); progressDialog.setCancelable(false); btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showProgressDialog(); txt_userName = editText_user_name.getText().toString(); txt_password = editText_password.getText().toString(); ValueRef = DatabaseRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { Register register = postSnapshot.getValue(Register.class); if(txt_userName.equals(register.getEmailID().toString()) && txt_password.equals(register.getPass().toString())) { Toast.makeText(LoginActivity.this,"Login Successfull", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(LoginActivity.this,BaseActivity.class); startActivity(intent); finish(); hideProgressDialog(); } else { // Toast.makeText(LoginActivity.this,"Invalid Login Credential", Toast.LENGTH_SHORT).show(); hideProgressDialog(); } Log.d(TAG,"User Name : "+register.getEmailID() + "\n "+"Password :"+register.getPass()); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } }); btn_signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent signIntent = new Intent(LoginActivity.this,RegistrationActivity.class); startActivity(signIntent); } }); } @Override protected void onDestroy() { super.onDestroy(); DatabaseRef.removeEventListener(ValueRef); } private void showProgressDialog() { if(!progressDialog.isShowing()) { progressDialog.show(); } } private void hideProgressDialog() { if (progressDialog.isShowing()) { progressDialog.hide(); } } }
28.821192
139
0.598116
2fa1e0f72bfdcbf254e4f2995ce711261b3711ec
9,762
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.roller.weblogger.pojos; import java.io.InputStream; import java.sql.Timestamp; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.util.UUIDGenerator; import org.apache.roller.weblogger.business.MediaFileManager; import org.apache.roller.weblogger.business.WebloggerFactory; /** * Represents a media file * */ public class MediaFile { private static Log log = LogFactory.getFactory().getInstance(MediaFile.class); private String id; private String name; private String description; private String copyrightText; private Boolean isSharedForGallery = Boolean.FALSE; private long length; private int width = -1; private int height = -1; private int thumbnailHeight = -1; private int thumbnailWidth = -1; private String contentType; private String originalPath; private Timestamp dateUploaded = new Timestamp(System.currentTimeMillis()); private Timestamp lastUpdated = new Timestamp(System.currentTimeMillis()); private String creatorUserName; private Weblog weblog; private InputStream is; private MediaFileDirectory directory; private Set<MediaFileTag> tags; private FileContent content; private FileContent thumbnail; // TODO: anchor to be populated private String anchor; public MediaFile() { this.id = UUIDGenerator.generateUUID(); } /** * Name for the media file * */ public String getName() { return name; } public void setName(String name) { this.name = name; } /** * Description for media file * */ public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } /** * Copyright text for media file * */ public String getCopyrightText() { return copyrightText; } public void setCopyrightText(String copyrightText) { this.copyrightText = copyrightText; } /** * Is media file shared for gallery * */ public Boolean isSharedForGallery() { return isSharedForGallery; } public void setSharedForGallery(Boolean isSharedForGallery) { this.isSharedForGallery = isSharedForGallery; } /** * Size of the media file * */ public long getLength() { return length; } public void setLength(long length) { this.length = length; } /** * Date uploaded * */ public Timestamp getDateUploaded() { return dateUploaded; } public void setDateUploaded(Timestamp dateUploaded) { this.dateUploaded = dateUploaded; } public long getLastModified() { return lastUpdated.getTime(); } /** * Last updated timestamp * */ public Timestamp getLastUpdated() { return lastUpdated; } public void setLastUpdated(Timestamp time) { this.lastUpdated = time; } public MediaFileDirectory getDirectory() { return directory; } public void setDirectory(MediaFileDirectory dir) { this.directory = dir; } /** * Set of tags for this media file * */ public Set<MediaFileTag> getTags() { return tags; } public void setTags(Set<MediaFileTag> tags) { this.tags = tags; } /** * Content type of the media file * */ public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } /** * Database surrogate key. * * @roller.wrapPojoMethod type="simple" */ public String getId() { return id; } public String getPath() { return directory.getPath(); } /** * Returns input stream for the underlying file in the file system. * @return */ public InputStream getInputStream() { if (is != null) { return is; } else if (content != null) { return content.getInputStream(); } return null; } public void setInputStream(InputStream is) { this.is = is; } public void setContent(FileContent content) { this.content = content; } /** * Indicates whether this is an image file. * */ public boolean isImageFile() { if (this.contentType == null) { return false; } return (this.contentType.toLowerCase().startsWith( MediaFileType.IMAGE.getContentTypePrefix().toLowerCase())); } /** * Returns permalink URL for this media file resource. */ public String getPermalink() { return WebloggerFactory.getWeblogger().getUrlStrategy().getMediaFileURL( this.weblog, this.getId(), true); } /** * Returns thumbnail URL for this media file resource. * Resulting URL will be a 404 if media file is not an image. */ public String getThumbnailURL() { return WebloggerFactory.getWeblogger().getUrlStrategy().getMediaFileThumbnailURL( this.weblog, this.getId(), true); } public String getCreatorUserName() { return creatorUserName; } public void setCreatorUserName(String creatorUserName) { this.creatorUserName = creatorUserName; } public User getCreator() { try { return WebloggerFactory.getWeblogger().getUserManager().getUserByUserName(getCreatorUserName()); } catch (Exception e) { log.error("ERROR fetching user object for username: " + getCreatorUserName(), e); } return null; } /** * For old migrated files and theme resource files, orignal path of file can never change. * @return the originalPath */ public String getOriginalPath() { return originalPath; } /** * For old migrated files and theme resource files, orignal path of file can never change. * @param originalPath the originalPath to set */ public void setOriginalPath(String originalPath) { this.originalPath = originalPath; } /** * @return the weblog */ public Weblog getWeblog() { return weblog; } /** * @param weblog the weblog to set */ public void setWeblog(Weblog weblog) { this.weblog = weblog; } /** * @return the width */ public int getWidth() { return width; } /** * @param width the width to set */ public void setWidth(int width) { this.width = width; } /** * @return the height */ public int getHeight() { return height; } /** * @param height the height to set */ public void setHeight(int height) { this.height = height; } /** * Returns input stream for the underlying thumbnail file in the file system. * @return */ public InputStream getThumbnailInputStream() { if (thumbnail != null) { return thumbnail.getInputStream(); } return null; } public void setThumbnailContent(FileContent thumbnail) { this.thumbnail = thumbnail; } /** * @return the thumbnailHeight */ public int getThumbnailHeight() { if (isImageFile() && (thumbnailWidth == -1 || thumbnailHeight == -1)) { figureThumbnailSize(); } return thumbnailHeight; } /** * @return the thumbnailWidth */ public int getThumbnailWidth() { if (isImageFile() && (thumbnailWidth == -1 || thumbnailHeight == -1)) { figureThumbnailSize(); } return thumbnailWidth; } private void figureThumbnailSize() { // image determine thumbnail size int newWidth = getWidth(); int newHeight = getHeight(); if (getWidth() > getHeight()) { if (getWidth() > MediaFileManager.MAX_WIDTH) { newHeight = (int)((float)getHeight() * ((float)MediaFileManager.MAX_WIDTH / (float)getWidth())); newWidth = MediaFileManager.MAX_WIDTH; } } else { if (getHeight() > MediaFileManager.MAX_HEIGHT) { newWidth = (int)((float)getWidth() * ((float)MediaFileManager.MAX_HEIGHT / (float)getHeight())); newHeight = MediaFileManager.MAX_HEIGHT; } } thumbnailHeight = newHeight; thumbnailWidth = newWidth; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } }
24.713924
112
0.605306
ad6452d0515f79c171c45383aff7ea938e0914e2
2,619
package mod.noobulus.tetrapak.eidolon; import mod.noobulus.tetrapak.loot.ReapingLootModifier; import mod.noobulus.tetrapak.util.DamageBufferer; import mod.noobulus.tetrapak.util.tetra_definitions.IHoloDescription; import mod.noobulus.tetrapak.util.tetra_definitions.ILootModifier; import mod.noobulus.tetrapak.util.tetra_definitions.ITetraEffect; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.Enchantments; import net.minecraft.entity.CreatureAttribute; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.item.ItemEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.loot.conditions.ILootCondition; import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.entity.living.LivingDropsEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.registries.ForgeRegistries; import se.mickelus.tetra.effect.ItemEffect; import java.util.function.Function; public class ReapingEffect implements IHoloDescription, ILootModifier<ReapingLootModifier> { @SubscribeEvent public void reapingSouls(LivingDropsEvent event) { LivingEntity target = event.getEntityLiving(); DamageSource lastActive = DamageBufferer.getLastActiveDamageSource(); if (target.getMobType() == CreatureAttribute.UNDEAD) { if(event.getSource().getEntity() instanceof PlayerEntity) { int levelLooting = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.MOB_LOOTING, ((PlayerEntity)event.getSource().getEntity()).getMainHandItem()); double modifier = 2 + ((Math.random() * (levelLooting) - 0.05)); System.out.println(modifier); System.out.println(getEffectEfficiency(lastActive) * (levelLooting)); System.out.println(getEffectEfficiency(lastActive)); System.out.println(levelLooting); ItemEntity drop = new ItemEntity(target.level, target.getX(), target.getY(), target.getZ(), new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation("eidolon","soul_shard")), ((int) Math.round(modifier)))); event.getDrops().add(drop); } } } @Override public ItemEffect getEffect() { return ITetraEffect.get("reaping"); } @Override public Function<ILootCondition[], ReapingLootModifier> getModifierConstructor() { return ReapingLootModifier::new; } }
48.5
169
0.730431
88b6ed820e73f0fd09978931eaf57afa1cee2517
388
package br.com.orangetalents.proposta.bloquearcartao.repository; import br.com.orangetalents.proposta.vincularcartaoaproposta.model.Bloqueio; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface BloqueioRepository extends JpaRepository<Bloqueio, String> { Bloqueio findByCartaoId(String id); }
35.272727
77
0.850515
abcb8f47262e4de27c45f419a154340ce3601512
7,026
/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.wildfly.extension.elytron; import java.security.KeyStore; import java.security.KeyStoreException; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.registry.DelegatingResource; import org.jboss.as.controller.registry.PlaceholderResource; import org.jboss.as.controller.registry.Resource; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceController.State; import org.wildfly.extension.elytron._private.ElytronSubsystemMessages; /** * A {@link Resource} to represent a {@link KeyStoreDefinition}, the majority is actually model but child resources are a * runtime concern. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ class KeyStoreResource extends DelegatingResource { private ServiceController<KeyStore> keyStoreServiceController; KeyStoreResource(Resource delegate) { super(delegate); } /** * Set the {@link ServiceController<KeyStore>} for the {@link KeyStore} represented by this {@link Resource}. * * @param keyStoreServiceController The {@link ServiceController<KeyStore>} to obtain the {@link KeyStore} from. */ public void setKeyStoreServiceController(ServiceController<KeyStore> keyStoreServiceController) { this.keyStoreServiceController = keyStoreServiceController; } @Override public Set<String> getChildTypes() { if (containsAliases()) { return Collections.singleton(ElytronDescriptionConstants.ALIAS); } return Collections.emptySet(); } @Override public boolean hasChildren(String childType) { return ElytronDescriptionConstants.ALIAS.equals(childType) && containsAliases(); } @Override public boolean hasChild(PathElement element) { final KeyStore keyStore; try { return (ElytronDescriptionConstants.ALIAS.equals(element.getKey()) && (keyStore = getKeyStore(keyStoreServiceController)) != null && keyStore.containsAlias(element.getValue())); } catch (KeyStoreException | IllegalStateException e) { ElytronSubsystemMessages.ROOT_LOGGER.trace(e); return false; } } @Override public Resource getChild(PathElement element) { final KeyStore keyStore; try { if (ElytronDescriptionConstants.ALIAS.equals(element.getKey()) && (keyStore = getKeyStore(keyStoreServiceController)) != null && keyStore.containsAlias(element.getValue())) { return PlaceholderResource.INSTANCE; } } catch (KeyStoreException | IllegalStateException e) { ElytronSubsystemMessages.ROOT_LOGGER.trace(e); } return null; } @Override public Resource requireChild(PathElement element) { Resource resource = getChild(element); if (resource == null) { throw new NoSuchResourceException(element); } return resource; } @Override public Set<String> getChildrenNames(String childType) { final KeyStore keyStore; try { if (ElytronDescriptionConstants.ALIAS.equals(childType) && (keyStore = getKeyStore(keyStoreServiceController)) != null && keyStore.size() > 0) { Enumeration<String> aliases = keyStore.aliases(); Set<String> children = new LinkedHashSet<String>(keyStore.size()); while (aliases.hasMoreElements()) { children.add(aliases.nextElement()); } return children; } } catch (KeyStoreException | IllegalStateException e) { ElytronSubsystemMessages.ROOT_LOGGER.trace(e); } return Collections.emptySet(); } @Override public Set<ResourceEntry> getChildren(String childType) { final KeyStore keyStore; try { if (ElytronDescriptionConstants.ALIAS.equals(childType) && (keyStore = getKeyStore(keyStoreServiceController)) != null && keyStore.size() > 0) { Enumeration<String> aliases = keyStore.aliases(); Set<ResourceEntry> children = new LinkedHashSet<ResourceEntry>(keyStore.size()); while (aliases.hasMoreElements()) { children.add(new PlaceholderResource.PlaceholderResourceEntry(ElytronDescriptionConstants.ALIAS, aliases.nextElement())); } return children; } } catch (KeyStoreException | IllegalStateException e) { ElytronSubsystemMessages.ROOT_LOGGER.trace(e); } return Collections.emptySet(); } @Override public Resource navigate(PathAddress address) { return Resource.Tools.navigate(this, address); } @Override public Resource clone() { KeyStoreResource keyStoreResource = new KeyStoreResource(super.clone()); keyStoreResource.setKeyStoreServiceController(keyStoreServiceController); return keyStoreResource; } /** * Check if the {@link KeyStore} contains any aliases. * * @return {@code true} if the {@link KeyStore} is available and contains at least one entry, {@code false} otherwise. */ private boolean containsAliases() { final KeyStore keyStore; try { return ((keyStore = getKeyStore(keyStoreServiceController)) != null) && keyStore.size() > 0; } catch (KeyStoreException | IllegalStateException e) { ElytronSubsystemMessages.ROOT_LOGGER.trace(e); return false; } } /** * Get the {@link KeyStore} represented by this {@link Resource} or {@code null} if it is not currently available. * * @return The {@link KeyStore} represented by this {@link Resource} or {@code null} if it is not currently available. */ static KeyStore getKeyStore(ServiceController<KeyStore> keyStoreServiceController) { if (keyStoreServiceController == null || keyStoreServiceController.getState() != State.UP) { return null; } else { return keyStoreServiceController.getValue(); } } }
37.174603
189
0.674495
12235077fddb9bacb52e881e934b166137888565
1,575
/** * Copyright (C) 2018-2019 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.streamplatform.streamregistry.repository.avro; import org.springframework.stereotype.Component; import com.expediagroup.streamplatform.streamregistry.model.Domain; @Component public class AvroDomainConversion implements Conversion<Domain, Domain.Key, AvroDomain> { public static AvroKey avroKey(Domain.Key key) { return AvroKey .newBuilder() .setId(key.getName()) .setType(AvroKeyType.DOMAIN) .setParent(null) .build(); } public static Domain.Key modelKey(AvroKey key) { return Domain.Key .builder() .name(key.getId()) .build(); } @Override public AvroKey key(Domain.Key key) { return avroKey(key); } @Override public Class<AvroDomain> avroClass() { return AvroDomain.class; } @Override public Class<Domain> entityClass() { return Domain.class; } @Override public AvroKeyType keyType() { return AvroKeyType.DOMAIN; } }
26.25
89
0.705397
9e2918b956f8e85fc586785eda81f518a8f68d39
665
package org.apache.log4j.rewrite; import org.apache.log4j.spi.LoggingEvent; /** * This interface is implemented to provide a rewrite * strategy for RewriteAppender. RewriteAppender will * call the rewrite method with a source logging event. * The strategy may return that event, create a new event * or return null to suppress the logging request. */ public interface RewritePolicy { /** * Rewrite a logging event. * @param source a logging event that may be returned or * used to create a new logging event. * @return a logging event or null to suppress processing. */ LoggingEvent rewrite(final LoggingEvent source); }
28.913043
62
0.726316
cbcea7735273661edb45780eafb660632d83f89b
531
package joshie.progression.criteria.conditions; import joshie.progression.api.IPlayerTeam; import joshie.progression.api.criteria.ProgressionRule; import net.minecraft.entity.player.EntityPlayer; @ProgressionRule(name="isSneaking", color=0xFFD96D00, meta="isSneaking") public class ConditionSneaking extends ConditionBase { @Override public boolean isSatisfied(IPlayerTeam team) { for (EntityPlayer player: team.getTeamEntities()) { return player.isSneaking(); } return false; } }
31.235294
72
0.745763
cd7d774041a2e13881956a252d0756a1b6cbd233
12,758
package com.nuriapp.activity; import org.apache.commons.lang3.StringUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.StrictMode; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.nuriapp.activitiy.R; import com.nuriapp.data.Config; import com.nuriapp.utils.BackPressCloseSystem; public class MainActivity extends Activity { private Button loginBtn; private Button logoutBtn; private Button configBtn; private Button directBtn; // //////////////////////////////////////////////////////// public static TextView loginTextView; // //////////////////////////////////////////////////////// public static EditText loginId; public static EditText loginPassword; // //////////////////////////////////////////////////////// public static String userId; public static String userPassword; // //////////////////////////////////////////////////////// private LinearLayout idLinear; private LinearLayout passwordLinear; private LinearLayout CheckBoxLinear; // //////////////////////////////////////////////////////// private CheckBox saveIdCheckbox; private CheckBox autoLoginCheckbox; // //////////////////////////////////////////////////////// private InputMethodManager imm; // keyboard hide or show private BackPressCloseSystem backPressCloseSystem; @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if (Config.sharedPreferences.getBoolean(Config.AutoLoginEnabled, false)) { loginId.setText(Config.sharedPreferences.getString(Config.Id, "")); loginPassword.setText(Config.sharedPreferences.getString(Config.Pw, "")); saveIdCheckbox.setChecked(true); autoLoginCheckbox.setChecked(true); loginTextView.setText("사용자 : " + loginId.getText()); idLinear.setVisibility(View.GONE); passwordLinear.setVisibility(View.GONE); CheckBoxLinear.setVisibility(View.GONE); loginBtn.setVisibility(View.GONE); logoutBtn.setVisibility(View.VISIBLE); configBtn.setVisibility(View.VISIBLE); directBtn.setVisibility(View.VISIBLE); loginTextView.setVisibility(View.VISIBLE); Config.editor = Config.sharedPreferences.edit(); Config.editor.putBoolean(Config.RadioBtnState1, false); Config.editor.putBoolean(Config.RadioBtnState2, false); Config.editor.putBoolean(Config.RadioBtnState3, false); Config.editor.putBoolean(Config.RadioBtnState4, false); Config.editor.putBoolean(Config.RadioBtnState5, false); Config.editor.putBoolean(Config.RadioBtnState6, false); Config.editor.putBoolean(Config.RadioBtnState7, false); Config.editor.putBoolean(Config.RadioBtnState8, false); Config.editor.putBoolean(Config.RadioBtnState9, false); Config.editor.putBoolean(Config.RadioBtnState10, false); Config.editor.putBoolean(Config.RadioBtnState11, false); Config.editor.putBoolean(Config.RadioBtnState12, false); Config.editor.putBoolean(Config.RadioBtnState13, false); Config.editor.putBoolean(Config.RadioBtnState14, false); Config.editor.putBoolean(Config.RadioBtnState15, false); Config.editor.putBoolean(Config.RadioBtnState16, false); Config.editor.putBoolean(Config.RadioBtnState17, false); Config.editor.putBoolean(Config.RadioBtnState18, false); Config.editor.putBoolean(Config.Address, false); Config.editor.putBoolean(Config.Si, false); Config.editor.putBoolean(Config.Gu, false); Config.editor.putBoolean(Config.Dong, false); Config.editor.putBoolean(Config.Area, false); Config.editor.commit(); String buildingState = Config.sharedPreferences.getString(Config.Building, ""); if(autoLoginCheckbox.isChecked()&& buildingState != "currentBuilding"){ Config.getInstance().setBuildingID(buildingState); Intent intent = new Intent(MainActivity.this, DetailInfo.class); startActivity(intent); } } else if (Config.sharedPreferences.getBoolean(Config.SaveIdEnabled, false)) { loginId.setText(Config.sharedPreferences.getString(Config.Id, "")); saveIdCheckbox.setChecked(true); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); final AlertDialog.Builder alert = new AlertDialog.Builder( MainActivity.this); backPressCloseSystem = new BackPressCloseSystem(this); // 뒤로 가기 버튼 이벤트 Config.sharedPreferences = getSharedPreferences(Config.StatesPref, MODE_PRIVATE); // ///////////////////////////////////////////////////////// loginBtn = (Button) findViewById(R.id.LoginBtn); logoutBtn = (Button) findViewById(R.id.LogoutBtn); configBtn = (Button) findViewById(R.id.ConfigBtn); directBtn = (Button) findViewById(R.id.DirectBtn); // loginTextView = (TextView) findViewById(R.id.LoginTV); // loginId = (EditText) findViewById(R.id.LoginID); loginPassword = (EditText) findViewById(R.id.LoginPW); // idLinear = (LinearLayout) findViewById(R.id.IDLinear); passwordLinear = (LinearLayout) findViewById(R.id.PWLinear); CheckBoxLinear = (LinearLayout) findViewById(R.id.CheckBoxLinear); // saveIdCheckbox = (CheckBox) findViewById(R.id.SaveIdChk); autoLoginCheckbox = (CheckBox) findViewById(R.id.AutoLoginChk); // loginTextView.setVisibility(View.GONE); logoutBtn.setVisibility(View.INVISIBLE); configBtn.setVisibility(View.INVISIBLE); directBtn.setVisibility(View.INVISIBLE); saveIdCheckbox .setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (isChecked) { Config.editor = Config.sharedPreferences.edit(); Config.editor.putBoolean(Config.SaveIdEnabled, isChecked); Config.editor.putString(Config.Id, userId); Config.editor.commit(); } else { Config.editor = Config.sharedPreferences.edit(); Config.editor.putBoolean(Config.SaveIdEnabled, isChecked); Config.editor.putString(Config.Id, ""); Config.editor.commit(); } } }); autoLoginCheckbox .setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (isChecked) { Config.editor = Config.sharedPreferences.edit(); Config.editor.putString(Config.Id, userId); Config.editor.putString(Config.Pw, userPassword); Config.editor.putBoolean(Config.SaveIdEnabled, isChecked); Config.editor.putBoolean(Config.AutoLoginEnabled, isChecked); Config.editor.commit(); } else { Config.editor = Config.sharedPreferences.edit(); Config.editor.putString(Config.Id, ""); Config.editor.putString(Config.Pw, ""); Config.editor.putBoolean(Config.SaveIdEnabled, isChecked); Config.editor.putBoolean(Config.AutoLoginEnabled, isChecked); Config.editor.commit(); } } }); loginBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { userId = loginId.getText().toString(); userPassword = loginPassword.getText().toString(); if (userId.equals("admin") && userPassword.equals("1")) { Toast.makeText(getApplicationContext(), "Login Success", Toast.LENGTH_LONG).show(); Config.getInstance().setCurrentUserId(userId); alert.setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.setMessage("로그인 성공"); alert.show(); if (autoLoginCheckbox.isChecked()) { Config.editor = Config.sharedPreferences.edit(); Config.editor.putString(Config.Id, userId); Config.editor.putString(Config.Pw, userPassword); Config.editor.commit(); } else if (saveIdCheckbox.isChecked()) { Config.editor = Config.sharedPreferences.edit(); Config.editor.putString(Config.Id, userId); Config.editor.commit(); } loginTextView.setText("사용자 : " + userId); idLinear.setVisibility(View.GONE); passwordLinear.setVisibility(View.GONE); CheckBoxLinear.setVisibility(View.GONE); loginBtn.setVisibility(View.GONE); logoutBtn.setVisibility(View.VISIBLE); configBtn.setVisibility(View.VISIBLE); directBtn.setVisibility(View.VISIBLE); loginTextView.setVisibility(View.VISIBLE); } else if (userId.equals("")) { Toast.makeText(getApplicationContext(), "아이디를 입력하세요.", Toast.LENGTH_LONG).show(); alert.setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.setMessage("아이디를 입력하세요."); alert.show(); } else if (userPassword.equals("")) { Toast.makeText(getApplicationContext(), "비밀번호를 입력하세요.", Toast.LENGTH_LONG).show(); alert.setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.setMessage("비밀번호를 입력하세요."); alert.show(); } else if (userId != "admin" && userPassword.equals("1")) { Toast.makeText(getApplicationContext(), "존재하지 않는 아이디 입니다.", Toast.LENGTH_LONG).show(); alert.setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.setMessage("존재하지 않는 아이디입니다."); alert.show(); } else if (userId.equals("admin") && userPassword != "1") { Toast.makeText(getApplicationContext(), "비밀번호가 일치하지 않습니다.", Toast.LENGTH_LONG).show(); alert.setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.setMessage("비밀번호가 일치하지 않습니다."); alert.show(); } else { alert.setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.setMessage("잘못입력하셨습니다."); alert.show(); } imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(loginId.getWindowToken(), 0); } }); logoutBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "Logout", Toast.LENGTH_LONG).show(); logoutBtn.setVisibility(View.INVISIBLE); configBtn.setVisibility(View.INVISIBLE); directBtn.setVisibility(View.INVISIBLE); loginBtn.setVisibility(View.VISIBLE); idLinear.setVisibility(View.VISIBLE); passwordLinear.setVisibility(View.VISIBLE); CheckBoxLinear.setVisibility(View.VISIBLE); loginTextView.setVisibility(View.GONE); } }); configBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this, Settings.class); startActivity(intent); } }); directBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this, BuildingList.class); startActivity(intent); } }); } @Override public void onBackPressed() { backPressCloseSystem.onBackPressed(); } }
31.974937
82
0.679809
4384babe173bab02dab838e2ad27d557470b8f35
1,676
package zedboardking.burgerqueenapp; /** * Created by Najib Arbaoui on 15-10-07. * CLasse où tout les caractéristique des produits sont gérés. * Très simple à utliser selon le modèle MVC */ public class ModelProducts { private String productID; private String productDesc; private String productPrice; private String productNomMenu; private String productDescMenu; private String productOption; private String productNumber; public ModelProducts(String productID,String productDesc,String productPrice, String productNomMenu, String productDescMenu, String productOption, String productNumber) { this.productID = productID; this.productDesc = productDesc; this.productPrice = productPrice; this.productNomMenu = productNomMenu; this.productDescMenu = productDescMenu; this.productOption = productOption; this.productNumber = productNumber; } public String getProductID() { return productID; } public String getProductDesc() { return productDesc; } public String getProductPrice() { return productPrice; } public String getproductNomMenu(){ return productNomMenu; } public String getProductDescMenu(){ return productDescMenu; } public String getProductOption(){ return productOption; } public String setProductOption(String option){ return productOption = option; } public String getProductNumber(String number){ return productNumber = number; } public String getProductNumber(){ return productNumber; } }
22.346667
172
0.685561
801284123dbfad980d6a41ca248a2b7cc1105579
1,097
package it.unive.lisa.symbolic.types; import it.unive.lisa.cfg.type.Type; import it.unive.lisa.cfg.type.Untyped; /** * An internal implementation of the {@link it.unive.lisa.cfg.type.StringType} * interface that can be used by domains that need a concrete instance of that * interface. * * @author <a href="mailto:luca.negrini@unive.it">Luca Negrini</a> */ public class StringType implements it.unive.lisa.cfg.type.StringType { /** * The singleton instance of this class. */ public static final StringType INSTANCE = new StringType(); private StringType() { } @Override public boolean canBeAssignedTo(Type other) { return other.isStringType() || other.isUntyped(); } @Override public Type commonSupertype(Type other) { return other.isStringType() ? this : Untyped.INSTANCE; } @Override public String toString() { return "string"; } @Override public boolean equals(Object other) { return other instanceof it.unive.lisa.cfg.type.StringType; } @Override public int hashCode() { return it.unive.lisa.cfg.type.StringType.class.getName().hashCode(); } }
22.854167
78
0.725615
010aae37971c9396dbde1d5858e3c6100f93a87f
2,808
/* * Copyright 2020 richard linsdale. * * 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 uk.theretiredprogrammer.racetrainingsketch.strategy; import java.io.IOException; import org.junit.jupiter.api.Test; /** * * @author Richard Linsdale (richard at theretiredprogrammer.uk) */ public class OffwindtoOffwindPortRoundingStrategyTest extends SailingStrategyTest { @Test public void layline1() throws IOException { System.out.println("layline 1"); Decision decision = makeDecision("/offwindtooffwind-starboardtack-portrounding.json", () -> setboatlocationvalue("location", 23, 53)); assertSAILON(decision); } @Test public void layline2() throws IOException { System.out.println("layline 2"); Decision decision = makeDecision("/offwindtooffwind-starboardtack-portrounding.json", () -> setboatlocationvalue("location", 21, 53)); assertSAILON(decision); } @Test public void layline3() throws IOException { System.out.println("layline 3"); Decision decision = makeDecision("/offwindtooffwind-starboardtack-portrounding.json", () -> setboatlocationvalue("location", 20, 53)); assertMARKROUNDING(decision, 180, false); } @Test public void layline4() throws IOException { System.out.println("layline 4"); Decision decision = makeDecision("/offwindtooffwind-starboardtack-portrounding.json", () -> setboatlocationvalue("location", 19.8, 52.8)); assertMARKROUNDING(decision, 180, false); } @Test public void layline5() throws IOException { System.out.println("layline 5"); Decision decision = makeDecision("/offwindtooffwind-starboardtack-portrounding.json", () -> setwindfrom(45), () -> setboatlocationvalue("location", 21, 53)); assertSAILON(decision); } @Test public void layline6() throws IOException { System.out.println("layline 6"); Decision decision = makeDecision("/offwindtooffwind-starboardtack-portrounding.json", () -> setwindfrom(45), () -> setboatlocationvalue("location", 20, 53)); assertMARKROUNDING(decision, 180, false); } }
36.467532
93
0.668447
18e44d6d58591f5b83b78ff074701235ad575ca7
891
package org.prosolo.web.util.pagination; public class PaginationLink { private int page; private String linkOutput; private boolean selected; private boolean isLink; public PaginationLink() { } public PaginationLink(int page, String linkOutput, boolean selected, boolean isLink) { this.page = page; this.linkOutput = linkOutput; this.selected = selected; this.isLink = isLink; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public String getLinkOutput() { return linkOutput; } public void setLinkOutput(String linkOutput) { this.linkOutput = linkOutput; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } public boolean isLink() { return isLink; } public void setLink(boolean isLink) { this.isLink = isLink; } }
16.5
87
0.714927
4433dd00d4bd7e774e3d74484235280aeb75dd83
2,859
package com.vechain.thorclient.utils; import com.alibaba.fastjson.JSON; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import com.mashape.unirest.request.GetRequest; import com.mashape.unirest.request.body.RequestBodyEntity; import com.vechain.thorclient.base.BaseTest; import com.vechain.thorclient.clients.BlockClient; import com.vechain.thorclient.clients.BlockchainClient; import com.vechain.thorclient.core.model.blockchain.RawClause; import com.vechain.thorclient.core.model.clients.RawTransaction; import com.vechain.thorclient.utils.BytesUtils; import com.vechain.thorclient.utils.CryptoUtils; import com.vechain.thorclient.utils.RawTransactionBuilder; import org.json.JSONObject; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * {"version":3,"id":"FEE947A3-785B-4839-A782-998E8F471DCC","crypto":{"ciphertext":"3b331bd66571d9e1ff4b7bbd10f68b0089301e0aae3c3507e44ce73588f049b4","cipherparams":{"iv":"d3f26875c39594d3c5fcb8c689e4a9a7"},"kdf":"scrypt","kdfparams":{"r":8,"p":1,"n":262144,"dklen":32,"salt":"ac901f3f5160c786ea0f5e760791e80f9fb4ddb7af2af69a697bcb61bc4dda13"},"mac":"c1444e90194d1d1357aa6d8d4f5754339c803c65867ef058e542a7118f219ca8","cipher":"aes-128-ctr"},"address":"c71adc46c5891a8963ea5a5eeaf578e0a2959779"} */ @RunWith(JUnit4.class) public class RawTransactionBuilderTest extends BaseTest { @Test public void testUpdateBuild() throws IOException { RawTransactionBuilder builder = new RawTransactionBuilder(); byte chainTag = BlockchainClient.getChainTag(); int n = chainTag & 0xFF; logger.info("Current chainTag:" + n); builder.update(Byte.valueOf(chainTag), "chainTag"); byte[] expirationBytes = BytesUtils.longToBytes(720); builder.update(expirationBytes, "expiration"); byte[] blockRef = BlockClient.getBlock(null).blockRef().toByteArray(); builder.update(blockRef, "blockRef"); byte[] nonce = CryptoUtils.generateTxNonce(); builder.update(nonce, "nonce"); byte[] gas = BytesUtils.longToBytes(21000); builder.update(gas, "gas"); RawClause clauses[] = new RawClause[1]; clauses[0] = new RawClause(); clauses[0].setTo(BytesUtils.toByteArray("0x42191bd624aBffFb1b65e92F1E51EB16f4d2A3Ce")); clauses[0].setValue(BytesUtils.defaultDecimalStringToByteArray("42.42")); builder.update(clauses); RawTransaction rawTxn = builder.build(); byte tag = rawTxn.getChainTag(); Assert.assertEquals("ChainTag is not equal.", chainTag, tag); } }
41.434783
494
0.747114
bc990b482fb0c7efe98b6eeaabefccb0c5bae9d5
1,129
package org.epnoi.storage.system.column.repository; import org.epnoi.storage.system.column.domain.SourceColumn; import org.epnoi.storage.system.column.domain.SourceColumn; import org.springframework.data.cassandra.repository.Query; /** * Created by cbadenes on 21/12/15. */ public interface SourceColumnRepository extends BaseColumnRepository<SourceColumn> { //Future Version of Spring-Data-Cassandra will implements native queries @Query("select * from sources where uri = ?0") Iterable<SourceColumn> findByUri(String uri); @Query("select * from sources where creationTime = ?0") Iterable<SourceColumn> findByCreationTime(String creationTime); @Query("select * from sources where name = ?0") Iterable<SourceColumn> findByName(String name); @Query("select * from sources where description = ?0") Iterable<SourceColumn> findByDescription(String description); @Query("select * from sources where url = ?0") Iterable<SourceColumn> findByUrl(String url); @Query("select * from sources where protocol = ?0") Iterable<SourceColumn> findByProtocol(String protocol); }
34.212121
84
0.746678
c3ef9d9194b6b31bf5774d65f8b276a4feafcf01
3,663
/* * Snow-Globe * * Copyright 2017 The Kroger Co. * * 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.kroger.oss.snowGlobe.call; import com.kroger.oss.snowGlobe.NginxRpBuilder; import java.net.URI; import java.util.HashMap; import java.util.Map; public class TestRequest { private Map<String, String> headers = new HashMap<>(); private String url; private String method; private String body; private NginxRpBuilder reverseProxy; private String userAgent; private String healthCheckUrl; public TestRequest(String method, String url) { this.method = method; this.url = url; } public static TestRequest getRequest(String url) { return new TestRequest("GET", url); } public static TestRequest postRequest(String url) { return new TestRequest("POST", url); } public static TestRequest putRequest(String url) { return new TestRequest("PUT", url); } public static TestRequest deleteRequest(String url) { return new TestRequest("DELETE", url); } public static TestRequest headRequest(String url) { return new TestRequest("HEAD", url); } public TestRequest withHeader(String key, String value) { headers.put(key, value); return this; } public TestRequest withBody(String body) { this.body = body; return this; } public TestRequest withUserAgent(String userAgent) { this.userAgent = userAgent; return this; } public String getUserAgent() { return this.userAgent; } public boolean hasUserAgent() { return getUserAgent() != null && getUserAgent().length() > 0; } public Map<String, String> getHeaders() { return headers; } public String getUrl() { try { URI o = new URI(this.url); URI injected = new URI("http", null, o.getHost(), reverseProxy.getPortForUrl(this.url), o.getPath(), o.getQuery(), o.getFragment()); return injected.toString(); } catch (Exception e) { throw new RuntimeException(e); } } public String getHealthCheckUrl() { if (null != this.healthCheckUrl) { try { URI o = new URI(this.url + this.healthCheckUrl); URI injected = new URI("http", null, o.getHost(), reverseProxy.getPortForUrl(this.url), o.getPath(), o.getQuery(), o.getFragment()); return injected.toString(); } catch (Exception e) { throw new RuntimeException(e); } } return this.healthCheckUrl; } public String getPrettyUrl() { return url; } public String getMethod() { return method; } public String getBody() { return body; } public TestRequest to(NginxRpBuilder reverseProxy) { this.reverseProxy = reverseProxy; return this; } public TestRequest withHealthCheck(String healthCheckUrl) { this.healthCheckUrl = healthCheckUrl; return this; } }
26.737226
103
0.623533
0b9ce5c5cf8f4d554587100a09869afb9d68856d
7,680
/** * Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com). * All rights reserved. Use is subject to license terms and conditions. */ package au.csiro.ontology.importer.rf2; /** * @author Alejandro Metke * */ public class RelationshipRow implements Comparable<RelationshipRow> { private final String id; private final String effectiveTime; private final String active; private final String moduleId; private final String sourceId; private final String destinationId; private final String relationshipGroup; private final String typeId; private final String characteristicTypeId; private final String modifierId; /** * Creates a new RelationshipRow. * * @param id * @param effectiveTime * @param active * @param moduleId * @param sourceId * @param destinationId * @param relationshipGroup * @param typeId * @param characteristicTypeId * @param modifierId */ public RelationshipRow(String id, String effectiveTime, String active, String moduleId, String sourceId, String destinationId, String relationshipGroup, String typeId, String characteristicTypeId, String modifierId) { super(); this.id = id; this.effectiveTime = effectiveTime; this.active = active; this.moduleId = moduleId; this.sourceId = sourceId; this.destinationId = destinationId; this.relationshipGroup = relationshipGroup; this.typeId = typeId; this.characteristicTypeId = characteristicTypeId; this.modifierId = modifierId; } /** * @return the id */ public String getId() { return id; } /** * @return the effectiveTime */ public String getEffectiveTime() { return effectiveTime; } /** * @return the active */ public String getActive() { return active; } /** * @return the moduleId */ public String getModuleId() { return moduleId; } /** * @return the sourceId */ public String getSourceId() { return sourceId; } /** * @return the destinationId */ public String getDestinationId() { return destinationId; } /** * @return the relationshipGroup */ public String getRelationshipGroup() { return relationshipGroup; } /** * @return the typeId */ public String getTypeId() { return typeId; } /** * @return the characteristicTypeId */ public String getCharacteristicTypeId() { return characteristicTypeId; } /** * @return the modifierId */ public String getModifierId() { return modifierId; } @Override public String toString() { return id + ", " + effectiveTime + ", " + active + ", " + moduleId + ", " + sourceId + ", " + destinationId + ", " + relationshipGroup + ", " + typeId + ", " + characteristicTypeId + ", " + modifierId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((active == null) ? 0 : active.hashCode()); result = prime * result + ((characteristicTypeId == null) ? 0 : characteristicTypeId .hashCode()); result = prime * result + ((destinationId == null) ? 0 : destinationId.hashCode()); result = prime * result + ((effectiveTime == null) ? 0 : effectiveTime.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((modifierId == null) ? 0 : modifierId.hashCode()); result = prime * result + ((moduleId == null) ? 0 : moduleId.hashCode()); result = prime * result + ((relationshipGroup == null) ? 0 : relationshipGroup .hashCode()); result = prime * result + ((sourceId == null) ? 0 : sourceId.hashCode()); result = prime * result + ((typeId == null) ? 0 : typeId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RelationshipRow other = (RelationshipRow) obj; if (active == null) { if (other.active != null) return false; } else if (!active.equals(other.active)) return false; if (characteristicTypeId == null) { if (other.characteristicTypeId != null) return false; } else if (!characteristicTypeId.equals(other.characteristicTypeId)) return false; if (destinationId == null) { if (other.destinationId != null) return false; } else if (!destinationId.equals(other.destinationId)) return false; if (effectiveTime == null) { if (other.effectiveTime != null) return false; } else if (!effectiveTime.equals(other.effectiveTime)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (modifierId == null) { if (other.modifierId != null) return false; } else if (!modifierId.equals(other.modifierId)) return false; if (moduleId == null) { if (other.moduleId != null) return false; } else if (!moduleId.equals(other.moduleId)) return false; if (relationshipGroup == null) { if (other.relationshipGroup != null) return false; } else if (!relationshipGroup.equals(other.relationshipGroup)) return false; if (sourceId == null) { if (other.sourceId != null) return false; } else if (!sourceId.equals(other.sourceId)) return false; if (typeId == null) { if (other.typeId != null) return false; } else if (!typeId.equals(other.typeId)) return false; return true; } public int compareTo(RelationshipRow other) { if(this.equals(other)) return 0; else { int res = effectiveTime.compareTo(other.effectiveTime); if(res != 0) return res; res = moduleId.compareTo(other.moduleId); if(res != 0) return res; res = id.compareTo(other.id); if(res != 0) return res; res = active.compareTo(other.active); if(res != 0) return res; res = sourceId.compareTo(other.sourceId); if(res != 0) return res; res = destinationId.compareTo(other.destinationId); if(res != 0) return res; res = relationshipGroup.compareTo(other.relationshipGroup); if(res != 0) return res; res = typeId.compareTo(other.typeId); if(res != 0) return res; res = characteristicTypeId.compareTo(other.characteristicTypeId); if(res != 0) return res; res = modifierId.compareTo(other.modifierId); assert(res != 0); return res; } } }
30.117647
77
0.542188
5292304548e0fc1f6daf03b9ffa5a4bbe1da2cd6
3,381
package com.alipay.api.domain; import java.util.Date; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 口碑订单商品凭证模型 * * @author auto create * @since 1.0, 2018-03-08 11:39:18 */ public class KbOrderVoucherModel extends AlipayObject { private static final long serialVersionUID = 6621884529984186886L; /** * 商品凭证过期时间 */ @ApiField("expire_date") private Date expireDate; /** * 商品凭证核销/退款对应的资金流水号 */ @ApiField("funds_voucher_no") private String fundsVoucherNo; /** * 商品ID */ @ApiField("item_id") private String itemId; /** * 退款理由,由消费者选择或填写内容,系统退款可以为空。 */ @ApiField("refund_reason") private String refundReason; /** * 退款类型,ROLE_DAEMON(超期未使用),ROLE_USER(消费者主动); */ @ApiField("refund_type") private String refundType; /** * 商品凭证核销门店ID,核销后会存在该字段 */ @ApiField("shop_id") private String shopId; /** * 状态 */ @ApiField("status") private String status; /** * 商品凭证核销门店外部ID */ @ApiField("store_id") private String storeId; /** * 凭证剩余可核销次数(次卡场景) */ @ApiField("ticket_effect_count") private String ticketEffectCount; /** * 凭证已退款次数(次卡场景) */ @ApiField("ticket_refunded_count") private String ticketRefundedCount; /** * 凭证已使用次数(次卡场景) */ @ApiField("ticket_used_count") private String ticketUsedCount; /** * 商品凭证ID */ @ApiField("voucher_id") private String voucherId; public Date getExpireDate() { return this.expireDate; } public void setExpireDate(Date expireDate) { this.expireDate = expireDate; } public String getFundsVoucherNo() { return this.fundsVoucherNo; } public void setFundsVoucherNo(String fundsVoucherNo) { this.fundsVoucherNo = fundsVoucherNo; } public String getItemId() { return this.itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public String getRefundReason() { return this.refundReason; } public void setRefundReason(String refundReason) { this.refundReason = refundReason; } public String getRefundType() { return this.refundType; } public void setRefundType(String refundType) { this.refundType = refundType; } public String getShopId() { return this.shopId; } public void setShopId(String shopId) { this.shopId = shopId; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public String getStoreId() { return this.storeId; } public void setStoreId(String storeId) { this.storeId = storeId; } public String getTicketEffectCount() { return this.ticketEffectCount; } public void setTicketEffectCount(String ticketEffectCount) { this.ticketEffectCount = ticketEffectCount; } public String getTicketRefundedCount() { return this.ticketRefundedCount; } public void setTicketRefundedCount(String ticketRefundedCount) { this.ticketRefundedCount = ticketRefundedCount; } public String getTicketUsedCount() { return this.ticketUsedCount; } public void setTicketUsedCount(String ticketUsedCount) { this.ticketUsedCount = ticketUsedCount; } public String getVoucherId() { return this.voucherId; } public void setVoucherId(String voucherId) { this.voucherId = voucherId; } }
19.32
68
0.683821
fcf2ed5e1bbdc169d2fa1fe51fac5b4df92ab66b
2,117
/* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.apple.xcode.xcodeproj; import com.facebook.buck.apple.xcode.XcodeprojSerializer; import com.google.common.base.Preconditions; public class PBXCopyFilesBuildPhase extends PBXBuildPhase { /** * The prefix path, this does not use SourceTreePath and build variables but rather some sort of * enum. */ public enum Destination { ABSOLUTE(0), WRAPPER(1), EXECUTABLES(6), RESOURCES(7), FRAMEWORKS(10), SHARED_FRAMEWORKS(11), SHARED_SUPPORT(12), PLUGINS(13), JAVA_RESOURCES(15), PRODUCTS(16), ; private int value; public int getValue() { return value; } private Destination(int value) { this.value = value; } } /** * Base path of destination folder. */ private Destination dstSubfolderSpec; /** * Subdirectory under the destination folder. */ private String path; public PBXCopyFilesBuildPhase(Destination dstSubfolderSpec, String path) { this.dstSubfolderSpec = Preconditions.checkNotNull(dstSubfolderSpec); this.path = Preconditions.checkNotNull(path); } public Destination getDstSubfolderSpec() { return dstSubfolderSpec; } public String getPath() { return path; } @Override public String isa() { return "PBXCopyFilesBuildPhase"; } @Override public void serializeInto(XcodeprojSerializer s) { super.serializeInto(s); s.addField("dstSubfolderSpec", dstSubfolderSpec.getValue()); s.addField("dstPath", path); } }
24.616279
98
0.703826
d4560c22a92e90182eb1c47cb6cd816cba56aab1
673
package net.covers1624.wt.api.workspace; import net.covers1624.wt.api.dependency.Dependency; import net.covers1624.wt.api.dependency.DependencyScope; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by covers1624 on 3/9/19. */ public interface WorkspaceModule { Path getPath(); String getName(); boolean getIsGroup(); //java -> paths //scala -> paths //groovy -> paths Map<String, List<Path>> getSourceMap(); //Resources. List<Path> getResources(); List<Path> getExcludes(); Path getOutput(); Map<DependencyScope, Set<Dependency>> getDependencies(); }
18.189189
60
0.686478
836b354962db8e6a2dec84a5ba84defa746cc96e
411
package com.change.hippo.utils.kafka; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * User: change.long * Date: 2017/12/8 * Time: 下午2:51 */ public class DemoConsumer implements MessageConsumer { private static final Logger LOGGER = LoggerFactory.getLogger(DemoConsumer.class); @Override public void consume(String payload) { LOGGER.info("consumer" + payload); } }
20.55
85
0.710462
ba4788fee469e7caf14f6a85d510bf88074cf48c
1,385
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import io.mantisrx.common.WorkerPorts; import io.mantisrx.runtime.MachineDefinition; import lombok.Value; /** * Data structure used at the time of registration by the task executor. * Different fields help identify the task executor in different dimensions. */ @Value public class TaskExecutorRegistration { TaskExecutorID taskExecutorID; ClusterID clusterID; // RPC address that's used to talk to the task executor String taskExecutorAddress; // host name of the task executor String hostname; // ports used by the task executor for various purposes. WorkerPorts workerPorts; // machine information identifies the cpu/mem/disk/network resources of the task executor. MachineDefinition machineDefinition; }
31.477273
92
0.764621
bed79b2beb541eea11a0873015dd4b1fe547f0b1
1,624
package cn.codingblock.ipcclient; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import cn.codingblock.ipcclient.aidl.ContactMangerActivity; import cn.codingblock.ipcclient.messenger.MessengerActivity; import cn.codingblock.ipcclient.socket.TCPClientActivity; import cn.codingblock.libutils.view.ViewUtils; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewUtils.findAndOnClick(this, R.id.btn_messenger_activity, mOnClickListener); ViewUtils.findAndOnClick(this, R.id.btn_tcp_client_activity, mOnClickListener); ViewUtils.findAndOnClick(this, R.id.btn_test_aidl, mOnClickListener); } private View.OnClickListener mOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_messenger_activity: startActivity(new Intent(getApplicationContext(), MessengerActivity.class)); break; case R.id.btn_tcp_client_activity: startActivity(new Intent(getApplicationContext(), TCPClientActivity.class)); break; case R.id.btn_test_aidl: startActivity(new Intent(getApplicationContext(), ContactMangerActivity.class)); break; } } }; }
38.666667
100
0.690887
b4b52ac09fa9931413ecde631660ce3874c0fe02
5,748
package eu.ensup.myresto.service; import java.util.ArrayList; import java.util.List; import eu.ensup.myresto.business.User; import eu.ensup.myresto.dao.ExceptionDao; import eu.ensup.myresto.dao.UserDao; import eu.ensup.myresto.dto.UserDTO; import eu.ensup.myresto.mapper.UserMapper; /** * The type Service person. */ public class UserService implements IService<UserDTO> { private UserDao dao = null; /** * The Class name. */ // nom de la classe String className = getClass().getName(); /** * Instantiates a new Service person. */ public UserService() { this.dao = new UserDao(); } /** * Instantiates a new Person service. * * @param idao the idao */ public UserService(UserDao idao) { this.dao = idao; } @Override public int create(UserDTO userDto) throws ExceptionService { String methodName = new Object(){}.getClass().getEnclosingMethod().getName(); // Checker le role et faire une instance et l'envoyer dans le DAO int check = 0; User user = UserMapper.dtoToBusiness(userDto); try { check = this.dao.create(user); }catch (ExceptionDao exceptionDao){ serviceLogger.logServiceError(className, methodName,"Un problème est survenue lors de l'appel à cette méthode."); throw new ExceptionService(exceptionDao.getMessage()); } return check; } // Update Person @Override public int update(UserDTO userDto) throws ExceptionService { String methodName = new Object(){}.getClass().getEnclosingMethod().getName(); int res = 0; User user = UserMapper.dtoToBusiness(userDto); try{ res = this.dao.update(user); }catch (ExceptionDao exceptionDao){ serviceLogger.logServiceError(className, methodName,"Un problème est survenue lors de l'appel à cette méthode."); throw new ExceptionService(exceptionDao.getMessage()); } return res; } @Override public int delete(UserDTO userDto) throws ExceptionService { String methodName = new Object(){}.getClass().getEnclosingMethod().getName(); int res = 0; User user = UserMapper.dtoToBusiness(userDto); try{ res = this.dao.delete(user); }catch (ExceptionDao exceptionDao){ serviceLogger.logServiceError(className, methodName,"Un problème est survenue lors de l'appel à cette méthode."); throw new ExceptionService(exceptionDao.getMessage()); } return res; } public int delete(String email) throws ExceptionService { String methodName = new Object(){}.getClass().getEnclosingMethod().getName(); int res = 0; try{ res = this.dao.delete(email); }catch (ExceptionDao exceptionDao){ serviceLogger.logServiceError(className, methodName,"Un problème est survenue lors de l'appel à cette méthode."); throw new ExceptionService(exceptionDao.getMessage()); } return res; } @Override public int delete(int index) throws ExceptionService { String methodName = new Object(){}.getClass().getEnclosingMethod().getName(); int res = 0; try{ res = this.dao.delete(index); }catch (ExceptionDao exceptionDao){ serviceLogger.logServiceError(className, methodName,"Un problème est survenue lors de l'appel à cette méthode."); throw new ExceptionService(exceptionDao.getMessage()); } return res; } @Override public UserDTO get(int index) throws ExceptionService { String methodName = new Object(){}.getClass().getEnclosingMethod().getName(); try{ User user = this.dao.get(index); UserDTO userDto = null; if(user != null) userDto = UserMapper.businessToDto(user); return userDto; }catch (ExceptionDao exceptionDao){ serviceLogger.logServiceError(className, methodName,"Un problème est survenue lors de l'appel à cette méthode."); throw new ExceptionService(exceptionDao.getMessage()); } } /** * Get person dto. * * @param email the email * @return the person dto * @throws ExceptionService the exception service */ public UserDTO get(String email) throws ExceptionService { String methodName = new Object(){}.getClass().getEnclosingMethod().getName(); try{ User user = this.dao.get(email); UserDTO personDto = null; personDto = UserMapper.businessToDto(user); return personDto; }catch (ExceptionDao exceptionDao){ serviceLogger.logServiceError(className, methodName,"Un problème est survenue lors de l'appel à cette méthode."); throw new ExceptionService(exceptionDao.getMessage()); } } @Override public List<UserDTO> getAll() throws ExceptionService{ String methodName = new Object(){}.getClass().getEnclosingMethod().getName(); List<UserDTO> userDTOList = new ArrayList<>(); try { List<User> listAllPerson = this.dao.getAll(); for(User user : listAllPerson) { UserDTO userDto = null; userDto = UserMapper.businessToDto(user); userDTOList.add(userDto); } return userDTOList; }catch (ExceptionDao exceptionDao){ serviceLogger.logServiceError(className, methodName,"Un problème est survenue lors de l'appel à cette méthode."); throw new ExceptionService(exceptionDao.getMessage()); } } }
33.418605
125
0.628914
22193623260e2b83abb31ddf489b8566bac44092
3,329
package uk.abdoul.co.fitit; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.support.v7.app.ActionBar; import android.view.MenuItem; import java.util.List; public class SettingsActivity2 extends AppCompatPreferenceActivity { /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private static boolean isLargeTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ private void setupActionBar() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { // Show the Up button in the action bar. actionBar.setDisplayHomeAsUpEnabled(true); } } /** * {@inheritDoc} */ @Override public boolean onIsMultiPane() { return isLargeTablet(this); } /** * {@inheritDoc} */ @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onBuildHeaders(List<PreferenceActivity.Header> target) { loadHeadersFromResource(R.xml.pref_headers, target); } /** * This method stops fragment injection in malicious applications. * Make sure to deny any unknown fragments here. */ protected boolean isValidFragment(String fragmentName) { return PreferenceFragment.class.getName().equals(fragmentName) || GeneralPreferenceFragment.class.getName().equals(fragmentName); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class GeneralPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int preferenceFile_toLoad=-1; String settings = getArguments().getString("settings"); if ("prefs_general".equalsIgnoreCase(settings)) { // Load the preferences from an XML resource preferenceFile_toLoad= R.xml.pref_general; }else if ("prefs_notification".equalsIgnoreCase(settings)) { // Load the preferences from an XML resource preferenceFile_toLoad=R.xml.pref_notification; }else if ("prefs_sync".equals(settings)) { // Load the preferences from an XML resource preferenceFile_toLoad=R.xml.pref_data_sync; } addPreferencesFromResource(preferenceFile_toLoad); } } }
29.723214
97
0.658156
bd7067d4fb89cab69b48d159a7eba18b7766303b
4,601
package com.bt.openlink.smack.iq; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertThat; import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.provider.ProviderManager; import org.jivesoftware.smack.util.PacketParserUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import com.bt.openlink.CoreFixtures; import com.bt.openlink.GetInterestsFixtures; import com.bt.openlink.OpenlinkXmppNamespace; import com.bt.openlink.smack.Fixtures; @SuppressWarnings("ConstantConditions") public class GetInterestsRequestTest { @Rule public final ExpectedException expectedException = ExpectedException.none(); @BeforeClass public static void setUpClass() throws Exception { ProviderManager.addIQProvider("command", OpenlinkXmppNamespace.XMPP_COMMANDS.uri(), new OpenlinkIQProvider()); } @AfterClass public static void tearDownClass() throws Exception { ProviderManager.removeIQProvider("command", OpenlinkXmppNamespace.XMPP_COMMANDS.uri()); } @Test public void canCreateAStanza() throws Exception { final GetInterestsRequest request = GetInterestsRequest.Builder.start() .setId(CoreFixtures.STANZA_ID) .setTo(Fixtures.TO_JID) .setFrom(Fixtures.FROM_JID) .setProfileId(CoreFixtures.PROFILE_ID) .build(); assertThat(request.getStanzaId(), is(CoreFixtures.STANZA_ID)); assertThat(request.getTo(), is(Fixtures.TO_JID)); assertThat(request.getFrom(), is(Fixtures.FROM_JID)); assertThat(request.getProfileId().get(), is(CoreFixtures.PROFILE_ID)); } @Test public void cannotCreateAStanzaWithoutAProfileId() throws Exception { expectedException.expect(IllegalStateException.class); expectedException.expectMessage("The get-interests request 'profileId' has not been set"); GetInterestsRequest.Builder.start() .setTo(Fixtures.TO_JID) .setFrom(Fixtures.FROM_JID) .build(); } @Test public void willGenerateAnXmppStanza() throws Exception { final GetInterestsRequest request = GetInterestsRequest.Builder.start() .setId(CoreFixtures.STANZA_ID) .setTo(Fixtures.TO_JID) .setFrom(Fixtures.FROM_JID) .setProfileId(CoreFixtures.PROFILE_ID) .build(); assertThat(request.toXML().toString(), isIdenticalTo(GetInterestsFixtures.GET_INTERESTS_REQUEST).ignoreWhitespace()); } @Test public void willParseAnXmppStanza() throws Exception { final GetInterestsRequest request = PacketParserUtils.parseStanza(GetInterestsFixtures.GET_INTERESTS_REQUEST); assertThat(request.getStanzaId(), is(CoreFixtures.STANZA_ID)); assertThat(request.getTo(), is(Fixtures.TO_JID)); assertThat(request.getFrom(), is(Fixtures.FROM_JID)); assertThat(request.getType(), is(IQ.Type.set)); assertThat(request.getProfileId().get(), is(CoreFixtures.PROFILE_ID)); assertThat(request.getParseErrors(), is(empty())); } @Test public void willReturnParsingErrors() throws Exception { final GetInterestsRequest request = PacketParserUtils.parseStanza(GetInterestsFixtures.GET_INTERESTS_REQUEST_WITH_BAD_VALUES); // Note; it's not possible to validate the core elements of Smack packets as the to/from/id/type are not // set until after the parsing is complete. assertThat(request.getParseErrors(), contains( // "Invalid stanza; missing 'to' attribute is mandatory", // "Invalid stanza; missing 'from' attribute is mandatory", // "Invalid stanza; missing 'id' attribute is mandatory", // "Invalid stanza; missing or incorrect 'type' attribute", "Invalid get-interests request stanza; missing 'profile'")); } @Test public void willGenerateAStanzaEvenWithParsingErrors() throws Exception { final GetInterestsRequest request = PacketParserUtils.parseStanza(GetInterestsFixtures.GET_INTERESTS_REQUEST_WITH_BAD_VALUES); assertThat(request.toXML().toString(), isIdenticalTo(GetInterestsFixtures.GET_INTERESTS_REQUEST_WITH_BAD_VALUES).ignoreWhitespace()); } }
39.663793
141
0.711802
e36bb18dfc33c774c9eecc7a48dbe241d371025b
3,632
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package DECL|package|org.apache.hadoop.hdfs.net package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hdfs operator|. name|net package|; end_package begin_import import|import name|java operator|. name|io operator|. name|Closeable import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|classification operator|. name|InterfaceAudience import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|net operator|. name|SocketTimeoutException import|; end_import begin_interface annotation|@ name|InterfaceAudience operator|. name|Private DECL|interface|PeerServer specifier|public interface|interface name|PeerServer extends|extends name|Closeable block|{ comment|/** * Set the receive buffer size of the PeerServer. * * @param size The receive buffer size. */ DECL|method|setReceiveBufferSize (int size) specifier|public name|void name|setReceiveBufferSize parameter_list|( name|int name|size parameter_list|) throws|throws name|IOException function_decl|; comment|/** * Get the receive buffer size of the PeerServer. * * @return The receive buffer size. */ DECL|method|getReceiveBufferSize () name|int name|getReceiveBufferSize parameter_list|() throws|throws name|IOException function_decl|; comment|/** * Listens for a connection to be made to this server and accepts * it. The method blocks until a connection is made. * * @exception IOException if an I/O error occurs when waiting for a * connection. * @exception SecurityException if a security manager exists and its *<code>checkAccept</code> method doesn't allow the operation. * @exception SocketTimeoutException if a timeout was previously set and * the timeout has been reached. */ DECL|method|accept () specifier|public name|Peer name|accept parameter_list|() throws|throws name|IOException throws|, name|SocketTimeoutException function_decl|; comment|/** * @return A string representation of the address we're * listening on. */ DECL|method|getListeningString () specifier|public name|String name|getListeningString parameter_list|() function_decl|; comment|/** * Free the resources associated with this peer server. * This normally includes sockets, etc. * * @throws IOException If there is an error closing the PeerServer */ DECL|method|close () specifier|public name|void name|close parameter_list|() throws|throws name|IOException function_decl|; block|} end_interface end_unit
28.155039
814
0.754956
fb65f451e7bf9bc55d78506ba5a5e4a3c325d483
4,073
/* * Copyright 2021 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jmix.dataimport.extractor.entity.impl; import io.jmix.core.Metadata; import io.jmix.dataimport.configuration.ImportConfiguration; import io.jmix.dataimport.configuration.mapping.PropertyMapping; import io.jmix.dataimport.extractor.data.ImportedData; import io.jmix.dataimport.extractor.data.ImportedDataItem; import io.jmix.dataimport.extractor.entity.EntityExtractionResult; import io.jmix.dataimport.extractor.entity.EntityExtractor; import io.jmix.dataimport.property.populator.EntityInfo; import io.jmix.dataimport.property.populator.EntityPropertiesPopulator; import io.jmix.dataimport.property.populator.impl.CreatedReference; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.*; @Component("datimp_EntityExtractor") public class EntityExtractorImpl implements EntityExtractor { @Autowired protected Metadata metadata; @Autowired protected EntityPropertiesPopulator entityPropertiesPopulator; @Override public EntityExtractionResult extractEntity(ImportConfiguration importConfiguration, ImportedDataItem dataItem) { Object entity = metadata.create(importConfiguration.getEntityClass()); EntityInfo entityInfo = entityPropertiesPopulator.populateProperties(entity, importConfiguration, dataItem); return new EntityExtractionResult(entityInfo.getEntity(), dataItem); } @Override public List<EntityExtractionResult> extractEntities(ImportConfiguration importConfiguration, ImportedData importedData) { return extractEntities(importConfiguration, importedData.getItems()); } @Override public List<EntityExtractionResult> extractEntities(ImportConfiguration importConfiguration, List<ImportedDataItem> importedDataItems) { List<EntityExtractionResult> entityExtractionResults = new ArrayList<>(); Map<PropertyMapping, List<Object>> createdReferences = new HashMap<>(); importedDataItems.forEach(importedDataItem -> { Object entityToPopulate = metadata.create(importConfiguration.getEntityClass()); EntityInfo entityInfo = entityPropertiesPopulator.populateProperties(entityToPopulate, importConfiguration, importedDataItem, createdReferences); entityExtractionResults.add(new EntityExtractionResult(entityInfo.getEntity(), importedDataItem)); fillCreatedReferences(entityInfo, createdReferences); }); return entityExtractionResults; } protected void fillCreatedReferences(EntityInfo entityInfo, Map<PropertyMapping, List<Object>> createdReferencesByMapping) { List<CreatedReference> createdReferences = entityInfo.getCreatedReferences(); if (CollectionUtils.isNotEmpty(createdReferences)) { createdReferences.forEach(createdReference -> { PropertyMapping propertyMapping = createdReference.getPropertyMapping(); Object createdObject = createdReference.getCreatedObject(); List<Object> createdObjects = createdReferencesByMapping.getOrDefault(propertyMapping, new ArrayList<>()); if (!(createdObject instanceof Collection) && !createdObjects.contains(createdObject)) { createdObjects.add(createdObject); } createdReferencesByMapping.put(propertyMapping, createdObjects); }); } } }
49.670732
157
0.764793
7d46ca58f2841103a8bc459e531772e3c64a34ca
250
package com.alibaba.datax.plugin.reader.httpreader.enums; /** * <p> * 数据接收格式 枚举 * </p> * * @author JupiterMouse 2020/8/5 * @since 1.0 */ public enum FormatEnum { /** * JSON格式 */ JSON, /** * XML格式 */ SOAP }
11.904762
57
0.516
c4741267d614e64334b041c19d4ec16cd4ac610a
9,368
package com.test.environment.alex.environmenttesttask002; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.view.GestureDetectorCompat; import android.support.wearable.view.DelayedConfirmationView; import android.support.wearable.view.WatchViewStub; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import com.mobvoi.android.common.ConnectionResult; import com.mobvoi.android.common.api.MobvoiApiClient; import com.mobvoi.android.common.api.ResultCallback; import com.mobvoi.android.semantic.EntityTagValue; import com.mobvoi.android.semantic.SemanticIntentApi; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.mobvoi.android.common.ConnectionResult; import com.mobvoi.android.common.api.MobvoiApiClient; import com.mobvoi.android.common.api.MobvoiApiClient.ConnectionCallbacks; import com.mobvoi.android.common.api.MobvoiApiClient.OnConnectionFailedListener; import com.mobvoi.android.common.data.FreezableUtils; import com.mobvoi.android.location.LocationServices; import com.mobvoi.android.wearable.Asset; import com.mobvoi.android.wearable.DataApi; import com.mobvoi.android.wearable.DataEvent; import com.mobvoi.android.wearable.DataEventBuffer; import com.mobvoi.android.wearable.DataMapItem; import com.mobvoi.android.wearable.MessageApi; import com.mobvoi.android.wearable.MessageEvent; import com.mobvoi.android.wearable.Node; import com.mobvoi.android.wearable.NodeApi; import com.mobvoi.android.wearable.Wearable; import java.util.Collection; import java.util.HashSet; public class TaxiHandler extends Activity implements MobvoiApiClient.ConnectionCallbacks, MobvoiApiClient.OnConnectionFailedListener, MessageApi.MessageListener, NodeApi.NodeListener, DelayedConfirmationView.DelayedConfirmationListener { private static final String TAG = "TaxiHandler"; private TextView mTextView; private String toStr = ""; private String fromStr = ""; private MobvoiApiClient mMobvoiApiClient; DelayedConfirmationView delayedConfirmationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_taxi_handler); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub); stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener(){ @Override public void onLayoutInflated(WatchViewStub stub){ mTextView=(TextView)stub.findViewById(R.id.text); mTextView.setText("正在处理中,请稍后……"); delayedConfirmationView = (DelayedConfirmationView) findViewById(R.id.timer); delayedConfirmationView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TaxiHandler.this.finish(); } }); getTexiInfo(); } }); initMobvoiAPI(); } @Override protected void onResume() { super.onResume(); mMobvoiApiClient.connect(); } @Override protected void onPause() { super.onPause(); Wearable.MessageApi.removeListener(mMobvoiApiClient, this); Wearable.NodeApi. removeListener(mMobvoiApiClient, this); mMobvoiApiClient.disconnect(); } private void initMobvoiAPI() { mMobvoiApiClient = new MobvoiApiClient.Builder(this) .addApi(Wearable.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } private void getTexiInfo() { EntityTagValue from = SemanticIntentApi.extractAsEntity(getIntent(), "from"); EntityTagValue to = SemanticIntentApi.extractAsEntity(getIntent(), "to"); if ( from != null ) { if ( from.normData != null ) { fromStr = from.normData; Log.i(TAG, "from: " + fromStr ); } } if ( to != null ) { if ( to.normData != null ) { toStr = to.normData; Log.i(TAG, "to: " + toStr ); } } } @Override public void onConnected(Bundle bundle) { Wearable.MessageApi.addListener(mMobvoiApiClient, this); Wearable.NodeApi. addListener(mMobvoiApiClient, this); new StartWearableActivityTask().execute(); } @Override public void onConnectionSuspended(int i) { } private static final String ALL_TARGET_PATH = "/all-target"; private static final String GET_UBER_PATH = "/get-uber"; @Override public void onMessageReceived(MessageEvent messageEvent) { Log.i( TAG, "onMessageReeived: " + messageEvent ); // Check to see if the message is to start an activity if ( messageEvent.getPath().equals(ALL_TARGET_PATH) ) { String allTarget = new String(messageEvent.getData()); final String[] targets = allTarget.split("@"); runOnUiThread(new Runnable() { @Override public void run() { String tmp = "人民优步\n"; tmp += "从 " + targets[0] + "\n"; tmp += "到 " + targets[1] + "\n"; mTextView.setText(tmp); onStartTimer(); ; } }); } } @Override public void onPeerConnected(Node node) { } @Override public void onPeerDisconnected(Node node) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } public void onStartTimer() { // DelayedConfirmationView delayedConfirmationView = (DelayedConfirmationView) // findViewById(R.id.timer); // delayedConfirmationView.setVisibility( View.VISIBLE ); delayedConfirmationView.setTotalTimeMs(3 * 1000); delayedConfirmationView.setListener(this); delayedConfirmationView.start(); } @Override public void onTimerFinished(View view) { new getUberTask().execute(); } @Override public void onTimerSelected(View view) { TaxiHandler.this.finish(); } private class StartWearableActivityTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { Collection<String> nodes = getNodes(); for ( String node : nodes ) { sendStartActivityMessage( node ); } return null; } } private static final String START_ACTIVITY_PATH = "/start-activity"; // private static final String TAXI_PATH = "/"; private void sendStartActivityMessage( String node ) { String tmp = fromStr + "@"; tmp += toStr; Log.i(TAG, "sending tmp:!!!" + tmp); Wearable.MessageApi.sendMessage( mMobvoiApiClient, node, START_ACTIVITY_PATH, tmp.getBytes()) .setResultCallback( new ResultCallback<MessageApi.SendMessageResult>() { @Override public void onResult(MessageApi.SendMessageResult sendMessageResult) { if (!sendMessageResult.getStatus().isSuccess()) { Log.e(TAG, "Fained to send message with status code: " + sendMessageResult.getStatus().getStatusCode()); } } } ); } private class getUberTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { Collection<String> nodes = getNodes(); for ( String node : nodes ) { sendTargetMessage( node ); } TaxiHandler.this.finish(); return null; } } private void sendTargetMessage( String node ) { Wearable.MessageApi.sendMessage( mMobvoiApiClient, node, GET_UBER_PATH, new byte[0]) .setResultCallback( new ResultCallback<MessageApi.SendMessageResult>() { @Override public void onResult(MessageApi.SendMessageResult sendMessageResult) { if (!sendMessageResult.getStatus().isSuccess()) { Log.e(TAG, "Fained to send message with status code: " + sendMessageResult.getStatus().getStatusCode()); } } } ); } private Collection<String> getNodes() { HashSet<String> results = new HashSet<String>(); NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( mMobvoiApiClient ).await(); for ( Node node : nodes.getNodes() ) { results.add( node.getId() ); } return results; } }
33.819495
98
0.618595
326c55ef6c19e4b85325b83a540150a453be9ba0
1,390
package am.foodi.popularmovies; import android.content.Context; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; public class FetchMovieReviewsTask extends FetchTheMovieDbJSONTask { private OnReviewsFetchCompleted listener; public interface OnReviewsFetchCompleted{ void onReviewsFetchCompleted(Review[] result); } public FetchMovieReviewsTask(Context context, OnReviewsFetchCompleted listener, int movie_id) { super(context); this.listener=listener; this.uriBuilder.appendEncodedPath("/3/movie/"+movie_id+"/reviews"); } public Review[] getItemsFromJSON(String reviewJsonStr) throws JSONException { JSONObject reviewsJson = new JSONObject(reviewJsonStr); JSONArray reviewArray = reviewsJson.getJSONArray("results"); Review[] resultReviews = new Review[ reviewArray.length() ]; for(int i = 0; i < reviewArray.length(); i++) { JSONObject review = reviewArray.getJSONObject(i); resultReviews[i] = new Review(review); } return resultReviews; } protected void onPostExecute(Object[] result){ if (result != null) { Review[] reviewArray = Arrays.copyOf(result, result.length, Review[].class); listener.onReviewsFetchCompleted(reviewArray); } } }
32.325581
99
0.692806
294c2c042d7a94bacd2fdfd8e8c7d99684033514
3,559
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.mapdemo; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.google.android.libraries.maps.CameraUpdateFactory; import com.google.android.libraries.maps.GoogleMap; import com.google.android.libraries.maps.OnMapReadyCallback; import com.google.android.libraries.maps.SupportMapFragment; import com.google.android.libraries.maps.model.BitmapDescriptorFactory; import com.google.android.libraries.maps.model.LatLng; import com.google.android.libraries.maps.model.Marker; import com.google.android.libraries.maps.model.MarkerOptions; /** This shows how to set collision behavior for the marker. */ public class MarkerCollisionDemoActivity extends AppCompatActivity implements OnMapReadyCallback { private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689); private GoogleMap map = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.marker_collision_demo); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap map) { this.map = map; addMarkersToMap(); map.moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, 3)); } private void addMarkersToMap() { MarkerOptions defaultMarkerOptions = new MarkerOptions(); // Add 100 markers to the map. for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { defaultMarkerOptions .position(new LatLng(SYDNEY.latitude + i, SYDNEY.longitude - j)) .zIndex(i * 10 + j) .title("zIndex:" + (i * 10 + j)) .draggable(true); if ((i + j) % 3 == 0) { defaultMarkerOptions.icon( BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); defaultMarkerOptions.collisionBehavior( Marker.CollisionBehavior.OPTIONAL_AND_HIDES_LOWER_PRIORITY); } else if ((i + j) % 3 == 1) { defaultMarkerOptions.icon( BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)); defaultMarkerOptions.collisionBehavior(Marker.CollisionBehavior.REQUIRED_AND_HIDES_OPTIONAL); } else { defaultMarkerOptions.icon( BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); defaultMarkerOptions.collisionBehavior(Marker.CollisionBehavior.REQUIRED); } map.addMarker(defaultMarkerOptions); } } } }
41.870588
114
0.650183
a76a6ea6881c9639259fb98990be7451cf960356
25,377
package salsa.corpora.xmlparser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import salsa.corpora.elements.Action; import salsa.corpora.elements.Annotation; import salsa.corpora.elements.Author; import salsa.corpora.elements.Body; import salsa.corpora.elements.Corpus; import salsa.corpora.elements.CorpusId; import salsa.corpora.elements.Date; import salsa.corpora.elements.Description; import salsa.corpora.elements.Edge; import salsa.corpora.elements.Edgelabel; import salsa.corpora.elements.Element; import salsa.corpora.elements.Feature; import salsa.corpora.elements.Fenode; import salsa.corpora.elements.Flag; import salsa.corpora.elements.Flags; import salsa.corpora.elements.Format; import salsa.corpora.elements.Frame; import salsa.corpora.elements.FrameElement; import salsa.corpora.elements.Frames; import salsa.corpora.elements.Global; import salsa.corpora.elements.Globals; import salsa.corpora.elements.Graph; import salsa.corpora.elements.Head; import salsa.corpora.elements.History; import salsa.corpora.elements.Match; import salsa.corpora.elements.Matches; import salsa.corpora.elements.Meta; import salsa.corpora.elements.Name; import salsa.corpora.elements.Nonterminal; import salsa.corpora.elements.Nonterminals; import salsa.corpora.elements.Part; import salsa.corpora.elements.Recipient; import salsa.corpora.elements.Secedge; import salsa.corpora.elements.Secedgelabel; import salsa.corpora.elements.Semantics; import salsa.corpora.elements.Sentence; import salsa.corpora.elements.Splitword; import salsa.corpora.elements.Splitwords; import salsa.corpora.elements.Step; import salsa.corpora.elements.Target; import salsa.corpora.elements.Terminal; import salsa.corpora.elements.Terminals; import salsa.corpora.elements.Underspecification; import salsa.corpora.elements.UnderspecificationFrameElements; import salsa.corpora.elements.UnderspecificationFrames; import salsa.corpora.elements.Uspblock; import salsa.corpora.elements.Uspitem; import salsa.corpora.elements.Value; import salsa.corpora.elements.Variable; import salsa.corpora.elements.Wordtag; import salsa.corpora.elements.Wordtags; import salsa.corpora.noelement.Id; /** * This handles events of the <code>CorpusParser</code>. It tells the parser * how to properly read in a SalsaXML file into the <code>Corpus</code> data * structure. * * @author Fabian Shirokov * */ public class CorpusHandler extends DefaultHandler { // the currently active element private String activeElement; // if the 'target' element is active, then <code>isTarget</code> is true. private boolean isTarget; // if 'fe' is active, the <code>isFrameElement</code> is true. private boolean isFrameElement; // if 'frame' is active, the <code>isFrame</code> is true. private boolean isFrame; // if 'uspframes' is active, the <code>isUspframes</code> is true. private boolean isUspframes; private boolean isEdgelabel; private boolean isSecedgelabel; private boolean isFeature; // the corpus that will at the end represent the whole XML file. private Corpus corpus; private Action currentAction; private Annotation currentAnnotation; private Author currentAuthor; private Body currentBody; private CorpusId currentCorpusId; private Date currentDate; private Description currentDescription; private Edge currentEdge; private Edgelabel currentEdgelabel; private Element currentElement; private Feature currentFeature; private Fenode currentFenode; private Flag currentFlag; private Flags currentFlags; private Format currentFormat; private Frame currentFrame; private FrameElement currentFrameElement; private Frames currentFrames; private Global currentGlobal; private Globals currentGlobals; private Graph currentGraph; private Head currentHead; private History currentHistory; private Match currentMatch; private Matches currentMatches; private Meta currentMeta; private Name currentName; private Nonterminal currentNonterminal; private Nonterminals currentNonterminals; private Part currentPart; private Recipient currentRecipient; private Secedge currentSecedge; private Secedgelabel currentSecedgelabel; private Semantics currentSemantics; private Sentence currentSentence; private Splitword currentSplitword; private Splitwords currentSplitwords; private Step currentStep; private Target currentTarget; private Terminal currentTerminal; private Terminals currentTerminals; private Underspecification currentUnderspecification; private UnderspecificationFrameElements currentUnderspecificationFrameElements; private UnderspecificationFrames currentUnderspecificationFrames; private Uspblock currentUspblock; private Uspitem currentUspitem; private Value currentValue; private Variable currentVariable; private Wordtag currentWordtag; private Wordtags currentWordtags; /** * Zero-argumented default constructor. */ public CorpusHandler() { } /** * This method is called when the XML document starts. By now, nothing * happens in this method. */ public void startDocument() { } /** * This overrides {@link org.xml.sax.helpers.DefaultHandler#startElement}. * This method is called when the parser has found an opening element tag. * It initializes new objects and assigns them to their superordinating * elements. For example, it creates a new <code>Head</code> and assigns * it to the <code>Corpus</code>. * * @param uri * a <code>String</code> with the namespace URI, empty if * parser factory is not namespace aware (default) * @param localName * a <code>String</code> with the local name (without prefix), * empty if parser factory is not namespace aware (default) * @param qualName * a <code>String</code> with the qualified (with prefix) name, * or the empty string if qualified names are not available * @param atts * <code>Attributes</code> attached to the element, empty if * there are no attributes * @throws SAXException * if an error occurs, possibly wrapping another exception */ public void startElement(@SuppressWarnings("unused") String uri, @SuppressWarnings("unused") String localName, String qualName, Attributes atts) throws SAXException { activeElement = qualName; if (qualName.equalsIgnoreCase("action")) { currentAction = new Action(atts.getValue("date"), atts .getValue("time"), atts.getValue("user"), atts .getValue("type")); currentHistory.addAction(currentAction); } else if (qualName.equalsIgnoreCase("annotation")) { currentAnnotation = new Annotation(); currentHead.setAnnotation(currentAnnotation); } else if (qualName.equalsIgnoreCase("author")) { currentAuthor = new Author(); currentMeta.setAuthor(currentAuthor); } else if (qualName.equalsIgnoreCase("body")) { currentBody = new Body(); corpus.setBody(currentBody); } else if (qualName.equalsIgnoreCase("corpus")) { corpus = new Corpus(atts.getValue("corpusname"), atts .getValue("target")); } else if (qualName.equalsIgnoreCase("corpus_id")) { currentCorpusId = new CorpusId(); currentMeta.setCorpus_id(currentCorpusId); } else if (qualName.equalsIgnoreCase("date")) { currentDate = new Date(); currentMeta.setDate(currentDate); } else if (qualName.equalsIgnoreCase("description")) { currentDescription = new Description(); currentMeta.setDescription(currentDescription); } else if (qualName.equalsIgnoreCase("edge")) { currentEdge = new Edge(new Id(atts.getValue("idref")), atts .getValue("label")); currentNonterminal.addEdge(currentEdge); } else if (qualName.equalsIgnoreCase("edgelabel")) { isEdgelabel = true; currentEdgelabel = new Edgelabel(); currentAnnotation.setEdgelabel(currentEdgelabel); } else if (qualName.equalsIgnoreCase("element")) { currentElement = new Element(atts.getValue("name"), atts .getValue("optional")); currentFrame.addElement(currentElement); } else if (qualName.equalsIgnoreCase("fe")) { isFrameElement = true; currentFrameElement = new FrameElement(new Id(atts.getValue("id")), atts.getValue("name")); String source = atts.getValue("source"); String usp = atts.getValue("usp"); if (null != source) { currentFrameElement.setSource(source); } if (null != usp) { currentFrameElement.setUsp(usp); } currentFrame.addFe(currentFrameElement); } else if (qualName.equalsIgnoreCase("feature")) { isFeature = true; currentFeature = new Feature(atts.getValue("domain"), atts .getValue("name")); currentAnnotation.addFeature(currentFeature); } else if (qualName.equalsIgnoreCase("fenode")) { currentFenode = new Fenode(new Id(atts.getValue("idref")), atts .getValue("is_split")); if (isTarget) { currentTarget.addFenode(currentFenode); } else { currentFrameElement.addFenode(currentFenode); } } else if (qualName.equalsIgnoreCase("flag")) { currentFlag = new Flag(atts.getValue("name")); String forWhat = atts.getValue("for"); if (null != forWhat) { currentFlag.setForWhat(forWhat); } String source = atts.getValue("source"); if (null != source) { currentFlag.setSource(source); } if (isFrameElement) { currentFrameElement.addFlag(currentFlag); } else if (isFrame) { currentFrame.addFlag(currentFlag); } else { currentFlags.addFlag(currentFlag); } } else if (qualName.equalsIgnoreCase("flags")) { currentFlags = new Flags(); currentHead.setFlags(currentFlags); } else if (qualName.equalsIgnoreCase("format")) { currentFormat = new Format(); currentMeta.setFormat(currentFormat); } else if (qualName.equalsIgnoreCase("frame")) { isFrame = true; currentFrame = new Frame(atts.getValue("name")); String idString = atts.getValue("id"); String source = atts.getValue("source"); String usp = atts.getValue("usp"); if (null != idString) { Id id = new Id(idString); currentFrame.setId(id); } if (null != source) { currentFrame.setSource(source); } if (null != usp) { currentFrame.setUsp(usp); } currentFrames.addFrame(currentFrame); } else if (qualName.equalsIgnoreCase("frames")) { currentFrames = new Frames(); String xmlns = atts.getValue("xmlns"); if (null != xmlns) { currentFrames.setXmlns(xmlns); } if (null == currentHead.getFrames()) { currentHead.setFrames(currentFrames); } else { currentSemantics.addFrames(currentFrames); } } else if (qualName.equalsIgnoreCase("global")) { currentGlobal = new Global(atts.getValue("type")); String param = atts.getValue("param"); if (null != param) { currentGlobal.setParam(param); } currentGlobals.addGlobal(currentGlobal); } else if (qualName.equalsIgnoreCase("globals")) { currentGlobals = new Globals(); currentSemantics.addGlobals(currentGlobals); } else if (qualName.equalsIgnoreCase("graph")) { currentGraph = new Graph(new Id(atts.getValue("root"))); currentSentence.setGraph(currentGraph); } else if (qualName.equalsIgnoreCase("head")) { currentHead = new Head(); corpus.setHead(currentHead); } else if (qualName.equalsIgnoreCase("history")) { currentHistory = new History(); currentMeta.setHistory(currentHistory); } else if (qualName.equalsIgnoreCase("match")) { currentMatch = new Match(atts.getValue("subgraph")); currentMatches.addMatch(currentMatch); } else if (qualName.equalsIgnoreCase("matches")) { currentMatches = new Matches(); currentSentence.setMatches(currentMatches); } else if (qualName.equalsIgnoreCase("meta")) { currentMeta = new Meta(); currentHead.setMeta(currentMeta); } else if (qualName.equalsIgnoreCase("name")) { currentName = new Name(); currentMeta.setName(currentName); } else if (qualName.equalsIgnoreCase("step")) { currentStep = new Step(); currentAction.setStep(currentStep); } else if (qualName.equalsIgnoreCase("recipient")) { currentRecipient = new Recipient(atts.getValue("id")); currentAction.addRecipient(currentRecipient); } else if (qualName.equalsIgnoreCase("nonterminals")) { currentNonterminals = new Nonterminals(); currentGraph.setNonterminals(currentNonterminals); } else if (qualName.equalsIgnoreCase("nt")) { currentNonterminal = new Nonterminal(atts.getValue("cat"), new Id( atts.getValue("id"))); currentNonterminals.addNonterminal(currentNonterminal); } else if (qualName.equalsIgnoreCase("part")) { currentPart = new Part(atts.getValue("word"), new Id(atts .getValue("id"))); currentSplitword.addPart(currentPart); } else if (qualName.equalsIgnoreCase("s")) { currentSentence = new Sentence(new Id(atts.getValue("id"))); String source = atts.getValue("source"); if (null != source) { currentSentence.setSource(source); } currentBody.addSentence(currentSentence); } else if (qualName.equalsIgnoreCase("secedge")) { currentSecedge = new Secedge(new Id(atts.getValue("id")), atts .getValue("label")); currentTerminal.setSecedge(currentSecedge); } else if (qualName.equalsIgnoreCase("secedgelabel")) { isSecedgelabel = true; currentSecedgelabel = new Secedgelabel(); currentAnnotation.setSecedgelabel(currentSecedgelabel); } else if (qualName.equalsIgnoreCase("sem")) { currentSemantics = new Semantics(); currentSentence.setSem(currentSemantics); } else if (qualName.equalsIgnoreCase("splitwords")) { currentSplitwords = new Splitwords(); currentSemantics.addSplitwords(currentSplitwords); } else if (qualName.equalsIgnoreCase("splitword")) { currentSplitword = new Splitword(new Id(atts.getValue("idref"))); currentSplitwords.addSplitword(currentSplitword); } else if (qualName.equalsIgnoreCase("step")) { currentStep = new Step(); currentAction.setStep(currentStep); } else if (qualName.equalsIgnoreCase("t")) { currentTerminal = new Terminal(new Id(atts.getValue("id")), atts .getValue("lemma"), atts.getValue("morph"), atts .getValue("pos"), atts.getValue("word")); currentTerminals.addTerminal(currentTerminal); } else if (qualName.equalsIgnoreCase("target")) { isTarget = true; currentTarget = new Target(); String idString = atts.getValue("id"); String lemma = atts.getValue("lemma"); String headlemma = atts.getValue("headlemma"); if (null != idString) { Id id = new Id(idString); currentTarget.setId(id); } if (null != lemma) { currentTarget.setLemma(lemma); } if (null != headlemma) { currentTarget.setHeadlemma(headlemma); } currentFrame.setTarget(currentTarget); } else if (qualName.equalsIgnoreCase("terminals")) { currentTerminals = new Terminals(); currentGraph.setTerminals(currentTerminals); } else if (qualName.equalsIgnoreCase("usp")) { currentUnderspecification = new Underspecification(); currentSemantics.addUsp(currentUnderspecification); } else if (qualName.equalsIgnoreCase("uspblock")) { currentUspblock = new Uspblock(); if (isUspframes) { currentUnderspecificationFrames.addUspblock(currentUspblock); } else { currentUnderspecificationFrameElements .addUspblock(currentUspblock); } } else if (qualName.equalsIgnoreCase("uspfes")) { currentUnderspecificationFrameElements = new UnderspecificationFrameElements(); currentUnderspecification .setUspfes(currentUnderspecificationFrameElements); } else if (qualName.equalsIgnoreCase("uspframes")) { isUspframes = true; currentUnderspecificationFrames = new UnderspecificationFrames(); currentUnderspecification .setUspframes(currentUnderspecificationFrames); } else if (qualName.equalsIgnoreCase("uspitem")) { currentUspitem = new Uspitem(new Id(atts.getValue("idref"))); currentUspblock.addUspitem(currentUspitem); } else if (qualName.equalsIgnoreCase("value")) { currentValue = new Value(atts.getValue("name")); if (isEdgelabel) { currentEdgelabel.addValue(currentValue); } else if (isSecedgelabel) { currentSecedgelabel.addValue(currentValue); } else if (isFeature) { currentFeature.addValue(currentValue); } else { System.err .println("parsing error: 'value' is in the wrong section"); } } else if (qualName.equalsIgnoreCase("variable")) { currentVariable = new Variable(atts.getValue("name"), new Id(atts .getValue("idref"))); currentMatch.addVariable(currentVariable); } else if (qualName.equalsIgnoreCase("wordtag")) { currentWordtag = new Wordtag(atts.getValue("name")); currentWordtags.setWordtag(currentWordtag); } else if (qualName.equalsIgnoreCase("wordtags")) { currentWordtags = new Wordtags(); String xmlns = atts.getValue("xmlns"); if (null != xmlns) { currentWordtags.setXmlns(xmlns); } if (null == currentHead.getWordtags()) { currentHead.setWordtags(currentWordtags); } else { currentSemantics.addWordtags(currentWordtags); } } } /** * This overrides {@link org.xml.sax.helpers.DefaultHandler#endElement}. * This method is called when the parser has found a closing element tag. * * @param uri * a <code>String</code> with the namespace URI, empty if * parser factory is not namespace aware (default) * @param localName * a <code>String</code> with the local name (without prefix), * empty if parser factory is not namespace aware (default) * @param qualName * a <code>String</code> with the qualified (with prefix) name, * or the empty string if qualified names are not available * @throws SAXException * if an error occurs, possibly wrapping another exception */ public void endElement(@SuppressWarnings("unused") String uri, @SuppressWarnings("unused") String localName, String qualName) throws SAXException { if (qualName.equalsIgnoreCase("action")) { } else if (qualName.equalsIgnoreCase("annotation")) { } else if (qualName.equalsIgnoreCase("body")) { } else if (qualName.equalsIgnoreCase("corpus")) { } else if (qualName.equalsIgnoreCase("corpus_id")) { } else if (qualName.equalsIgnoreCase("edge")) { } else if (qualName.equalsIgnoreCase("edgelabel")) { isEdgelabel = false; } else if (qualName.equalsIgnoreCase("element")) { } else if (qualName.equalsIgnoreCase("fe")) { isFrameElement = false; } else if (qualName.equalsIgnoreCase("feature")) { isFeature = false; } else if (qualName.equalsIgnoreCase("fenode")) { } else if (qualName.equalsIgnoreCase("flag")) { } else if (qualName.equalsIgnoreCase("flags")) { } else if (qualName.equalsIgnoreCase("format")) { } else if (qualName.equalsIgnoreCase("frame")) { isFrame = false; } else if (qualName.equalsIgnoreCase("frames")) { } else if (qualName.equalsIgnoreCase("global")) { } else if (qualName.equalsIgnoreCase("globals")) { } else if (qualName.equalsIgnoreCase("graph")) { } else if (qualName.equalsIgnoreCase("head")) { } else if (qualName.equalsIgnoreCase("history")) { } else if (qualName.equalsIgnoreCase("match")) { } else if (qualName.equalsIgnoreCase("matches")) { } else if (qualName.equalsIgnoreCase("meta")) { } else if (qualName.equalsIgnoreCase("step")) { } else if (qualName.equalsIgnoreCase("recipient")) { } else if (qualName.equalsIgnoreCase("nonterminals")) { } else if (qualName.equalsIgnoreCase("nt")) { } else if (qualName.equalsIgnoreCase("part")) { } else if (qualName.equalsIgnoreCase("s")) { } else if (qualName.equalsIgnoreCase("secedge")) { } else if (qualName.equalsIgnoreCase("secedgelabel")) { isSecedgelabel = false; } else if (qualName.equalsIgnoreCase("sem")) { } else if (qualName.equalsIgnoreCase("splitwords")) { } else if (qualName.equalsIgnoreCase("splitword")) { } else if (qualName.equalsIgnoreCase("step")) { } else if (qualName.equalsIgnoreCase("t")) { } else if (qualName.equalsIgnoreCase("target")) { isTarget = false; } else if (qualName.equalsIgnoreCase("terminals")) { } else if (qualName.equalsIgnoreCase("usp")) { } else if (qualName.equalsIgnoreCase("uspblock")) { } else if (qualName.equalsIgnoreCase("uspfes")) { } else if (qualName.equalsIgnoreCase("uspframes")) { isUspframes = false; } else if (qualName.equalsIgnoreCase("uspitem")) { } else if (qualName.equalsIgnoreCase("value")) { } else if (qualName.equalsIgnoreCase("variable")) { } else if (qualName.equalsIgnoreCase("wordtag")) { } else if (qualName.equalsIgnoreCase("wordtags")) { } } /** * This method is called when some text is found in the XML file. It adds or * assigns the text to the currently active element. * */ public void characters(char[] c, int start, int length) throws SAXException { String currentString = new String(c, start, length); if (activeElement.equalsIgnoreCase("author")) { String text = currentAuthor.getText(); if (null != text) { text = text + currentString; currentAuthor.setText(text); } else { currentAuthor.setText(currentString); } } else if (activeElement.equalsIgnoreCase("corpus_id")) { String text = currentCorpusId.getId(); if (null != text) { text = text + currentString; currentCorpusId.setId(text); } else { currentCorpusId.setId(currentString); } } else if (activeElement.equalsIgnoreCase("date")) { String text = currentDate.getText(); if (null != text) { text = text + currentString; currentDate.setText(text); } else { currentDate.setText(currentString); } } else if (activeElement.equalsIgnoreCase("description")) { String text = currentDescription.getText(); if (null != text) { text = text + currentString; currentDescription.setText(text); } else { currentDescription.setText(currentString); } } else if (activeElement.equalsIgnoreCase("flag")) { String text = currentFlag.getText(); if (null != text) { text = text + currentString; currentFlag.setText(text); } else { currentFlag.setText(currentString); } } else if (activeElement.equalsIgnoreCase("format")) { String text = currentFormat.getFormat(); if (null != text) { text = text + currentString; currentFormat.setFormat(text); } else { currentFormat.setFormat(currentString); } } else if (activeElement.equalsIgnoreCase("global")) { String text = currentGlobal.getText(); if (null != text) { text = text + currentString; currentGlobal.setText(text); } else { currentGlobal.setText(currentString); } } else if (activeElement.equalsIgnoreCase("name")) { String text = currentName.getText(); if (null != text) { text = text + currentString; currentName.setText(text); } else { currentName.setText(currentString); } } else if (activeElement.equalsIgnoreCase("recipient")) { String text = currentRecipient.getText(); if (null != text) { text = text + currentString; currentRecipient.setText(text); } else { currentRecipient.setText(currentString); } } else if (activeElement.equalsIgnoreCase("step")) { String text = currentStep.getStep(); if (null != text) { text = text + currentString; currentStep.setStep(text); } else { currentStep.setStep(currentString); } } else if (activeElement.equalsIgnoreCase("value")) { String text = currentValue.getText(); if (null != text) { text = text + currentString; currentValue.setText(text); } else { currentValue.setText(currentString); } } else if (activeElement.equalsIgnoreCase("variable")) { String text = currentVariable.getText(); if (null != text) { text = text + currentString; currentVariable.setText(text); } else { currentVariable.setText(currentString); } } } /** * This returns the <code>Corpus</code> that has been read out of the XML * file. */ public Corpus getCorpus() { return this.corpus; } }
25.275896
83
0.680262
bf1cb53ffa994b389663eaf95f1a1d7fedfcd675
3,466
class e { public boolean RA0uDo; public LjFYwkoZYDl3 H2CpmYFtczzIn () throws g4jdIWRz { W[] S82iohsz5Tba = ( false[ 9738579.A3UWIghH9Akr0q()]).WwBEddxEIUTM(); C7dIThRtsn[] BCfuyd1 = !new O4RmA3WsX3().DiGgqPv(); } public boolean[] yj3M7 (boolean UfX6Pg, int[][] L17bratvt, int R88I1G, int Him, vNthv9KAN4tj5T[][][][] lt, int rdLhfwx0lKR) throws gTQyEKpWbez { int CR5 = !!--true.lJiqL1sujROLo9() = -!-!new cUEo3Kzyk()[ null.BSYpoEcenj1zL]; return; int[] VmSbKoW = new void[ this[ null.DKzo0t()]][ --!!-!!!( true.SvFHLw0S7O0ZOW()).oB6b5JWI()] = this[ new void[ ( true.sj0FBQ2OKd)[ HmFZGAe01.sP8C323()]][ false[ -this.XVu9o2gES]]]; while ( -AccaTj7i6EF().N0lgg()) while ( --!zQn15P().yrqvonCN8cazUa) ; if ( !-!new IT77y9T8Rc2z().lIyv) ; if ( --!-!!!( -null.HhooAPyWMwnN())[ false.t3GHtf3Rj21c0L()]) return; void NqR21g8jATKRPI = mqSdCc().a2PwzvFU9vdVh; } public int[] SsrNV6rP5; public static void S4EXewUAMt (String[] vaq4Tut) throws tmPe { if ( -!-!-!new OKVKj8O9aJ().PS2ie) return;else return; void[][] g5P; void[] Fx6I = this[ --false[ !!-false.u4()]] = new QTxEwKL()[ new int[ true.curEN16PmuTEl][ !62.l2LWB56()]]; int[][][] V = KQ_QFcypV0hQc().YvfzJntjbENO; void[][] wj0AzHk; { return; boolean[] aP; FzS_t1zz5[] NvH_4_0z7Tox8Z; void XltH3V; return; void mNZD; if ( -!-false.TO8b1TIYLRh()) if ( false.Rf2WQeQ6) return; eQtrIkyXIK7Cl[] wjXdyL0PNg; int PF25uuoo3wW6K; if ( ( --!null.uwB).TQMDk6xoJzF()) while ( false[ ( null.wSj5XSO7)[ !false.y]]) if ( ( this.ZFAaz)[ -!!this.L8POHbHQ()]) return; boolean[] k321kzMps9zG; } } public static void R (String[] bUtDJo9WkWdBy) { while ( !this.xY4NdU2oDv7X()) while ( zThsqPC[ false.Biu_2h]) while ( ( ( -true.Pnbdvu)[ l8VQMu962AKf0.ghH()])[ null.ui865qTp8t0K02]) { void[][][] ott4iNmIxM; } void[] pmUwqotuoJw4b; ; int[][] ZMxKzN = !!-xBFMABgbfWG2AR().DK6FlKwdaC; boolean[] CKqvM = Dg1eQq7bF1Qh1I().dUW(); boolean D952ytx3l = !eEcry6ga4oqWVR.Wbg89() = -false.RIsXSyJTLls; int[][] Dl87sgmO2AN = true.pHU3_Z = this[ this.O2R4kxjVr1t()]; void zgemzNiWAq9mUj = false.xJU8jq; new void[ !false.xvRRubyXw()][ false[ !null.VYMojvcoxaz()]]; boolean[] CNgvj; } public static void bj2xyxxPN6RoxV (String[] tqOKg9qDKW) throws f714EGAGtf5JEi { bSGWx7HBOewALU[][] wuzACVY; void[] Z = -false.Qqpbakx13viy() = false.rUwm7gEZIM; hWf[] g_RkCpf0ubH; void[] EllclrChi61 = EQ7NA().qWoMWC4F6; return; boolean[] J0Cd8gXBZI0sB; boolean kdN; while ( false.zz4CdruG) { B5utB7LALks0 PdLRbtj0uu3mE; } int[] lzwtz37lC64 = -3992635[ ( false[ new boolean[ !!-!this.brFetJ694PG7x9()][ H3sijvoIG._pfAitp74()]]).F9HgEqnqf()] = ( ---new o9Dmjh5f()[ this[ -false.bTqB_jvyKH]]).Z0a34TxNRY(); return; while ( new S2uRdQ[ this.PM()].BfBLdTESz()) if ( new KvSEjf().nf3AQY6t9oz()) return; IiafaP9ylaD[] D3kByyR; void Lda; !!32[ 10077[ !-!K59Y.TduK_spIq]]; } public boolean ljCwzwtVPsU6; public void[] L; public KyAH3lNXvP7RvK B7Xkrbp8BV; } class nURXCpi5x { } class bsleTA4GMdP2U { }
42.790123
191
0.579342
294d060c5f3d16545f3e931b64e7aedfef4d968d
4,166
package com.edu.uni.augsburg.uniatron.domain.dao; import android.arch.lifecycle.LiveData; import android.arch.persistence.room.Room; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.edu.uni.augsburg.uniatron.domain.AppDatabase; import com.edu.uni.augsburg.uniatron.domain.dao.converter.DateConverter; import com.edu.uni.augsburg.uniatron.domain.query.StepCountQuery; import com.edu.uni.augsburg.uniatron.domain.query.TimeCreditQuery; import com.edu.uni.augsburg.uniatron.domain.table.StepCountEntity; import com.edu.uni.augsburg.uniatron.domain.table.TimeCreditEntity; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Calendar; import java.util.Date; import static com.edu.uni.augsburg.uniatron.domain.util.TestUtils.getDate; import static com.edu.uni.augsburg.uniatron.domain.util.TestUtils.getLiveDataValue; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; @RunWith(AndroidJUnit4.class) public class StepCountDaoTest { private AppDatabase mDb; private StepCountQuery mDao; private TimeCreditQuery mDaoCredit; @Before public void setUp() { final Context context = InstrumentationRegistry.getTargetContext(); mDb = Room.inMemoryDatabaseBuilder(context, AppDatabase.class) .allowMainThreadQueries() .build(); mDao = mDb.stepCountQuery(); mDaoCredit = mDb.timeCreditQuery(); } @After public void tearDown() { mDb.close(); } @Test public void add() { final StepCountEntity stepCountEntity = create(1, new Date()); mDao.add(stepCountEntity); assertThat(stepCountEntity.getId(), is(notNullValue())); } @Test public void loadRemainingStepCountsNegative() throws Exception { final int count = 10; final Date date = getDate(1, 1, 2018); TimeCreditEntity entry = new TimeCreditEntity(); entry.setStepCount(count); entry.setTimestamp(date); entry.setTimeBonus(2); mDaoCredit.add(entry); final LiveData<Integer> data = mDao .loadRemainingStepCount(DateConverter.getMin(Calendar.DATE).convert(date), DateConverter.getMax(Calendar.DATE).convert(date)); final Integer liveDataValue = getLiveDataValue(data); assertThat(liveDataValue, is(notNullValue())); assertThat(liveDataValue, is(-count)); } @Test public void loadRemainingStepCountsZero() throws Exception { final int count = 10; final Date date = getDate(1, 1, 2018); mDao.add(create(count, date)); TimeCreditEntity entry = new TimeCreditEntity(); entry.setStepCount(count); entry.setTimestamp(date); entry.setTimeBonus(2); mDaoCredit.add(entry); final LiveData<Integer> data = mDao .loadRemainingStepCount(DateConverter.getMin(Calendar.DATE).convert(date), DateConverter.getMax(Calendar.DATE).convert(date)); final Integer liveDataValue = getLiveDataValue(data); assertThat(liveDataValue, is(notNullValue())); assertThat(liveDataValue, is(0)); } @Test public void loadRemainingStepCountsPositive() throws Exception { final int count = 10; final Date date = getDate(1, 1, 2018); mDao.add(create(count, date)); final LiveData<Integer> data = mDao .loadRemainingStepCount(DateConverter.getMin(Calendar.DATE).convert(date), DateConverter.getMax(Calendar.DATE).convert(date)); final Integer liveDataValue = getLiveDataValue(data); assertThat(liveDataValue, is(notNullValue())); assertThat(liveDataValue, is(count)); } private StepCountEntity create(int count, Date date) { final StepCountEntity stepCountEntity = new StepCountEntity(); stepCountEntity.setStepCount(count); stepCountEntity.setTimestamp(date); return stepCountEntity; } }
35.305085
142
0.706193
85700ee6df8fda2cac816c7d9b469735184603fa
1,535
package com.dubbo.dev.plugin.loadbalance; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.rpc.RpcContext; /** * @author 86180 * @Description: 当前请求 * @date 2020/6/19:22 */ public class CurrRequest { private static ThreadLocal<ReqMeta> metaThreadLocal = new ThreadLocal<ReqMeta>(); public static ReqMeta getMeta() { return metaThreadLocal.get(); } public static void setMeta(ReqMeta reqMeta) { metaThreadLocal.set(reqMeta); } public static void remove() { metaThreadLocal.remove(); } public static ReqMeta setAttachment(ReqMeta meta){ String dubboLbHost = null; String dubboLbDefault = null; if (meta != null && !StringUtils.isBlank(meta.getDubboLbHost())) { dubboLbHost = meta.getDubboLbHost(); dubboLbDefault = meta.getDubboLbDefault(); RpcContext.getContext().setAttachment(LbConst.DUBBO_LB_HOST, dubboLbHost); RpcContext.getContext().setAttachment(LbConst.DUBBO_LB_DEFAULT, dubboLbDefault); } else { dubboLbHost = LbConfig.getConf().getProperty(LbConst.DUBBO_LB_HOST, "127.0.0.1"); dubboLbDefault = LbConfig.getConf().getProperty(LbConst.DUBBO_LB_DEFAULT, "127.0.0.1"); RpcContext.getContext().setAttachment(LbConst.DUBBO_LB_HOST, dubboLbHost); } ReqMeta reqMeta=new ReqMeta(); reqMeta.setDubboLbHost(dubboLbHost); reqMeta.setDubboLbDefault(dubboLbDefault); return reqMeta; } }
33.369565
99
0.673616
92215426d0dac78089bc849aa8f7e9e549dd24d5
84
package org.haobtc.onekey.event; @Deprecated public class HideWalletErrorEvent { }
14
35
0.809524
de7d2ad950078cf9be24133e98916d68311c45e2
110
package japicmp.test.semver100.d; public class SemverTestee100dSuperclass { public int fieldInSuperclass; }
18.333333
41
0.827273
635b00dabaedf7092462506320df3f726721679d
2,692
/* * Copyright 2015 - 2019 TU Dortmund * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.learnlib.alex.modelchecking.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import de.learnlib.alex.data.entities.Project; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotBlank; import java.io.Serializable; /** * Entity for a LtsMin LTL formula. */ @Entity public class LtsFormula implements Serializable { private static final long serialVersionUID = -5978527026208231972L; /** The ID of the formula in the database. */ @Id @GeneratedValue private Long id; /** The project. */ @JsonIgnore @ManyToOne(fetch = FetchType.EAGER) private Project project; /** The formula. */ @Column(columnDefinition = "MEDIUMTEXT") private String name; /** The formula. */ @NotBlank @Column(columnDefinition = "MEDIUMTEXT") private String formula; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } @JsonProperty("projectId") public Long getProjectId() { return this.project == null ? null : this.project.getId(); } @JsonProperty("projectId") public void setProjectId(Long projectId) { this.project = new Project(projectId); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFormula() { return formula; } public void setFormula(String formula) { this.formula = formula; } @Override public String toString() { return "LtsFormula{" + "name='" + name + '\'' + ", formula='" + formula + '\'' + '}'; } }
24.472727
75
0.660475
f788bc3145dfc873e01f036858ac6761df248c94
2,376
/* Copyright 1996-2008 Ariba, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. $Id: //ariba/platform/ui/aribaweb/ariba/ui/aribaweb/core/AWErrorBucket.java#8 $ */ package ariba.ui.aribaweb.core; import java.util.List; /** This interface allows uniform access to a bucket that holds one or more errors that share the same error keys. This allows different implementations for the single error and multiple error cases. @aribaapi ariba */ public interface AWErrorBucket { public boolean isSingleErrorBucket (); public int getDisplayOrder (); public int getUnnavigableDisplayOrder (); public int getRegistrationOrder (); public void setRegistrationOrder (int order); public Object getKey (); public Object[] getKeys (); public boolean keysEqual (Object[] theirKeys); public boolean isDuplicateError (AWErrorInfo error); public boolean hasErrorsWithSeverity (Boolean isWarning); public AWErrorInfo getFirstError (Boolean isWarning); public AWErrorBucket add (AWErrorInfo error); public int size (); public AWErrorInfo get (int i); public boolean hasDuplicate (); public AWComponent getAssociatedDataTable (); public Object getAssociatedTableItem (); public void setAssociatedTableItem (AWComponent table, Object item); /** Returns a list of all the <code>AWErrorInfos</code> in <code>this</code>. @aribaapi ariba */ public List<AWErrorInfo> getErrorInfos(); /** Returns a list of all the error infos in <code>this</code> that satisfy the condition {@link AWErrorInfo#isValidationError()} == <code>validationErrors</code>. All error infos are returned if <code>validationErrors == null</code>. @aribaapi ariba */ public List<AWErrorInfo> getErrorInfos (Boolean validationErrors); }
36.553846
83
0.71633
8a9d137c7c84cd8972002c522cbdb5d3c0a3f66d
534
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.apache.marmotta.ucuenca.wk.pubman.api; /** * * @author cedia */ public interface DisambiguationService { public String startDisambiguation(); public String startMerge(); public String startDisambiguation(String[] orgs); public void Process(); public void Process(String[] orgs); public void Merge(); }
19.777778
79
0.709738
7a512a45dfea67cd3796540b30bc90a21048d505
660
package cn.stackflow.aums.domain.service; import cn.stackflow.aums.common.bean.*; import cn.stackflow.aums.domain.entity.User; import java.util.List; import java.util.Optional; public interface UserService { PageResult<UserDTO> list(PageResult page); List<IdNameDTO> listSimpleUserByDeptId(String deptId); User get(String userId); UserDTO getUser(String id); Optional<User> getUserInfoByUsername(String username); UserDTO create(UserDTO userDTO); void updatePwd(UpdatePwdDTO updatePwdDTO); void updatePhone(UpdatePhoneDTO updatePhoneDTO); void update(UserDTO userDTO); void delete(User user, String id); }
20.625
58
0.751515
534ac7e1dfbd197d5b6ded0cbc49542a902f7990
1,191
package edu.matkosoric.execution.output.global.namescope; /* * Code examples for Oracle Certified Professional (OCP) Exam 1Z0-819 * Java 11 SE, 2021. * Created by © Matko Soric. */ // #TAG1 public class GlobalNamescope { // how to produce output "Global:namescope" ? static String prefix = "Global:"; private String name = "namescope"; public static String getName() { return new GlobalNamescope().name; } public static void main(String[] args) { GlobalNamescope globalNamescope = new GlobalNamescope(); // System.out.println(GlobalNamescope.prefix + GlobalNamescope.name); // does not compile System.out.println(new GlobalNamescope().prefix + new GlobalNamescope().name); System.out.println(GlobalNamescope.prefix + GlobalNamescope.getName()); // System.out.println(GlobalNamescope.getName + prefix); // does not compile // System.out.println(prefix + GlobalNamescope.name); // does not compile // System.out.println(prefix + name); // does not compile } }
32.189189
113
0.607893
a84e1ad04a1e0f063b02c25bc673cd2c46a306dd
2,953
package cn.zhengcaiyun.idata.develop.dal.dao.integration; import java.sql.JDBCType; import java.util.Date; import javax.annotation.Generated; import org.mybatis.dynamic.sql.SqlColumn; import org.mybatis.dynamic.sql.SqlTable; public final class DSEntityMappingDynamicSqlSupport { @Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source Table: ite_ds_entity_mapping") public static final DSEntityMapping DS_ENTITY_MAPPING = new DSEntityMapping(); /** * Database Column Remarks: * 主键 */ @Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: ite_ds_entity_mapping.id") public static final SqlColumn<Long> id = DS_ENTITY_MAPPING.id; /** * Database Column Remarks: * 创建时间 */ @Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: ite_ds_entity_mapping.create_time") public static final SqlColumn<Date> createTime = DS_ENTITY_MAPPING.createTime; /** * Database Column Remarks: * 业务实体id */ @Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: ite_ds_entity_mapping.entity_id") public static final SqlColumn<Long> entityId = DS_ENTITY_MAPPING.entityId; /** * Database Column Remarks: * 环境 */ @Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: ite_ds_entity_mapping.environment") public static final SqlColumn<String> environment = DS_ENTITY_MAPPING.environment; /** * Database Column Remarks: * 业务实体type: workflow, task */ @Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: ite_ds_entity_mapping.ds_entity_type") public static final SqlColumn<String> dsEntityType = DS_ENTITY_MAPPING.dsEntityType; /** * Database Column Remarks: * ds 业务实体code */ @Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source field: ite_ds_entity_mapping.ds_entity_code") public static final SqlColumn<Long> dsEntityCode = DS_ENTITY_MAPPING.dsEntityCode; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", comments="Source Table: ite_ds_entity_mapping") public static final class DSEntityMapping extends SqlTable { public final SqlColumn<Long> id = column("id", JDBCType.BIGINT); public final SqlColumn<Date> createTime = column("create_time", JDBCType.TIMESTAMP); public final SqlColumn<Long> entityId = column("entity_id", JDBCType.BIGINT); public final SqlColumn<String> environment = column("environment", JDBCType.VARCHAR); public final SqlColumn<String> dsEntityType = column("ds_entity_type", JDBCType.VARCHAR); public final SqlColumn<Long> dsEntityCode = column("ds_entity_code", JDBCType.BIGINT); public DSEntityMapping() { super("ite_ds_entity_mapping"); } } }
40.452055
129
0.729089
370536adc2f025b7b436affe6752daf7cea9d3b2
1,085
package de.melanx.botanicalmachinery.network; import io.github.noeppi_noeppi.libx.network.PacketSerializer; import net.minecraft.network.PacketBuffer; import net.minecraft.util.math.BlockPos; public class ManaBatteryLockedSerializer implements PacketSerializer<ManaBatteryLockedSerializer.Message> { @Override public Class<Message> messageClass() { return Message.class; } @Override public void encode(Message msg, PacketBuffer buffer) { buffer.writeBlockPos(msg.pos); buffer.writeBoolean(msg.locked1); buffer.writeBoolean(msg.locked2); } @Override public Message decode(PacketBuffer buffer) { return new Message(buffer.readBlockPos(), buffer.readBoolean(), buffer.readBoolean()); } public static class Message { public Message(BlockPos pos, boolean locked1, boolean locked2) { this.pos = pos; this.locked1 = locked1; this.locked2 = locked2; } public BlockPos pos; public boolean locked1; public boolean locked2; } }
27.820513
107
0.685714
2106dcac74d0395c3c55ea54a2a2716f98d46d76
758
package UI; import javafx.application.Application; import javafx.geometry.Rectangle2D; import javafx.stage.Screen; public abstract class AdaptableWindowApplication extends Application { private static double getWidth(){ Rectangle2D rectangle2D = Screen.getPrimary().getVisualBounds(); return rectangle2D.getWidth(); } private static double getHeight(){ Rectangle2D rectangle2D = Screen.getPrimary().getVisualBounds(); return rectangle2D.getHeight(); } protected static double getPercentageWidth(double percentage){ return ((getWidth() / 100f) * percentage); } protected static double getPercentageHeight(double percentage){ return ((getHeight() / 100f) * percentage); } }
28.074074
72
0.712401
98e668da3eb19ef6c790ed5f8e0e3f9d947b45ba
291
package dw.cli.commands.itest; import dw.cli.Output; import dw.cli.itest.TestHelper; public class Test_TitleGetter extends TestHelper { @org.junit.Test public void getTitle() throws Exception{ Output output = runWithArguments("getTitle"); assertSuccess("test xmlrpc", output); } }
20.785714
50
0.762887
f6c8d8cb717b6b44c9c18394987c0d405822fc8d
4,994
package java.lang; import lejos.nxt.NXTEvent; import java.util.ArrayList; import lejos.util.Delay; /** * This is an internal system class that implements the system shutdown process. * Classes which require some form of cleanup when the program is about to exit * can register a system shutdown hook which will be run via this code when the * system shuts down. System shutdown can be triggered by one of the following * 1) A call to the exit function * 2) The last none daemon thread exiting * 3) A user generated shutdown interrupt (ENTER+ESCAPE) * Note: Some care has been taken to minimise the impact of this code on * programs that do not require shutdown hooks. In particular the event wait * thread is not created unless a shutdown hook is in place. This means that * the associated collection, and collection classes will not be loaded. * @author andy * */ class Shutdown { private final static int SHUTDOWN_EVENT = 1; private volatile static ShutdownThread singleton; //TODO running is only partly protected by synchronized(Shutdown.class){}, discuss with Andy private volatile static boolean running = false; private static int exitCode = 0; static class ShutdownThread extends Thread { private final NXTEvent event; private ArrayList<Thread> hooks = new ArrayList<Thread>(); private ShutdownThread() { this.setPriority(Thread.MAX_PRIORITY-1); event = NXTEvent.allocate(NXTEvent.SYSTEM, SHUTDOWN_EVENT, 1000); this.setDaemon(true); this.start(); } /** * This thread waits for the system shutdown event, and then proceeds to * start the actual hooks, it then waits for these hook threads to complete * before halting the program. */ @Override public void run() { // We wait to be told to shut the system down try { event.waitEvent(NXTEvent.WAIT_FOREVER); } catch (InterruptedException e) { // If we get interrupted just give up... event.free(); return; } // make sure we continue to run, even if other threads exit. setDaemon(false); running = true; // Call each of the hooks in turn for(int i = 0; i < hooks.size(); i++) hooks.get(i).start(); // and now wait for them to complete for(int i = 0; i < hooks.size(); i++) try { hooks.get(i).join(); } catch (InterruptedException e) { // ignore and retry i--; } // Now make the system exit halt(exitCode); } } private Shutdown() { //empty } /** * Terminate the application. Does not trigger the calling of shutdown hooks. */ public static native void halt(int code); /** * Tell the system that we want to shutdown. Calling this will trigger the running * of any shutdown hooks. If no hooks are installed the system will simply terminate. */ private static native void shutdown(); /** * Called to shutdown the system. If any shutdown hooks have been installed * these will be run before the system terminates. This function will never return. */ public static void shutdown(int code) { // If no singleton then no hooks, so simply exit if (singleton == null) halt(code); if (!running) { // Not already running the shutdown code, so go do it exitCode = code; shutdown(); } // Now wait for ever for the system to shut down Delay.msDelay(NXTEvent.WAIT_FOREVER); } /** * Install a shutdown hook. Can only be called before system shutdown has * started. * @param hook */ public static void addShutdownHook(Thread hook) { synchronized(Shutdown.class) { if (singleton == null) singleton = new ShutdownThread(); if (running || hook.isAlive()) throw(new IllegalStateException()); if (singleton.hooks.indexOf(hook) >= 0) throw(new IllegalArgumentException()); singleton.hooks.add(hook); } } /** * Remove a shutdown hook. * @param hook item to be removed * @return true iff the hook is actually removed */ public static boolean removeShutdownHook(Thread hook) { synchronized(Shutdown.class) { if (singleton == null) return false; if (running) throw(new IllegalStateException()); return singleton.hooks.remove(hook); } } }
32.219355
97
0.579696
44b9bdbc9057d387c79166bfd2a7e0b44b246af3
2,368
package ShadowSiren.cards; import IconsAddon.util.BlockModifierManager; import ShadowSiren.ShadowSirenMod; import ShadowSiren.blockTypes.IceBlock; import ShadowSiren.cards.abstractCards.AbstractIceCard; import ShadowSiren.cards.tempCards.IceShard; import ShadowSiren.characters.Vivian; import ShadowSiren.damageModifiers.AbstractVivianDamageModifier; import com.megacrit.cardcrawl.actions.common.GainBlockAction; import com.megacrit.cardcrawl.actions.common.MakeTempCardInHandAction; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.monsters.AbstractMonster; import static ShadowSiren.ShadowSirenMod.makeCardPath; public class SnowFort extends AbstractIceCard { // TEXT DECLARATION public static final String ID = ShadowSirenMod.makeID(SnowFort.class.getSimpleName()); public static final String IMG = makeCardPath("PlaceholderSkill.png"); // Setting the image as as easy as can possibly be now. You just need to provide the image name // /TEXT DECLARATION/ // STAT DECLARATION private static final CardRarity RARITY = CardRarity.COMMON; private static final CardTarget TARGET = CardTarget.SELF; private static final CardType TYPE = CardType.SKILL; public static final CardColor COLOR = Vivian.Enums.VOODOO_CARD_COLOR; private static final int COST = 2; private static final int BLOCK = 12; private static final int UPGRADE_PLUS_BLOCK = 4; // /STAT DECLARATION/ public SnowFort() { super(ID, IMG, COST, TYPE, COLOR, RARITY, TARGET, AbstractVivianDamageModifier.TipType.DAMAGE_AND_BLOCK); baseBlock = block = BLOCK; cardsToPreview = new IceShard(); BlockModifierManager.addModifier(this, new IceBlock()); } // Actions the card should do. @Override public void use(AbstractPlayer p, AbstractMonster m) { this.addToBot(new GainBlockAction(p, block)); this.addToBot(new MakeTempCardInHandAction(cardsToPreview.makeStatEquivalentCopy())); } // Upgraded stats. @Override public void upgrade() { if (!upgraded) { upgradeName(); //upgradeBaseCost(UPGRADE_COST); upgradeBlock(UPGRADE_PLUS_BLOCK); cardsToPreview.upgrade(); rawDescription = UPGRADE_DESCRIPTION; initializeDescription(); } } }
34.318841
113
0.733953
ee46650e7ef7123fa76c4a9ad163dc39a4a26a80
1,970
package tonyusamples.block; import tonyu.kernel.TGL; import tonyu.kernel.TonyuPage; import tonyu.kernel.TonyuSecretChar; import tonyu.kernel.TonyuTextBitmap; public class Monitor extends TonyuSecretChar { int blc; private int xx; private int yy; private int pa; private int i; private int loop = 0, loop2 = 0; TonyuPage nextPage; private TonyuTextBitmap textBlockCnt, textGameOver, textClear; public Monitor(float x, float y) { super(x, y); } @Override public void onAppear() { // 面全体にブロックがいくつあるか数える。その数をblcに入れる blc=0; xx=0; while (xx<TGL.map.getWidth()) { yy=0; while (yy<TGL.map.getHeight()) { pa = TGL.map.get(xx,yy) ; if (pa>=GLB.pat_block+1 && pa<=GLB.pat_block+4) blc+=1; yy+=1; } xx+=1; } GLB.ballC = 1; textBlockCnt = new TonyuTextBitmap(); textGameOver = new TonyuTextBitmap(); textClear = new TonyuTextBitmap(); } @Override public void loop() { if (loop2 == 0) { // ブロックの数が0になるか、ボールが0になるまで待機。 if (blc > 0 && GLB.ballC > 0) { loop = 1; } else { loop = 0; loop2 = 1; i = 0; } if (loop == 1) { //drawText(0, 0, intToStr(blc), color(255,0,0), 20); textBlockCnt.drawText(0, 0, intToStr(blc), color(255,0,0), 20); GLB.ballC=0; return; } } if (loop2 == 1) { if (i < 60) { loop = 1; } else { // 次の面に移動する(gameoverならタイトルに) TGL.projectManager.loadPage(nextPage); loop = 0; } if (loop == 1) { // ブロックが0ならクリア if (blc<=0) { //drawText(x, y, "Clear!", color(255,255,255), 20); textClear.drawText(x, y, "Clear!", color(255,255,255), 20); } // ボール0ならゲームオーバー if (GLB.ballC<=0) { //drawText(x, y, "Game Over", color(255,255,0), 20); textGameOver.drawText(x, y, "Game Over", color(255,255,0), 20); nextPage = GLB.page_title; } i+=1; } } } @Override public void onRelease() { textBlockCnt.delete(); textGameOver.delete(); textClear.delete(); } }
20.736842
68
0.600508
39ac2e9cd253999d926040d5d4e0e0d60df6ea51
3,076
/* * Copyright (C) 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.twitter.sdk.android.tweetui; import android.graphics.drawable.Drawable; import android.widget.ImageView; import com.twitter.sdk.android.core.Session; import com.twitter.sdk.android.core.TwitterApiClient; import com.twitter.sdk.android.core.services.StatusesService; import com.squareup.picasso.Picasso; import com.squareup.picasso.RequestCreator; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; public final class MockUtils { private MockUtils() {} public static Picasso mockPicasso(Picasso picasso, RequestCreator requestCreator) { when(picasso.load(anyString())).thenReturn(requestCreator); when(picasso.load(anyInt())).thenReturn(requestCreator); when(requestCreator.centerCrop()).thenReturn(requestCreator); when(requestCreator.fit()).thenReturn(requestCreator); when(requestCreator.placeholder(any(Drawable.class))) .thenReturn(requestCreator); doNothing().when(requestCreator).into(any(ImageView.class)); return picasso; } public static void mockExecutorService(ExecutorService executorService) { final ArgumentCaptor<Runnable> runableArgument = ArgumentCaptor.forClass(Runnable.class); when(executorService.submit(runableArgument.capture())).thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; } } ); } public static void mockStatusesServiceClient(TwitterApiClient apiClient, StatusesService statusesService) { when(apiClient.getStatusesService()).thenReturn(statusesService); } public static void mockClients(ConcurrentHashMap<Session, TwitterApiClient> clients, TwitterApiClient apiClient) { when(clients.get(anyObject())).thenReturn(apiClient); when(clients.contains(anyObject())).thenReturn(true); } }
37.060241
88
0.71619
7adb06c6b48743eb6ff689245ae1b1ed8def918e
589
package com.encryptlang.v1.node; import com.encryptlang.v1.env.Environment; import java.util.ArrayList; import java.util.List; /** * Created by jianjunwei on 2017/7/10. */ public class ListNode implements Node { private List<Node> nodeList = new ArrayList<>(); public boolean addNode(Node n){ return this.nodeList.add(n); } @Override public Object[] eval(Environment env) { List<Object> evalParm = new ArrayList<>(); for(Node node :nodeList){ evalParm.add(node.eval(env)); } return evalParm.toArray(); } }
19
53
0.640068
8d177f64c58c7122c35d03ac6a1d59435ac6f8ce
2,085
package akka.example.tcp; import akka.actor.AbstractActor; import akka.actor.ActorRef; import akka.actor.Props; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.io.Tcp; import akka.io.TcpMessage; import java.net.InetSocketAddress; public class ServerActor extends AbstractActor { private final ActorRef tcpManager = Tcp.get(getContext().system()).getManager(); private LoggingAdapter log = Logging.getLogger(getContext().system(), this); private String host = "127.0.0.1"; private int port = 2020; @Override public Receive createReceive() { return receiveBuilder() .matchEquals( "start", message -> { InetSocketAddress endpoint = new InetSocketAddress(host, port); Tcp.Command cmd = TcpMessage.bind(getSelf(), endpoint, 10); tcpManager.tell(cmd, getSelf()); }) .match( Tcp.Bound.class, bound -> { InetSocketAddress addr = bound.localAddress(); log.info("Bound to {}:{}", addr.getHostString(), addr.getPort()); }) .match( Tcp.Connected.class, connected -> { InetSocketAddress remote = ((Tcp.Connected) connected) .remoteAddress(); log.info("A new connection from {}:{}", remote.getHostString(), remote.getPort()); ActorRef handlerActor = getContext().actorOf( Props.create(HandlerActor.class, remote, getSender())); Tcp.Command cmd = TcpMessage.register(handlerActor); getSender().tell(cmd, getSelf()); }) .build(); } public ServerActor() { } }
39.339623
93
0.493525
cf07cb9fe046ff92f4214d114a10d984e7470c67
19,931
package org.drools.base.evaluators; /* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.drools.base.BaseEvaluator; import org.drools.base.ValueType; import org.drools.common.InternalWorkingMemory; import org.drools.rule.VariableRestriction.DoubleVariableContextEntry; import org.drools.rule.VariableRestriction.VariableContextEntry; import org.drools.spi.Evaluator; import org.drools.spi.Extractor; import org.drools.spi.FieldValue; public class DoubleFactory implements EvaluatorFactory { private static final long serialVersionUID = 400L; private static EvaluatorFactory INSTANCE = new DoubleFactory(); private DoubleFactory() { } public static EvaluatorFactory getInstance() { if ( DoubleFactory.INSTANCE == null ) { DoubleFactory.INSTANCE = new DoubleFactory(); } return DoubleFactory.INSTANCE; } public Evaluator getEvaluator(final Operator operator) { if ( operator == Operator.EQUAL ) { return DoubleEqualEvaluator.INSTANCE; } else if ( operator == Operator.NOT_EQUAL ) { return DoubleNotEqualEvaluator.INSTANCE; } else if ( operator == Operator.LESS ) { return DoubleLessEvaluator.INSTANCE; } else if ( operator == Operator.LESS_OR_EQUAL ) { return DoubleLessOrEqualEvaluator.INSTANCE; } else if ( operator == Operator.GREATER ) { return DoubleGreaterEvaluator.INSTANCE; } else if ( operator == Operator.GREATER_OR_EQUAL ) { return DoubleGreaterOrEqualEvaluator.INSTANCE; } else if ( operator == Operator.MEMBEROF ) { return DoubleMemberOfEvaluator.INSTANCE; } else if ( operator == Operator.NOTMEMBEROF ) { return DoubleNotMemberOfEvaluator.INSTANCE; } else { throw new RuntimeException( "Operator '" + operator + "' does not exist for DoubleEvaluator" ); } } static class DoubleEqualEvaluator extends BaseEvaluator { /** * */ private static final long serialVersionUID = 400L; public final static Evaluator INSTANCE = new DoubleEqualEvaluator(); private DoubleEqualEvaluator() { super( ValueType.PDOUBLE_TYPE, Operator.EQUAL ); } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor, final Object object1, final FieldValue object2) { if ( extractor.isNullValue( workingMemory, object1 ) ) { return object2.isNull(); } else if ( object2.isNull() ) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor.getDoubleValue( workingMemory, object1 ) == object2.getDoubleValue(); } public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object left) { if ( context.declaration.getExtractor().isNullValue( workingMemory, left ) ) { return context.isRightNull(); } else if ( context.isRightNull() ) { return false; } // TODO: we are not handling delta right now... maybe we should return context.declaration.getExtractor().getDoubleValue( workingMemory, left ) == ((DoubleVariableContextEntry) context).right; } public boolean evaluateCachedLeft(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object right) { if ( context.extractor.isNullValue( workingMemory, right )) { return context.isLeftNull(); } else if ( context.isLeftNull() ) { return false; } // TODO: we are not handling delta right now... maybe we should return ((DoubleVariableContextEntry) context).left == context.extractor.getDoubleValue( workingMemory, right ); } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor1, final Object object1, final Extractor extractor2, final Object object2) { if (extractor1.isNullValue( workingMemory, object1 )) { return extractor2.isNullValue( workingMemory, object2 ); } else if (extractor2.isNullValue( workingMemory, object2 )) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor1.getDoubleValue( workingMemory, object1 ) == extractor2.getDoubleValue( workingMemory, object2 ); } public String toString() { return "Double =="; } } static class DoubleNotEqualEvaluator extends BaseEvaluator { /** * */ private static final long serialVersionUID = 400L; public final static Evaluator INSTANCE = new DoubleNotEqualEvaluator(); private DoubleNotEqualEvaluator() { super( ValueType.PDOUBLE_TYPE, Operator.NOT_EQUAL ); } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor, final Object object1, final FieldValue object2) { if ( extractor.isNullValue( workingMemory, object1 ) ) { return !object2.isNull(); } else if ( object2.isNull() ) { return true; } // TODO: we are not handling delta right now... maybe we should return extractor.getDoubleValue( workingMemory, object1 ) != object2.getDoubleValue(); } public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object left) { if ( context.declaration.getExtractor().isNullValue( workingMemory, left ) ) { return !context.isRightNull(); } else if ( context.isRightNull() ) { return true; } // TODO: we are not handling delta right now... maybe we should return context.declaration.getExtractor().getDoubleValue( workingMemory, left ) != ((DoubleVariableContextEntry) context).right; } public boolean evaluateCachedLeft(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object right) { if ( context.extractor.isNullValue( workingMemory, right )) { return !context.isLeftNull(); } else if ( context.isLeftNull() ) { return true; } // TODO: we are not handling delta right now... maybe we should return ((DoubleVariableContextEntry) context).left != context.extractor.getDoubleValue( workingMemory, right ); } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor1, final Object object1, final Extractor extractor2, final Object object2) { if (extractor1.isNullValue( workingMemory, object1 )) { return !extractor2.isNullValue( workingMemory, object2 ); } else if (extractor2.isNullValue( workingMemory, object2 )) { return true; } // TODO: we are not handling delta right now... maybe we should return extractor1.getDoubleValue( workingMemory, object1 ) != extractor2.getDoubleValue( workingMemory, object2 ); } public String toString() { return "Double !="; } } static class DoubleLessEvaluator extends BaseEvaluator { /** * */ private static final long serialVersionUID = 400L; public final static Evaluator INSTANCE = new DoubleLessEvaluator(); private DoubleLessEvaluator() { super( ValueType.PDOUBLE_TYPE, Operator.LESS ); } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor, final Object object1, final FieldValue object2) { if( extractor.isNullValue( workingMemory, object1 ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor.getDoubleValue( workingMemory, object1 ) < object2.getDoubleValue(); } public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object left) { if( context.rightNull ) { return false; } // TODO: we are not handling delta right now... maybe we should return ((DoubleVariableContextEntry) context).right < context.declaration.getExtractor().getDoubleValue( workingMemory, left ); } public boolean evaluateCachedLeft(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object right) { if( context.extractor.isNullValue( workingMemory, right ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return context.extractor.getDoubleValue( workingMemory, right ) < ((DoubleVariableContextEntry) context).left; } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor1, final Object object1, final Extractor extractor2, final Object object2) { if( extractor1.isNullValue( workingMemory, object1 ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor1.getDoubleValue( workingMemory, object1 ) < extractor2.getDoubleValue( workingMemory, object2 ); } public String toString() { return "Double <"; } } static class DoubleLessOrEqualEvaluator extends BaseEvaluator { /** * */ private static final long serialVersionUID = 400L; public final static Evaluator INSTANCE = new DoubleLessOrEqualEvaluator(); private DoubleLessOrEqualEvaluator() { super( ValueType.PDOUBLE_TYPE, Operator.LESS_OR_EQUAL ); } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor, final Object object1, final FieldValue object2) { if( extractor.isNullValue( workingMemory, object1 ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor.getDoubleValue( workingMemory, object1 ) <= object2.getDoubleValue(); } public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object left) { if( context.rightNull ) { return false; } // TODO: we are not handling delta right now... maybe we should return ((DoubleVariableContextEntry) context).right <= context.declaration.getExtractor().getDoubleValue( workingMemory, left ); } public boolean evaluateCachedLeft(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object right) { if( context.extractor.isNullValue( workingMemory, right ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return context.extractor.getDoubleValue( workingMemory, right ) <= ((DoubleVariableContextEntry) context).left; } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor1, final Object object1, final Extractor extractor2, final Object object2) { if( extractor1.isNullValue( workingMemory, object1 ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor1.getDoubleValue( workingMemory, object1 ) <= extractor2.getDoubleValue( workingMemory, object2 ); } public String toString() { return "Double <="; } } static class DoubleGreaterEvaluator extends BaseEvaluator { /** * */ private static final long serialVersionUID = 400L; public final static Evaluator INSTANCE = new DoubleGreaterEvaluator(); private DoubleGreaterEvaluator() { super( ValueType.PDOUBLE_TYPE, Operator.GREATER ); } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor, final Object object1, final FieldValue object2) { if( extractor.isNullValue( workingMemory, object1 ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor.getDoubleValue( workingMemory, object1 ) > object2.getDoubleValue(); } public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object left) { if( context.rightNull ) { return false; } // TODO: we are not handling delta right now... maybe we should return ((DoubleVariableContextEntry) context).right > context.declaration.getExtractor().getDoubleValue( workingMemory, left ); } public boolean evaluateCachedLeft(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object right) { if( context.extractor.isNullValue( workingMemory, right ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return context.extractor.getDoubleValue( workingMemory, right ) > ((DoubleVariableContextEntry) context).left; } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor1, final Object object1, final Extractor extractor2, final Object object2) { if( extractor1.isNullValue( workingMemory, object1 ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor1.getDoubleValue( workingMemory, object1 ) > extractor2.getDoubleValue( workingMemory, object2 ); } public String toString() { return "Double >"; } } static class DoubleGreaterOrEqualEvaluator extends BaseEvaluator { /** * */ private static final long serialVersionUID = 400L; private final static Evaluator INSTANCE = new DoubleGreaterOrEqualEvaluator(); private DoubleGreaterOrEqualEvaluator() { super( ValueType.PDOUBLE_TYPE, Operator.GREATER_OR_EQUAL ); } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor, final Object object1, final FieldValue object2) { if( extractor.isNullValue( workingMemory, object1 ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor.getDoubleValue( workingMemory, object1 ) >= object2.getDoubleValue(); } public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object left) { if( context.rightNull ) { return false; } // TODO: we are not handling delta right now... maybe we should return ((DoubleVariableContextEntry) context).right >= context.declaration.getExtractor().getDoubleValue( workingMemory, left ); } public boolean evaluateCachedLeft(InternalWorkingMemory workingMemory, final VariableContextEntry context, final Object right) { if( context.extractor.isNullValue( workingMemory, right ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return context.extractor.getDoubleValue( workingMemory, right ) >= ((DoubleVariableContextEntry) context).left; } public boolean evaluate(InternalWorkingMemory workingMemory, final Extractor extractor1, final Object object1, final Extractor extractor2, final Object object2) { if( extractor1.isNullValue( workingMemory, object1 ) ) { return false; } // TODO: we are not handling delta right now... maybe we should return extractor1.getDoubleValue( workingMemory, object1 ) >= extractor2.getDoubleValue( workingMemory, object2 ); } public String toString() { return "Double >="; } } static class DoubleMemberOfEvaluator extends BaseMemberOfEvaluator { private static final long serialVersionUID = 400L; public final static Evaluator INSTANCE = new DoubleMemberOfEvaluator(); private DoubleMemberOfEvaluator() { super( ValueType.PDOUBLE_TYPE, Operator.MEMBEROF ); } public String toString() { return "Double memberOf"; } } static class DoubleNotMemberOfEvaluator extends BaseNotMemberOfEvaluator { private static final long serialVersionUID = 400L; public final static Evaluator INSTANCE = new DoubleNotMemberOfEvaluator(); private DoubleNotMemberOfEvaluator() { super( ValueType.PDOUBLE_TYPE, Operator.NOTMEMBEROF ); } public String toString() { return "Double not memberOf"; } } }
43.708333
140
0.588681
3b6a0e94ce42fdc20d6a29129e5ede1d4f99e734
870
package com.bluestream.app; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; public class TabPagerAdapter extends FragmentStatePagerAdapter { String [] tabarray =new String[]{"Home","Category"}; Integer tabnumber = 2; public TabPagerAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return tabarray[position]; } @Override public Fragment getItem(int position) { switch (position) { case 0: One one = new One(); return one; case 1: Two two = new Two(); return two; } return null; } @Override public int getCount() { return tabnumber; } }
20.714286
64
0.606897
3e2a45281ed5850e87149ad0422229c9ef0752a5
4,608
package org.autogui.swing.mapping; import org.autogui.base.mapping.GuiMappingContext; import org.autogui.base.mapping.GuiReprValue; import org.autogui.base.type.GuiUpdatedValue; import org.autogui.swing.util.SwingDeferredRunner; import javax.swing.*; import java.util.concurrent.Future; import java.util.function.Consumer; import java.util.function.Supplier; /** * a GUI component for a property holding a {@link JComponent} * <pre> * private JComponent comp; * &#64;GuiIncluded public JComponent getComp() { * if (comp == null) { * comp = new JLabel("hello"); * } * return comp; * } * </pre> * <p> * the class executes obtaining and updating a target value under the event dispatching thread * via {@link SwingDeferredRunner}. * <p> * For the case of updating from GUI, * an UI event (in the event thread) -&gt; * executeContextTask * and it observes that {@link #isTaskRunnerUsedFor(Supplier)} returns false and directly invoke the given task * -&gt; * updateFromGui -&gt; update -&gt; * {@link SwingDeferredRunner#run(SwingDeferredRunner.Task)} with super.update (it directly invoke the task as in the event thread) * -&gt; the method of the target object is invoked under the event thread. */ public class GuiReprEmbeddedComponent extends GuiReprValue { @Override public boolean matchValueType(Class<?> cls) { return JComponent.class.isAssignableFrom(cls); } @Override public boolean isTaskRunnerUsedFor(Supplier<?> task) { return false; } @Override public GuiUpdatedValue getValue(GuiMappingContext context, GuiMappingContext.GuiSourceValue parentSource, ObjectSpecifier specifier, GuiMappingContext.GuiSourceValue prev) throws Throwable { Object v = SwingDeferredRunner.run(() -> super.getValue(context, parentSource, specifier, prev)); if (v instanceof GuiUpdatedValue) { return (GuiUpdatedValue) v; } else { return GuiUpdatedValue.of(v); } } @Override public Object update(GuiMappingContext context, GuiMappingContext.GuiSourceValue parentSource, Object newValue, ObjectSpecifier specifier) { try { return SwingDeferredRunner.run(() -> super.update(context, parentSource, newValue, specifier)); } catch (Throwable ex) { throw new RuntimeException(ex); } } /** * @param context the context of the repr. * @param value the current value * @return obtains a {@link JComponent} value, or if the value is a deferred future, * then get the done value or null if it is not completed. * To support the delayed completion, use {@link #toUpdateValue(GuiMappingContext, Object, Consumer)} instead. */ @Override public JComponent toUpdateValue(GuiMappingContext context, Object value) { return toUpdateValue(context, value, null); } public JComponent toUpdateValue(GuiMappingContext context, Object value, Consumer<JComponent> delayed) { if (value instanceof SwingDeferredRunner.TaskResultFuture) { Future<Object> f = ((SwingDeferredRunner.TaskResultFuture) value).getFuture(); if (f.isDone()) { try { value = f.get(); } catch (Exception ex) { return null; } } else { if (delayed != null) { SwingDeferredRunner.getDefaultService().execute(() -> { try { delayed.accept(toUpdateValue(context, f.get())); } catch (Exception ex) { throw new RuntimeException(ex); } }); } return null; } } if (value instanceof GuiUpdatedValue) { return toUpdateValue(context, ((GuiUpdatedValue) value).getValue(), delayed); } else if (value instanceof JComponent) { return (JComponent) value; } else { return null; } } @Override public Object toJson(GuiMappingContext context, Object source) { return null; } @Override public Object fromJson(GuiMappingContext context, Object target, Object json) { return target; } @Override public boolean isHistoryValueSupported() { return false; } }
36.283465
139
0.610243
5912c12388af1581621c1a0fab4f7dff8a250475
633
/* * Created on 23.10.2006 */ package jeliot.mcode; import java.io.BufferedReader; import java.io.PrintWriter; /** * It is made sure that all the registered MCodePreProcessors will execute their interpretation before * the primary MCInterpreter is processing the same line of MCode thus the implementations of this interface * <b>should not</b> do any time consuming computations. * * @author nmyller */ public interface MCodePreProcessor { public PrintWriter getMCodeInputWriter(); public BufferedReader getMCodeOutputReader(); public void closeMCodeOutputReader(); }
25.32
109
0.71722
6266fe1f534e52ec5a02ab026644cc3ca5daaa12
1,520
package nl.homeserver.energie.opgenomenvermogen; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import nl.homeserver.cache.DailyCacheWarmer; import nl.homeserver.cache.InitialCacheWarmer; import org.springframework.stereotype.Component; import java.time.Clock; import java.time.LocalDate; import java.util.List; import static java.time.LocalDate.now; import static java.util.concurrent.TimeUnit.MINUTES; import static nl.homeserver.DatePeriod.aPeriodWithToDate; @Slf4j @Component @RequiredArgsConstructor class OpgenomenVermogenCacheWarmer implements InitialCacheWarmer, DailyCacheWarmer { private static final long DEFAULT_SUB_PERIOD_LENGTH_IN_SECONDS = MINUTES.toMillis(3); private final OpgenomenVermogenController opgenomenVermogenController; private final Clock clock; @Override public void warmupInitialCache() { log.info("Warmup of cache opgenomenVermogenHistory"); final LocalDate today = LocalDate.now(clock); aPeriodWithToDate(today.minusDays(14), today).getDays().forEach(this::warmupCacheForDay); } @Override public void warmupDailyCache() { log.info("Warmup of cache opgenomenVermogenHistory"); final LocalDate yesterday = now(clock).minusDays(1); warmupCacheForDay(yesterday); } private void warmupCacheForDay(final LocalDate day) { opgenomenVermogenController.getOpgenomenVermogenHistory( day, day.plusDays(1), DEFAULT_SUB_PERIOD_LENGTH_IN_SECONDS); } }
33.043478
97
0.774342
4ff5b9ba199a6807221e7401144d411db1c8a72b
1,749
package ThinkingInJava.zAssistant.javaiosystem; import java.io.*; import java.util.ArrayList; import java.util.List; import static ThinkingInJava.zUtils.Print.*; class House implements Serializable { } class Animal implements Serializable { private String name; private House preferredHouse; Animal(String nm, House h) { name = nm; preferredHouse = h; } public String toString() { return name + "[" + super.toString() + "], " + preferredHouse + "\n"; } } public class MyWorld { public static void main(String[] args) throws IOException, ClassNotFoundException { House house = new House(); List<Animal> animals = new ArrayList<>(); animals.add(new Animal("Bosco the dog", house)); animals.add(new Animal("Ralph the hamster", house)); animals.add(new Animal("Molly the cat", house)); print("animals: " + animals); ByteArrayOutputStream buf1 = new ByteArrayOutputStream(); ObjectOutputStream o1 = new ObjectOutputStream(buf1); o1.writeObject(animals); o1.writeObject(animals); ByteArrayOutputStream buf2 = new ByteArrayOutputStream(); ObjectOutputStream o2 = new ObjectOutputStream(buf2); o2.writeObject(animals); ObjectInputStream in1 = new ObjectInputStream(new ByteArrayInputStream(buf1.toByteArray())); ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(buf2.toByteArray())); List animals1 = (List) in1.readObject(), animals2 = (List) in1.readObject(), animals3 = (List) in2.readObject(); print("animals1: " + animals1); print("animals2: " + animals2); //animals1和animals2地址相同; print("animals3: " + animals3); } }
38.021739
120
0.668382
15d12a2eb88c20c52b4e0a2234888201efb6ae90
992
/* * @(#)TestUrlUtils.java 1.0 Nov 2, 2016 * Copyright 2016 by GNU Lesser General Public License (LGPL). All rights reserved. */ package org.nlh4j.util; import java.io.Serializable; import org.junit.Test; /** * Test class {@link UrlUtils} * * @author Hai Nguyen (hainguyenjc@gmail.com) * */ public final class TestUrlUtils implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = 1L; /** * Test {@link UrlUtils#isUrlVaid(String)} */ @Test public void testUrl1() { String url = "http://localhost:8080/isev"; if (UrlUtils.isUrlVaid(url)) { System.out.println("VALID: " + url); } else { System.out.println("INVALID: " + url); } url = "http://127.0.0.1:8080/isev"; if (UrlUtils.isUrlVaid(url)) { System.out.println("VALID: " + url); } else { System.out.println("INVALID: " + url); } } }
23.069767
83
0.573589
7743b76bcaed94833d791717789d4c72691b1313
3,048
package org.omegabyte.gaboom.transforms; import org.apache.beam.runners.dataflow.repackaged.com.google.common.collect.ImmutableList; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.util.SerializableUtils; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView; import org.omegabyte.gaboom.BaseItem; import org.omegabyte.gaboom.Individual; import org.omegabyte.gaboom.Individuals; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; public class Populate { public abstract static class PopulateFn<GenomeT extends Serializable> extends DoFn<BaseItem, Individuals<GenomeT>> { private int popSize = 1; public void setPopSize(int popSize) { this.popSize = popSize; } public abstract GenomeT makeGenome(ProcessContext context, Random random); @ProcessElement public void processElement(ProcessContext c) { BaseItem baseItem = c.element(); Random rng = baseItem.getRandomGenerator(); Individuals<GenomeT> individuals = new Individuals<>(rng.nextLong()); for (int i = 0; i < popSize; i++) { GenomeT genome = makeGenome(c, rng); individuals.getIndividuals().add(new Individual<>(rng, genome)); } c.output(individuals); } } public static class PopulateTransform<GenomeT extends Serializable> extends PTransform<PCollection<BaseItem>, PCollection<Individuals<GenomeT>>> { private final PopulateFn<GenomeT> fn; private final List<PCollectionView<?>> sideInputs; public PopulateTransform(PopulateFn<GenomeT> fn, List<PCollectionView<?>> sideInputs) { this.fn = SerializableUtils.clone(fn); this.sideInputs = sideInputs; } public PopulateTransform<GenomeT> withSideInputs(PCollectionView... sideInputs) { return this.withSideInputs((Iterable) Arrays.asList(sideInputs)); } public PopulateTransform<GenomeT> withSideInputs(Iterable<? extends PCollectionView<?>> sideInputs) { List list = ImmutableList.builder().addAll(this.sideInputs).addAll(sideInputs).build(); return new PopulateTransform<>(fn, list); } public PopulateTransform<GenomeT> withPopSize(int popSize) { PopulateTransform pt = new PopulateTransform<>(fn, sideInputs); pt.fn.setPopSize(popSize); return pt; } @Override public PCollection<Individuals<GenomeT>> expand(PCollection<BaseItem> input) { return input.apply(ParDo.of(fn).withSideInputs(sideInputs)); } } public static <GenomeT extends Serializable> PopulateTransform<GenomeT> as(PopulateFn<GenomeT> fn) { return new PopulateTransform<>(fn, Collections.emptyList()); } }
39.076923
150
0.689304
771b9940ce213ab3dfcc73d31b34227df7563e07
33,160
package com.kcchen.drawingpdf; import android.Manifest; import android.content.pm.PackageManager; import android.net.Uri; import android.util.Log; import com.artifex.mupdf.fitz.Document; import com.artifex.mupdf.fitz.PDFDocument; import com.artifex.mupdf.fitz.Page; import com.artifex.mupdf.fitz.Rect; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PermissionHelper; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; // import java.io.File; /** * DrawingPDF is a PhoneGap plugin that bridges Android intents and web * applications: * <p> * 1. web apps can spawn intents that call native Android applications. 2. * (after setting up correct intent filters for PhoneGap applications), Android * intents can be handled by PhoneGap web applications. * * @author boris@borismus.com */ public class DrawingPDF extends CordovaPlugin { private static final String TAG = DrawingPDF.class.getSimpleName(); private static final int READ_EXTERNAL_REQUEST_CODE = 0; private static final int WRITE_EXTERNAL_REQUEST_CODE = 1; private static final int PERMISSION_DENIED_ERROR = 20; private CallbackContext openCallbackContext = null; private CallbackContext closeCallbackContext = null; private Uri pdfUri; private PDFDocument pdfDoc; private Document doc; private Document svgDoc; private String closeFilepath; /** * @param action The action to execute. * @param args The exec() arguments. * @param callbackContext The callback context used when calling back into JavaScript. * @return true: comsume false: reject if using Promise */ @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { try { Log.w(TAG, "execute " + "action:" + action + " args:" + args + " callbackContext:" + callbackContext); // openPDF: (url: string) => Promise<OpenPDFInfo>; // insertBase64Image: (imageBase64Url: string) => Promise<any>; // insertBase64SVG: (svgBase64Url: string) => Promise<any>; // insertImagePath: (path: string, pageIdx: number, x: number, y: number, w?: number, h?: number) => Promise<any>; // insertSVGPath: (path: string, pageIdx: number, x: number, y: number, w?: number, h?: number) => Promise<any>; // getTotalPages: () => Promise<any>; // closePDF: () => Promise<any>; if (action.equals("openPDF")) { String pdfPath = args.getString(0); if (pdfPath == null) { callbackContext.error("missing pdf file."); return true; } pdfUri = Uri.parse(pdfPath); if(pdfUri == null){ pdfUri = Uri.parse(EscapeUtils.encodeURIComponent(pdfPath)); } if (!PermissionHelper.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { openCallbackContext = callbackContext; PermissionHelper.requestPermission(this, READ_EXTERNAL_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE); } else { openPDF(callbackContext); } return true; } else if (action.equals("insertBase64Image")) { return true; } else if (action.equals("insertBase64SVG")) { return true; } else if (action.equals("insertImagePath")) { String imgFile = args.getString(0); int pageIdx = args.getInt(1); int x = args.getInt(2); int y = args.getInt(3); int w = args.getInt(4); int h = args.getInt(5); insertImagePath(callbackContext, imgFile, pageIdx, x, y, w, h); return true; } else if (action.equals("insertSVGPath")) { return true; } else if (action.equals("openPDFforExport")) { String filepath = (args.getString(0) == null) ? "" : args.getString(0); String password = (args.getString(1) == null) ? "" : args.getString(1); int resolution = args.getInt(2); int timeout = args.getInt(3); timeout = timeout == 9999 ? -1 : timeout; if (filepath.isEmpty()) { callbackContext.error("> openPDFforExport missing pdf file."); return true; } if (!PermissionHelper.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { openCallbackContext = callbackContext; PermissionHelper.requestPermission(this, READ_EXTERNAL_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE); } else { openPDFforExport(callbackContext, filepath, password, resolution, timeout); } return true; } else if (action.equals("getPDFforExportDimension")) { int pageNumber = args.getInt(0); getDimension(callbackContext, pageNumber); return true; } else if (action.equals("getPDFforExportSVG")) { int pageNumber = args.getInt(0); String filepath = (args.getString(1) == null) ? "" : args.getString(1); int resolution = args.getInt(2); getPDFforExportSVG(callbackContext, pageNumber, filepath, resolution); return true; } else if (action.equals("getPDFforExportPNG")) { int pageNumber = args.getInt(0); String filepath = (args.getString(1) == null) ? "" : args.getString(1); int resolution = args.getInt(2); getPDFforExportPNG(callbackContext, pageNumber, filepath, resolution); return true; } else if (action.equals("setPNGPathFullForExport")) { String imgFile = args.getString(0); int pageIdx = args.getInt(1); int x = args.getInt(2); int y = args.getInt(3); int w = args.getInt(4); int h = args.getInt(5); setPNGPathFullForExport(callbackContext, imgFile, pageIdx, x, y, w, h); return true; } else if (action.equals("getPDFforExportTotalPages")) { getPDFforExportTotalPages(callbackContext); return true; } else if (action.equals("closePDFforExport")) { closeFilepath = (args.getString(0) == null) ? "" : args.getString(0); if (!PermissionHelper.hasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { closeCallbackContext = callbackContext; PermissionHelper.requestPermission(this, WRITE_EXTERNAL_REQUEST_CODE, Manifest.permission.WRITE_EXTERNAL_STORAGE); } else { closePDFforExport(callbackContext); } return true; } else if (action.equals("getTotalPages")) { getTotalPages(callbackContext); return true; } else if (action.equals("closePDF")) { closeFilepath = (args.getString(0) == null) ? "" : args.getString(0); if (!PermissionHelper.hasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { closeCallbackContext = callbackContext; PermissionHelper.requestPermission(this, WRITE_EXTERNAL_REQUEST_CODE, Manifest.permission.WRITE_EXTERNAL_STORAGE); } else { closePDF(callbackContext); } return true; } //return new PluginResult(PluginResult.Status.INVALID_ACTION); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } catch (JSONException e) { e.printStackTrace(); String errorMessage = e.getMessage(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, errorMessage)); return false; } } public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { for (int r : grantResults) { if (r == PackageManager.PERMISSION_DENIED) { if (openCallbackContext != null) { openCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR)); openCallbackContext = null; } else if (closeCallbackContext != null) { closeCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR)); closeCallbackContext = null; } return; } } switch (requestCode) { case READ_EXTERNAL_REQUEST_CODE: openPDF(openCallbackContext); break; case WRITE_EXTERNAL_REQUEST_CODE: closePDF(closeCallbackContext); break; } } private void openPDFforExport(final CallbackContext callbackContext, final String filepath, final String password, final int resolution, final int timeout) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult = null; String file = ((filepath == null) ? "" : filepath); String svg = null; Uri importFile; String error = null; if (file.isEmpty()) { svgDoc = null; error = "openPDFforExport no input path !!!"; } else { importFile = Uri.parse(file); Log.d(TAG, "path:" + importFile.getPath()); File importedFile = new File(importFile.getPath()); if (importedFile.exists() && importedFile.length() != 0 && importedFile.canRead()) { svgDoc = Document.openDocumentForExport(importedFile.getPath(), password, resolution, timeout); } else { svgDoc = null; error = "openPDFforExport input file invalid !!!"; } } if (svgDoc != null) { try { JSONObject info = new JSONObject(); info.put("isUnencryptedPDF", svgDoc.getPDFforExportIsUnencryptedPDF()); info.put("needsPassword", svgDoc.getPDFforExportNeedsPassword()); info.put("countPages", svgDoc.getDocumentForExportTotalPages()); Log.e(TAG, "pdfInfo:" + info.toString()); String encoded = EscapeUtils.encodeURIComponent(info.toString()); pluginResult = new PluginResult(PluginResult.Status.OK, encoded); } catch (Exception e) { pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS"); } } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, error); } if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "openPDFforExport error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } private void getDimension(final CallbackContext callbackContext, final int pageNumber) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult = null; String dimString = null; if (svgDoc != null) { dimString = svgDoc.getDocumentDimension(pageNumber); if (dimString != null && !dimString.isEmpty()) { JSONArray dim = null; try { dim = new JSONArray(dimString); String encoded = EscapeUtils.encodeURIComponent(dim.toString()); pluginResult = new PluginResult(PluginResult.Status.OK, encoded); } catch (Exception e) { e.printStackTrace(); pluginResult = new PluginResult(PluginResult.Status.OK, dimString); } } } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getDimension document invalid!!!"); } if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getDimension error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } private void getTotalPages(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult = null; if (doc == null) { callbackContext.error("need open a pdf file"); return; } int pages = doc.countPages(); pluginResult = new PluginResult(PluginResult.Status.OK, pages); if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getTotalPages error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } private void getPDFforExportSVG(final CallbackContext callbackContext, final int pageNumber, final String filepath, final int resolution) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult = null; String file = ((filepath == null) ? "" : filepath); String svg = null; Uri exportFile; if (svgDoc != null) { if (file.isEmpty()) { svg = svgDoc.getDocumentForSVG(pageNumber, file, resolution); if (svg == null || svg.isEmpty()) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportSVG: no svg got!!!"); } else { Log.e(TAG, "> getPDFforExportSVG svg:\n" + ((svg != null && svg.length() > 250) ? svg.substring(0, 250) : svg)); try { String encoded = EscapeUtils.encodeURIComponent(svg); Log.e(TAG, "> getPDFforExportSVG string:" + svg.length()); Log.e(TAG, "> getPDFforExportSVG encoded:" + encoded.length()); pluginResult = new PluginResult(PluginResult.Status.OK, encoded); } catch (Exception e) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportSVG: svg url encode error!!!"); e.printStackTrace(); } } } else { exportFile = Uri.parse(file); File exportedFile = new File(exportFile.getPath()); try { if (!exportedFile.exists()) exportedFile.createNewFile(); if (exportedFile.canWrite()) { svgDoc.getDocumentForSVG(pageNumber, exportFile.getPath(), resolution); if (exportedFile.exists() && exportedFile.length() != 0) { Log.e(TAG, "> SVG length:" + exportedFile.length()); pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS"); } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportSVG: no svg gexported!!!"); } } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportSVG: file location can not write!!!"); } } catch (IOException e) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportSVG: file location can not write!!!"); e.printStackTrace(); } } }else{ Log.e(TAG, "> svgDoc missing!!"); } if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportSVG error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } private void getPDFforExportPNG(final CallbackContext callbackContext, final int pageNumber, final String filepath, final int resolution) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult = null; String file = ((filepath == null) ? "" : filepath); Uri exportFile; if (svgDoc != null) { if (file.isEmpty()) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportPNG no output path !!!"); } else { exportFile = Uri.parse(file); File exportedFile = new File(exportFile.getPath()); try { if (!exportedFile.exists()) exportedFile.createNewFile(); if (exportedFile.canWrite()) { svgDoc.getDocumentForPNG(pageNumber, exportFile.getPath(), resolution); if (exportedFile.exists() && exportedFile.length() != 0) { Log.e(TAG, "> PNG length:" + exportedFile.length()); pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS"); } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportPNG: no png gexported!!!"); } } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportPNG: file location can not write!!!"); } } catch (IOException e) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportPNG: file location can not write!!!"); e.printStackTrace(); } } } if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportPNG error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } private void getPDFforExportTotalPages(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult; int pages = 0; if (svgDoc != null) { pages = svgDoc.getDocumentForExportTotalPages(); pluginResult = new PluginResult(PluginResult.Status.OK, pages); } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "PDF not opened!!!"); } if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "getPDFforExportTotalPages error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } private void closePDFforExport(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult = null; String file = ((closeFilepath == null) ? "" : closeFilepath); Uri exportFile = null; File exportedFile = null; int result = -1; if (svgDoc != null) { if (!file.isEmpty()) { exportFile = Uri.parse(file); exportedFile = new File(exportFile.getPath()); try { if (!exportedFile.exists()) exportedFile.createNewFile(); if (exportedFile.canWrite()) { } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDFforExport: file location can not write!!!"); } } catch (IOException e) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDFforExport: file location can not write!!!"); e.printStackTrace(); } } if(exportFile != null){ Log.e(TAG, "> closePDFforExport to "+exportFile.getPath()); result = svgDoc.closeDocumentForExport(exportFile.getPath()); Log.e(TAG, "> closePDFforExport"); }else{ result = svgDoc.closeDocumentForExport(""); } if (result == 0) { if (!file.isEmpty() && exportFile != null && exportedFile != null) { try { if (exportedFile.exists() && exportedFile.length() != 0) { Log.e(TAG, "> PDF length:" + exportedFile.length()); pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS"); } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDFforExport: no pdf gexported!!!"); } } catch (Exception e) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDFforExport: file location can not write!!!"); e.printStackTrace(); } }else{ pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS"); } svgDoc = null; } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDFforExport: PDF write error!!!"); } }else{ pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDFforExport svgDoc error!!!"); } if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDFforExport error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } public void openPDF(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult; if(pdfUri != null){ if (doc != null) { doc.destroy(); doc = null; } doc = Document.openDocument(pdfUri.getPath()); if (doc == null) { callbackContext.error("Can not open pdf: " + pdfUri.getPath()); return; } JSONObject pdfInfo = new JSONObject(); try { pdfInfo.put("isUnencryptedPDF", doc.isUnencryptedPDF()); pdfInfo.put("needsPassword", doc.needsPassword()); pdfInfo.put("countPages", doc.countPages()); } catch (JSONException e) { callbackContext.error("JSON Exception: " + e.getMessage()); return; } String encoded = EscapeUtils.encodeURIComponent(pdfInfo.toString()); pluginResult = new PluginResult(PluginResult.Status.OK, encoded); }else{ pluginResult = new PluginResult(PluginResult.Status.ERROR, "openPDF path error!!!"); } if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "openPDF error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } private void setPNGPathFullForExport(final CallbackContext callbackContext, final String imgFile, final int pageNumber, final int x, final int y, final int w, final int h) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult = null; String file = ((imgFile == null) ? "" : imgFile); Uri importFile; if (svgDoc != null) { if (file.isEmpty()) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "setPNGPathFullForExport no output path !!!"); } else { importFile = Uri.parse(file); File importedFile = new File(importFile.getPath()); try { if (importedFile.exists() && importedFile.canRead()) { int result = svgDoc.setPNGPathFullForExport(importFile.getPath(), pageNumber, x, y, w, h); if (result == 0) { pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS"); } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "setPNGPathFullForExport: write png error!!!"); } } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "setPNGPathFullForExport: file location can not read or not existed!!!"); } } catch (Exception e) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "setPNGPathFullForExport: file location can not write!!!"); e.printStackTrace(); } } } if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "setPNGPathFullForExport error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } public void insertImagePath(final CallbackContext callbackContext, final String imgFile, final int pageIdx, final int x, final int y, final int w, final int h) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { if (imgFile == null) { callbackContext.error("missing img file."); return; } if (doc == null) { callbackContext.error("need open a pdf file"); return; } Uri imgUri = Uri.parse(imgFile); Log.d(TAG, "insertImage: " + imgUri.getPath()); Page mPage = doc.loadPage(pageIdx); Rect rect = mPage.getBounds(); Log.d(TAG, "pageIdx: " + pageIdx + ", pageRect: " + rect.toString()); int width = w; int height = h; if (width == 0 || height == 0) { width = (int) (rect.x1 - rect.x0); // fit pdf page height = (int) (rect.y1 - rect.y0); } int left = x; int top = (int) (rect.y1 - rect.y0) - height - y; pdfDoc = doc.toPDFDocument(); pdfDoc.insertImage(imgUri.getPath(), pageIdx, left, top, width, height); pdfDoc.destroy(); pdfDoc = null; mPage.destroy(); mPage = null; callbackContext.success(); } }); } public void closePDF(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { PluginResult pluginResult = null; String file = ((closeFilepath == null) ? "" : closeFilepath); Uri exportFile; if (doc != null) { if (file.isEmpty()) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDF no output path !!!"); } else { exportFile = Uri.parse(file); File exportedFile = new File(exportFile.getPath()); try { if (!exportedFile.exists()) exportedFile.createNewFile(); if (exportedFile.canWrite()) { doc.toPDFDocument().save(exportFile.getPath(), "decompress=no,compress-images=yes"); Log.d(TAG, "closePDF: " + pdfUri.getPath()); Log.d(TAG, "saveTo: " + exportFile.getPath()); if (pdfDoc != null) pdfDoc.destroy(); if (doc != null) doc.destroy(); pdfDoc = null; doc = null; pdfUri = null; if (exportedFile.exists() && exportedFile.length() != 0) { Log.e(TAG, "> PDF length:" + exportedFile.length()); pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS"); } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDF: no pdf gexported!!!"); } } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDF: file location can not write!!!"); } } catch (IOException e) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDF: file location can not write!!!"); e.printStackTrace(); } } } if (pluginResult == null) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "closePDF error!!!"); } pluginResult.setKeepCallback(false); callbackContext.sendPluginResult(pluginResult); } }); } }
43.92053
177
0.504524
a00e6eeb1632eb91567fcf90821b79f30f79e9f2
938
package com.lfp.demo.pattern.behaviour.observer.jdk; /** * Title: * Description: * Project: lfp-pattern * Date: 2017-12-19 * Copyright: Copyright (c) 2020 * Company: LFP * * @author ZhuTao * @version 1.0 */ public class Client { public static void main(String[] args) { MyObserver observer1 = new MyObserver("observer1"); MyObserver observer2 = new MyObserver("observer2"); MySubject subject1 = new MySubject("subject1"); MySubject subject2 = new MySubject("subject2"); subject1.addObserver(observer1); subject1.addObserver(observer2); subject2.addObserver(observer2); subject1.setChanged(); subject1.notifyObservers("开启"); subject1.setChanged(); subject1.notifyObservers("关闭"); subject2.setChanged(); subject2.notifyObservers("开启"); subject2.setChanged(); subject2.notifyObservers("关闭"); } }
24.051282
59
0.641791
0abf19eb3ea2a7fc86cb71223cb863f912ae4b11
1,076
package practice.concurrency.five; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Semaphore; /** * 有界的ArrayList * 计数信号量(Counting Semaphore)用来控制同时访问某一个特定资源的操作数量,或者同时执行某个特定操作的数量 * 计数器信号量还可以实现某种资源池,或者对容器增加边界 * acquire()将阻塞直到获取一个许可信号量 * release()方法将返回一个许可信号量,相当于增加一个信号量 * Semaphore的信号量数量并不受限于创建的数量 * * @author liming * @version 2.2.7 * @date 15-3-20 下午2:34 */ public class BoundedArrayList<T> { private final List<T> list; private final Semaphore semaphore; public BoundedArrayList (int bound) { list = Collections.synchronizedList(new ArrayList<T>()); semaphore = new Semaphore(bound); } /** * 先获取一个信号量 * 如果增加失败则返回一个信号量 */ public boolean add (T t) throws InterruptedException { semaphore.acquire(); boolean b = false; try { b = list.add(t); return b; } finally { if (!b) { semaphore.release(); } } } public boolean remove(T t){ boolean b = false; try{ b = list.remove(t); return b; }finally { if(b){ semaphore.release(); } } } }
17.639344
64
0.683086