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
921c9c0f0e7e9f243382f5bb29d0ea563d41a012
192
// // (C) Copyright 2015 Martin E. Nordberg III // Apache 2.0 License // /** * Package containing lower level utilities for file I/O. */ package org.barlom.persistence.ioutilities.fileio;
17.454545
57
0.708333
c72269db08a15aa256eb4eeef3abdff36debd151
915
package com.feign.feign; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * 通过添加fallback即可实现熔断器功能 * * 微服务架构中服务被拆分成多个服务,服务之间可相互调用(RPC),SpringCloud使用Fegin调用,为保障服务高可用性单个服务会部署 * 集群,由于服务或者网络原因总会导致服务不可100%可用。如果服务出现问题,掉用该服务就会出现拥塞,此时若再有大量请求,servlet * 容器中的线程资源也会耗尽,导致服务瘫痪,并且可能导致整个微服务崩溃,所以使用断路器,当调用服务不可用时会快速执行失败,直接返回 * 固定的字符串来代替响应超时,从而很好的控制了容器的线程阻塞。 Fegin自带熔断器feign.hystrix.enabled=true配置开启然后实现访问接口 * 编写失败返回值即可。 * * */ //@FeignClient(value = "service-hi1") @FeignClient(value = "service-hi1",fallback = SchedualServiceHiHystric.class) interface SchedarServiceHi { @RequestMapping(value = "/hi",method = RequestMethod.GET) String sayHiFromClientOne(@RequestParam(value = "name") String name); }
31.551724
84
0.795628
ba84a09eed3e05dcfa0e6994072d885800eb9625
3,000
package com.lordofthejars.nosqlunit.mongodb; import com.mongodb.MongoClient; import com.mongodb.ServerAddress; import com.mongodb.WriteConcern; import java.util.ArrayList; import java.util.List; public class ReplicationMongoDbConfigurationBuilder { private static final String DEFAULT_HOST = "localhost"; private static final int DEFAULT_PORT = 27017; private MongoDbConfiguration mongoDbConfiguration = new MongoDbConfiguration(); private List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>(); private boolean enableSharding = false; private WriteConcern writeConcern = WriteConcern.ACKNOWLEDGED; private ReplicationMongoDbConfigurationBuilder() { super(); } public static ReplicationMongoDbConfigurationBuilder replicationMongoDbConfiguration() { return new ReplicationMongoDbConfigurationBuilder(); } public ReplicationMongoDbConfigurationBuilder seed(String host, int port) { serverAddresses.add(new ServerAddress(host, port)); return this; } public ReplicationMongoDbConfigurationBuilder databaseName( String databaseName) { mongoDbConfiguration.setDatabaseName(databaseName); return this; } public ReplicationMongoDbConfigurationBuilder username(String username) { mongoDbConfiguration.setUsername(username); return this; } public ReplicationMongoDbConfigurationBuilder password(String password) { mongoDbConfiguration.setPassword(password); return this; } public ReplicationMongoDbConfigurationBuilder connectionIdentifier( String identifier) { mongoDbConfiguration.setConnectionIdentifier(identifier); return this; } public ReplicationMongoDbConfigurationBuilder enableSharding() { this.enableSharding = true; return this; } public ReplicationMongoDbConfigurationBuilder writeConcern( WriteConcern writeConcern) { this.writeConcern = writeConcern; return this; } public MongoDbConfiguration configure() { if (this.serverAddresses.isEmpty()) { addDefaultSeed(); } MongoClient mongoClient = new MongoClient(this.serverAddresses); if (this.enableSharding) { enableSharding(mongoClient); } mongoDbConfiguration.setWriteConcern(writeConcern); mongoDbConfiguration.setMongo(mongoClient); return mongoDbConfiguration; } private void enableSharding(MongoClient mongoClient) { MongoDbCommands.enableSharding(mongoClient, this.mongoDbConfiguration.getDatabaseName()); } private boolean isAuthenticationSet() { return this.mongoDbConfiguration.getUsername() != null && this.mongoDbConfiguration.getPassword() != null; } private void addDefaultSeed() { serverAddresses.add(new ServerAddress(DEFAULT_HOST, DEFAULT_PORT)); } }
29.126214
92
0.713333
19365917e55a4a524ae867366b79f7b1740c8d76
3,910
package com.owsega.hackernews.data; import com.google.gson.GsonBuilder; import com.owsega.hackernews.data.model.Comment; import com.owsega.hackernews.data.model.Post; import java.util.ArrayList; import java.util.List; import retrofit.RestAdapter; import retrofit.converter.GsonConverter; import rx.Observable; import rx.Scheduler; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Retrieves and provides data (Model) in a way the views (activity/fragments) need it. */ public class DataProvider { private static DataProvider instance; // todo use injection not singleton private final List<Post> posts; private HackerNews hackerNews; private Scheduler subscribeScheduler; public DataProvider(HackerNews hackerNews, Scheduler scheduler) { this.hackerNews = hackerNews; this.subscribeScheduler = scheduler; posts = new ArrayList<>(); } public static DataProvider getInstance() { if (instance == null) { instance = new DataProvider( new RestAdapter.Builder() .setEndpoint(HackerNews.BASE_URL) .setConverter(new GsonConverter(new GsonBuilder().create())) .build() .create(HackerNews.class), Schedulers.io()); } return instance; } public Scheduler getScheduler() { return subscribeScheduler; } public Observable<Post> getTopStories() { return hackerNews.getTopStories().concatMap(new Func1<List<Long>, Observable<? extends Post>>() { @Override public Observable<? extends Post> call(List<Long> longs) { return getPostsFromIds(longs); } }); } private Observable<Post> getPostsFromIds(List<Long> storyIds) { return Observable.from(storyIds) .concatMap(new Func1<Long, Observable<Post>>() { @Override public Observable<Post> call(Long aLong) { return hackerNews.getStoryItem(String.valueOf(aLong)); } }).flatMap(new Func1<Post, Observable<Post>>() { @Override public Observable<Post> call(Post post) { return post.title != null ? Observable.just(post) : Observable.<Post>empty(); } }); } public Observable<Comment> getPostComments(final List<Long> commentIds, final int depth) { return Observable.from(commentIds) .concatMap(new Func1<Long, Observable<Comment>>() { @Override public Observable<Comment> call(Long aLong) { return hackerNews.getCommentItem(String.valueOf(aLong)); } }).concatMap(new Func1<Comment, Observable<Comment>>() { @Override public Observable<Comment> call(Comment comment) { comment.depth = depth; if (comment.kids == null || comment.kids.isEmpty()) { return Observable.just(comment); } else { return Observable.just(comment) .mergeWith(getPostComments(comment.kids, depth + 1)); } } }).filter(new Func1<Comment, Boolean>() { @Override public Boolean call(Comment comment) { return (comment.by != null && !comment.by.trim().isEmpty() && comment.text != null && !comment.text.trim().isEmpty()); } }); } public List<Post> getPosts() { return posts; } }
37.238095
105
0.545013
b2394b5ee7fd56d94616e510db6d664ba56e27b2
480
package com.google.sample.cast.refplayer.di.component; import com.google.sample.cast.refplayer.di.module.ChannelListModule; import com.codesyntax.jarrion.di.scope.FragmentScope; import com.google.sample.cast.refplayer.ui.channellist.view.ChannelListFragment; import dagger.Component; @FragmentScope @Component(modules = ChannelListModule.class, dependencies = ApplicationComponent.class) public interface ChannelListComponent { void inject(ChannelListFragment fragment); }
34.285714
88
0.8375
13c8a3ecad6059e7c148e48164d4fdbc3469b644
320
package jorisdgffdemos.somebigsystem.cqrskit; public class Acknowledgement { public final String refferingEvent; public final String message; public Acknowledgement(String refferingEvent, String message){ this.refferingEvent = refferingEvent; this.message = message; } }
22.857143
67
0.70625
0321d8edd3d3df96268f8183df1cf581fee0e49c
5,507
package de.taimos.gpsd4java.types.subframes; /* * #%L * GPSd4Java * %% * Copyright (C) 2011 - 2012 Taimos GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import de.taimos.gpsd4java.types.IGPSObject; /** * @author aevdokimov */ public class EPHEM3Object implements IGPSObject { /** * the GPSd internal name */ public static final String NAME = "EPHEM3"; private int IODE = -1; private double IDOT = Double.NaN; private double Cic = Double.NaN; private double Omega0 = Double.NaN; private double Cis = Double.NaN; private double i0 = Double.NaN; private double Crc = Double.NaN; private double omega = Double.NaN; private double Omegad = Double.NaN; /** * @return the iODE */ public int getIODE() { return this.IODE; } /** * @param iODE the iODE to set */ public void setIODE(final int iODE) { this.IODE = iODE; } /** * @return the iDOT */ public double getIDOT() { return this.IDOT; } /** * @param iDOT the iDOT to set */ public void setIDOT(final double iDOT) { this.IDOT = iDOT; } /** * @return the cic */ public double getCic() { return this.Cic; } /** * @param cic the cic to set */ public void setCic(final double cic) { this.Cic = cic; } /** * @return the omega0 */ public double getOmega0() { return this.Omega0; } /** * @param omega0 the omega0 to set */ public void setOmega0(final double omega0) { this.Omega0 = omega0; } /** * @return the cis */ public double getCis() { return this.Cis; } /** * @param cis the cis to set */ public void setCis(final double cis) { this.Cis = cis; } /** * @return the i0 */ public double getI0() { return this.i0; } /** * @param i0 the i0 to set */ public void setI0(final double i0) { this.i0 = i0; } /** * @return the crc */ public double getCrc() { return this.Crc; } /** * @param crc the crc to set */ public void setCrc(final double crc) { this.Crc = crc; } /** * @return the omega */ public double getOmega() { return this.omega; } /** * @param omega the omega to set */ public void setOmega(final double omega) { this.omega = omega; } /** * @return the omegad */ public double getOmegad() { return this.Omegad; } /** * @param omegad the omegad to set */ public void setOmegad(final double omegad) { this.Omegad = omegad; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof EPHEM3Object)) { return false; } final EPHEM3Object that = (EPHEM3Object) o; if (Double.compare(that.Cic, this.Cic) != 0) { return false; } if (Double.compare(that.Cis, this.Cis) != 0) { return false; } if (Double.compare(that.Crc, this.Crc) != 0) { return false; } if (Double.compare(that.IDOT, this.IDOT) != 0) { return false; } if (this.IODE != that.IODE) { return false; } if (Double.compare(that.Omega0, this.Omega0) != 0) { return false; } if (Double.compare(that.Omegad, this.Omegad) != 0) { return false; } if (Double.compare(that.i0, this.i0) != 0) { return false; } if (Double.compare(that.omega, this.omega) != 0) { return false; } return true; } @Override public int hashCode() { int result; long temp; result = this.IODE; temp = this.IDOT != +0.0d ? Double.doubleToLongBits(this.IDOT) : 0L; result = (31 * result) + (int) (temp ^ (temp >>> 32)); temp = this.Cic != +0.0d ? Double.doubleToLongBits(this.Cic) : 0L; result = (31 * result) + (int) (temp ^ (temp >>> 32)); temp = this.Omega0 != +0.0d ? Double.doubleToLongBits(this.Omega0) : 0L; result = (31 * result) + (int) (temp ^ (temp >>> 32)); temp = this.Cis != +0.0d ? Double.doubleToLongBits(this.Cis) : 0L; result = (31 * result) + (int) (temp ^ (temp >>> 32)); temp = this.i0 != +0.0d ? Double.doubleToLongBits(this.i0) : 0L; result = (31 * result) + (int) (temp ^ (temp >>> 32)); temp = this.Crc != +0.0d ? Double.doubleToLongBits(this.Crc) : 0L; result = (31 * result) + (int) (temp ^ (temp >>> 32)); temp = this.omega != +0.0d ? Double.doubleToLongBits(this.omega) : 0L; result = (31 * result) + (int) (temp ^ (temp >>> 32)); temp = this.Omegad != +0.0d ? Double.doubleToLongBits(this.Omegad) : 0L; result = (31 * result) + (int) (temp ^ (temp >>> 32)); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("EPHEM3Object{IODE="); sb.append(this.IODE); sb.append(", IDOT="); sb.append(this.IDOT); sb.append(", Cic="); sb.append(this.Cic); sb.append(", Omega0="); sb.append(this.Omega0); sb.append(", Cis="); sb.append(this.Cis); sb.append(", i0="); sb.append(this.i0); sb.append(", Crc="); sb.append(this.Crc); sb.append(", omega="); sb.append(this.omega); sb.append(", Omegad="); sb.append(this.Omegad); sb.append("}"); return sb.toString(); } }
20.321033
75
0.613583
5c82afe3276ad74098a6a42385ac6ac7c8ca8f4c
454
/** * ObjectPropertyPresenter.java * * Created on 2. 11. 2021, 13:59:35 by burgetr */ package io.github.radkovo.owldocgen.pres; import io.github.radkovo.owldocgen.DocBuilder; import io.github.radkovo.owldocgen.model.ResourceObject; /** * * @author burgetr */ public class ObjectPropertyPresenter extends PropertyPresenter { public ObjectPropertyPresenter(DocBuilder builder, ResourceObject res) { super(builder, res); } }
18.916667
74
0.729075
530f776c95e99b4ba7c86a8c716f78f9b83db9b4
3,261
/* * Copyright 2013 Dominic Masters and Jordan Atkins * * 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.domsplace.Villages.GUI; import com.domsplace.Villages.Bases.Base; import com.domsplace.Villages.Events.VillageGUICloseEvent; import com.domsplace.Villages.GUI.BukkitGUI.VillageGUIFrame; import com.domsplace.Villages.GUI.BukkitGUI.VillageImage; import java.awt.BorderLayout; import java.awt.Color; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; public class VillagesFrame extends VillageGUIFrame { private static final String VILLAGE_LOGO_REL = "images/VillagesLogo.png"; private static final String VILLAGE_ICON_REL = "images/VillagesIcon.png"; private static final int FRAME_WIDTH = 750; private static final int FRAME_HEIGHT = 600; //Instance private JPanel panel; private JLabel copyrightLabel; private VillageImage villageLogo; private VillageImage villageIcon; private VillagesTabbedPane villageTabbedPane; public VillagesFrame(VillagesGUIManager manager) { super(manager, "Villages"); this.setBackground(Color.WHITE); //Build GUI this.panel = new JPanel(new BorderLayout(4,4)); this.panel.setBackground(Color.WHITE); try { //Build Images this.villageLogo = new VillageImage(VILLAGE_LOGO_REL); this.villageIcon = new VillageImage(VILLAGE_ICON_REL); } catch(Exception e) { Base.error("Failed to setup gui!", e); } this.villageTabbedPane = new VillagesTabbedPane(); this.copyrightLabel = new JLabel("2013 Dominic Masters - http://domsplace.com/"); //Position this.villageLogo.setHorizontalAlignment(SwingConstants.CENTER); this.copyrightLabel.setHorizontalAlignment(SwingConstants.CENTER); //Add Items this.panel.add(this.villageLogo, BorderLayout.NORTH); this.panel.add(this.villageTabbedPane, BorderLayout.CENTER); this.panel.add(this.copyrightLabel, BorderLayout.SOUTH); this.setIconImage(this.villageIcon.getImage()); this.add(this.panel); this.pack(); this.setResizable(false); this.setSize(FRAME_WIDTH, FRAME_HEIGHT); this.setVisible(true); } public JPanel getMainPanel() {return this.panel;} public VillageImage getVillageLogo() {return this.villageLogo;} public VillagesTabbedPane getTabbedPane() {return this.villageTabbedPane;} @Override public void onClose() { VillageGUICloseEvent event = new VillageGUICloseEvent(this); event.fireEvent(); } }
34.691489
89
0.693959
80b8d0a6981bc79da39c390e2e37ed1b1cbe7bb4
311
package com.muggle.use.spring; import java.util.Properties; public class MyDataSourceProperties { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } }
19.4375
54
0.710611
0b95fc7b8680fa4ccec309bc57edf6b13306127f
11,643
/** * Copyright 2016 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 org.specs.matisselib.passes.posttype.loopgetsimplifier; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.function.Consumer; import org.specs.CIR.Types.VariableType; import org.specs.matisselib.helpers.BlockUtils; import org.specs.matisselib.helpers.LoopVariable; import org.specs.matisselib.helpers.NameUtils; import org.specs.matisselib.helpers.UsageMap; import org.specs.matisselib.helpers.sizeinfo.ScalarValueInformation; import org.specs.matisselib.services.ScalarValueInformationBuilderService; import org.specs.matisselib.ssa.InstructionType; import org.specs.matisselib.ssa.SsaBlock; import org.specs.matisselib.ssa.instructions.ForInstruction; import org.specs.matisselib.ssa.instructions.FunctionCallInstruction; import org.specs.matisselib.ssa.instructions.IterInstruction; import org.specs.matisselib.ssa.instructions.PhiInstruction; import org.specs.matisselib.ssa.instructions.SsaInstruction; import org.specs.matisselib.typeinference.TypedInstance; import com.google.common.collect.Lists; public class IndexExtractionUtils { private final Consumer<String> logger; public IndexExtractionUtils(Consumer<String> logger) { this.logger = logger; } public boolean checkIndicesGrowWithIters(TypedInstance instance, ScalarValueInformationBuilderService scalarBuilder, List<String> iters, List<String> indices, List<SsaInstruction> instructionsToInject, Set<String> externalVars) { try (ScalarValueInformation scalarInfo = scalarBuilder.build(instance::getVariableType)) { for (String externalVar : externalVars) { scalarInfo.addAlias(externalVar + "#1", externalVar + "#2"); } for (SsaInstruction instruction : instructionsToInject) { if (instruction instanceof FunctionCallInstruction) { FunctionCallInstruction functionCall = (FunctionCallInstruction) instruction; scalarInfo.addScalarFunctionCallInformation(functionCall, "1"); scalarInfo.addScalarFunctionCallInformation(functionCall, "2"); } } return scalarInfo.growsWith(indices, iters, "1", "2"); } } public boolean checkSizesDeclarationsValid(TypedInstance instance, int blockId, Set<String> externalVars) { ForInstruction xfor = (ForInstruction) instance.getBlock(blockId).getEndingInstruction().get(); Set<String> variablesDeclaredInLoop = BlockUtils.getVariablesDeclaredInContainedBlocks( instance.getFunctionBody(), xfor.getLoopBlock()); for (String externalVar : externalVars) { if (variablesDeclaredInLoop.contains(externalVar)) { log("Declaration of " + externalVar + " is unavailable at the preallocation location."); return false; } } return true; } public Optional<LoopVariable> findMatchingVariable(TypedInstance instance, List<LoopVariable> candidateVariables, LoopVariable currentVariable, UsageMap usageMap) { log("Finding parent variable of " + currentVariable); log("Candidates are: " + candidateVariables); for (LoopVariable candidateVariable : candidateVariables) { if (!candidateVariable.loopStart.equals(currentVariable.beforeLoop) || !Optional.of(candidateVariable.loopEnd).equals(currentVariable.getAfterLoop())) { continue; } log("Testing " + candidateVariable + ", " + currentVariable); if (!checkUsageCounts(candidateVariable, usageMap, false)) { return Optional.empty(); } if (!checkTypeCompatibility(instance, candidateVariable)) { log("Incompatible types"); log(instance.getVariableType(candidateVariable.beforeLoop).toString()); log(instance.getVariableType(candidateVariable.loopStart).toString()); log(instance.getVariableType(candidateVariable.loopEnd).toString()); if (candidateVariable.getAfterLoop().isPresent()) { log(instance.getVariableType(candidateVariable.getAfterLoop().get()).toString()); } return Optional.empty(); } if (instance.getVariableType(candidateVariable.loopStart) .equals(instance.getVariableType(currentVariable.loopStart))) { log("Found match"); return Optional.of(candidateVariable); } return Optional.empty(); } log("Could not find reasonable candidate"); return Optional.empty(); } public boolean checkUsageCounts(LoopVariable loopVariable, UsageMap usageMap, boolean innerMost) { if (usageMap.getUsageCount(loopVariable.loopStart) != (innerMost ? 1 : 2)) { log("(LoopStart) Variable has wrong number of uses: " + loopVariable.loopStart); log(usageMap.toString()); return false; } if (loopVariable.getAfterLoop().isPresent()) { if (usageMap.getUsageCount(loopVariable.beforeLoop) != 2 || usageMap.getUsageCount(loopVariable.loopEnd) != 2) { log("Variable has wrong number of uses: " + loopVariable); log(usageMap.toString()); return false; } } else { if (usageMap.getUsageCount(loopVariable.beforeLoop) != 1 || usageMap.getUsageCount(loopVariable.loopEnd) != 1) { log("Variable has wrong number of uses: " + loopVariable); log(usageMap.toString()); return false; } } return true; } public boolean verifyInstructionsToInject(TypedInstance instance, List<SsaInstruction> instructionsToInject, Set<String> varsThatMustBeAccessible, List<Integer> loopBlocks, List<String> iters, List<String> indices, List<String> loopSizes) { Map<String, SsaInstruction> declarations = new HashMap<>(); for (int blockId : loopBlocks) { ForInstruction xfor = (ForInstruction) instance.getBlock(blockId).getEndingInstruction().get(); for (SsaInstruction instruction : instance.getBlock(xfor.getLoopBlock()).getInstructions()) { if (instruction instanceof IterInstruction || instruction instanceof PhiInstruction || instruction.getInstructionType() != InstructionType.NO_SIDE_EFFECT) { continue; } for (String output : instruction.getOutputs()) { declarations.put(output, instruction); } } } log(declarations.toString()); Queue<String> varsToVisit = new LinkedList<>(); Set<String> visitedVars = new HashSet<>(); varsToVisit.addAll(indices); Set<SsaInstruction> unorderedInstructionsToInject = new HashSet<>(); while (!varsToVisit.isEmpty()) { String var = varsToVisit.poll(); if (!visitedVars.add(var)) { // Already visited continue; } int iterIndex = iters.indexOf(var); if (iterIndex >= 0) { varsThatMustBeAccessible.add(loopSizes.get(iterIndex)); continue; } if (!declarations.containsKey(var)) { varsThatMustBeAccessible.add(var); continue; } SsaInstruction declaration = declarations.get(var); unorderedInstructionsToInject.add(declaration); varsToVisit.addAll(declaration.getInputVariables()); } for (int blockId : Lists.reverse(loopBlocks)) { ForInstruction xfor = (ForInstruction) instance.getBlock(blockId).getEndingInstruction().get(); for (SsaInstruction instruction : instance.getBlock(xfor.getLoopBlock()).getInstructions()) { if (unorderedInstructionsToInject.contains(instruction)) { instructionsToInject.add(instruction); } } } assert unorderedInstructionsToInject.equals(new HashSet<>(instructionsToInject)); return true; } public void injectInstructions(TypedInstance instance, int blockId, List<SsaInstruction> instructionsToInject, List<String> inputValues, List<String> indices, List<String> iters, List<String> loopSizes) { SsaBlock block = instance.getBlock(blockId); int injectionPoint = block.getInstructions().size() - 1; Map<String, String> newNames = new HashMap<>(); for (int i = 0; i < iters.size(); ++i) { newNames.put(iters.get(i), loopSizes.get(i)); } instructionsToInject.stream() .flatMap(instruction -> instruction.getOutputs().stream()) .distinct() .forEach(output -> { String newName = instance.makeTemporary("max_" + NameUtils.getSuggestedName(output), instance.getVariableType(output)); newNames.put(output, newName); }); for (SsaInstruction instructionToInject : instructionsToInject) { SsaInstruction newInstruction = instructionToInject.copy(); newInstruction.renameVariables(newNames); block.insertInstruction(injectionPoint++, newInstruction); } for (String index : indices) { String newName = newNames.getOrDefault(index, index); inputValues.add(newName); } } public boolean checkTypeCompatibility(TypedInstance instance, LoopVariable loopVariable) { Optional<VariableType> referenceType = instance.getVariableType(loopVariable.loopStart); boolean beforeLoopTypeMatches = instance .getVariableType(loopVariable.beforeLoop) .map(type -> type.equals(referenceType.get())) .orElse(true); boolean afterLoopTypeMatches = !loopVariable.getAfterLoop().isPresent() || instance.getVariableType(loopVariable.getAfterLoop().get()).equals(referenceType); boolean areTypesCompatible = beforeLoopTypeMatches && instance.getVariableType(loopVariable.loopEnd).equals(referenceType) && afterLoopTypeMatches; return areTypesCompatible; } public void log(String message) { logger.accept(message); } }
38.425743
118
0.631624
e6ce4d4170185c025587e251fa1932bd150d542d
536
package dev.sanda.javagraphqlspqrdemo.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import java.util.HashSet; import java.util.Set; @Data @Entity public class Author { @Id @GeneratedValue private Long id; private String name; private String email; @OneToMany(mappedBy = "author") private Set<BlogPost> blogPosts = new HashSet<>(); }
22.333333
54
0.761194
9f60714d49a5f9584c1e736b174dfa386330ab42
8,509
/* * ------------------------------------------------------------------ * This source code, its documentation and all appendant files * are protected by copyright law. All rights reserved. * * Copyright, 2003 - 2010 * University of Konstanz, Germany * Chair for Bioinformatics and Information Mining (Prof. M. Berthold) * and KNIME GmbH, Konstanz, Germany * * You may not modify, publish, transmit, transfer or sell, reproduce, * create derivative works from, distribute, perform, display, or in * any way exploit any of the content, in whole or in part, except as * otherwise expressly permitted in writing by the copyright owner or * as specified in the license file distributed with this product. * * If you have any questions please contact the copyright holder: * website: www.knime.org * email: [email protected] * --------------------------------------------------------------------- * * * History * 12.09.2008 (gabriel): created */ package de.mpicbg.knime.scripting.r.generic; import java.awt.BorderLayout; import java.awt.Font; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.zip.ZipEntry; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.text.DefaultCaret; import org.apache.commons.lang3.StringUtils; import org.knime.core.node.CanceledExecutionException; import org.knime.core.node.ExecutionMonitor; import org.knime.core.node.NodeLogger; import org.knime.core.node.port.PortObject; import org.knime.core.node.port.PortObjectSpec; import org.knime.core.node.port.PortObjectZipInputStream; import org.knime.core.node.port.PortObjectZipOutputStream; import org.knime.core.node.port.PortType; import org.knime.core.util.FileUtil; import org.rosuda.REngine.Rserve.RConnection; import de.mpicbg.knime.scripting.core.exceptions.KnimeScriptingException; import de.mpicbg.knime.scripting.r.RUtils; import de.mpicbg.knime.scripting.r.node.snippet.RSnippetNodeModel; /** * {@deprecated} * A port object for R model port providing a file containing a R model. * * @author Kilian Thiel, University of Konstanz */ public class RPortObject implements PortObject { /** * Convenience access member for <code>new PortType(RPortObject.class)</code>. */ public static final PortType TYPE = new PortType(RPortObject.class); private static final NodeLogger LOGGER = NodeLogger.getLogger(RPortObject.class); private final File m_fileR; /** * Creates an instance of <code>RPortObject</code> with given file. * * @param fileR The file containing a R model. */ public RPortObject(final File fileR) { m_fileR = fileR; } /** * {@inheritDoc} */ public RPortObjectSpec getSpec() { return RPortObjectSpec.INSTANCE; } /** * {@inheritDoc} */ public String getSummary() { return "R Object"; } /** * Returns the file containing the R model. * * @return the file containing the R model. */ public File getFile() { return m_fileR; } /** * Serializer used to save this port object. * * @return a {@link RPortObject} */ public static PortObjectSerializer<RPortObject> getPortObjectSerializer() { return new PortObjectSerializer<RPortObject>() { /** {@inheritDoc} */ @Override public void savePortObject(final RPortObject portObject, final PortObjectZipOutputStream out, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { out.putNextEntry(new ZipEntry("knime.R")); FileInputStream fis = new FileInputStream(portObject.m_fileR); FileUtil.copy(fis, out); fis.close(); out.close(); } /** {@inheritDoc} */ @Override public RPortObject loadPortObject( final PortObjectZipInputStream in, final PortObjectSpec spec, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { in.getNextEntry(); File fileR = File.createTempFile("~knime", ".R"); FileOutputStream fos = new FileOutputStream(fileR); FileUtil.copy(in, fos); in.close(); fos.close(); return new RPortObject(fileR); } }; } /** * {@inheritDoc} */ public JComponent[] getViews() { JPanel panel = new JPanel(new BorderLayout()); JTextArea jep = new JTextArea(); // prevent autoscrolling DefaultCaret caret = (DefaultCaret)jep.getCaret(); caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); jep.setEditable(false); panel.setName("R Port View"); RConnection connection; try { connection = RUtils.createConnection(); } catch (KnimeScriptingException e) { jep.setText(e.getMessage()); panel.add(new JScrollPane(jep)); e.printStackTrace(); return new JComponent[]{panel}; } jep.setFont(new Font("Monospaced", Font.PLAIN, 14)); try { RUtils.loadGenericInputs(Collections.singletonMap(RSnippetNodeModel.R_OUTVAR_BASE_NAME, new File(getFilePath())), connection); // to get structure information about the output object, one needs to use capture the output // str(...) does not provide any return value connection.voidEval("tempfile <- tempfile(pattern = 'structure_', fileext = '.txt')"); List<String> objects = Arrays.asList(connection.eval("ls()").asStrings()); for(String obj : objects) { // exclude files which where created temporary TODO: it is too dependent on how temporary file variables are named... other solution? if(!(obj.equals("tempfile") || obj.equals("tmpwfile"))) connection.voidEval("capture.output(print(\"" + obj + "\"), str(" + obj + "), file = tempfile, append = TRUE)"); } String[] structure = connection.eval("readLines(tempfile)").asStrings(); connection.voidEval("unlink(tempfile)"); String summary = StringUtils.join(structure, '\n'); jep.setText(summary); } catch (Exception e) { jep.setText("Failed to retrieve the structure of R objects from port file " + getFilePath()); } connection.close(); panel.add(new JScrollPane(jep)); return new JComponent[]{panel}; } /** * @return The path of the R model file if available, otherwise "No file available". */ String getFilePath() { if (m_fileR != null) { return m_fileR.getAbsolutePath(); } return "No file available"; } /** * @return The input of the R model file. */ String getModelData() { StringBuffer buf = new StringBuffer(); if (m_fileR != null && m_fileR.exists() && m_fileR.canRead()) { try { BufferedReader reader = new BufferedReader(new FileReader(m_fileR)); String line; while ((line = reader.readLine()) != null) { buf.append(line); } } catch (Exception e) { LOGGER.warn("R model could not be read from file!"); buf.append("R model could no be read from file!"); } } return buf.toString(); } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof RPortObject)) { return false; } RPortObject rPort = (RPortObject) obj; return m_fileR.equals(rPort.m_fileR); } /** * {@inheritDoc} */ @Override public int hashCode() { return m_fileR.hashCode(); } }
31.398524
146
0.598425
2eca47c6f7e97159af5b08eba2c0c228862c99ef
231
package com.aya.financegateway; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class FinanceGatewayApplicationTests { @Test void contextLoads() { } }
16.5
60
0.766234
a80d44ab1c0e8cac680174bb7f124e7e53e06276
822
package de.oio.ui.views; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.server.ExternalResource; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.spring.annotation.SpringView; import com.vaadin.ui.Label; import com.vaadin.ui.Link; import com.vaadin.ui.Panel; import com.vaadin.ui.VerticalLayout; @SpringView(name = "") public class MainView extends Panel implements View { public MainView() { VerticalLayout layout = new VerticalLayout(); layout.addComponent(new Label("<h1>Welcome Stranger</h1><hr/>You're currently not logged in.<hr/>", ContentMode.HTML)); layout.addComponent(new Link("Your Profile", new ExternalResource("#!profile"))); setContent(layout); } @Override public void enter(ViewChangeEvent event) { } }
30.444444
121
0.774939
475e861c89bcb5dcd10e1a3ba1c83a5bd0d2b738
4,203
package pdbs3.csp8.cspapp; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class gpsLocation extends AppCompatActivity { private Button b; private TextView t; private LocationManager locationManager; private LocationListener listener; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gps_location); t = (TextView) findViewById(R.id.textView); b = (Button) findViewById(R.id.button); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); listener = new LocationListener() { @Override public void onLocationChanged(Location location) { t.append("\n " + location.getLongitude() + " " + location.getLatitude()); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(i); } }; configure_button(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 10: configure_button(); break; default: break; } } void configure_button() { // first check for permissions if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET} , 10); } return; } // this code won't execute IF permissions are not allowed, because in the line above there is return statement. b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //noinspection MissingPermission if ((ActivityCompat.checkSelfPermission(gpsLocation.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ActivityCompat.checkSelfPermission(gpsLocation.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } locationManager.requestLocationUpdates("gps", 1000, 0, listener); } }); } }
38.916667
296
0.62955
8cb7a0b3269e4661098176e939db7ce062f3dcf4
1,934
package ichttt.mods.mcpaint.networking; import ichttt.mods.mcpaint.common.MCPaintUtil; import ichttt.mods.mcpaint.common.block.TileEntityCanvas; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.network.PacketBuffer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraftforge.fml.network.NetworkEvent; import java.util.function.Supplier; public class MessageDrawAbort { private final BlockPos pos; public MessageDrawAbort(PacketBuffer buffer) { this.pos = buffer.readBlockPos(); } public MessageDrawAbort(BlockPos pos) { this.pos = pos; } public void encode(PacketBuffer buf) { buf.writeBlockPos(this.pos); } public static class Handler { public static void onMessage(MessageDrawAbort message, Supplier<NetworkEvent.Context> supplier) { NetworkEvent.Context ctx = supplier.get(); ServerPlayerEntity player = MCPaintUtil.checkServer(ctx); ctx.setPacketHandled(true); ctx.enqueueWork(() -> { if (MCPaintUtil.isPosInvalid(player, message.pos)) return; TileEntity te = player.world.getTileEntity(message.pos); if (te instanceof TileEntityCanvas) { TileEntityCanvas canvas = (TileEntityCanvas) te; boolean hasData = false; for (Direction facing : Direction.values()) { if (canvas.hasPaintFor(facing)) { hasData = true; break; } } if (!hasData && canvas.getContainedState() != null) { player.world.setBlockState(message.pos, canvas.getContainedState()); } } }); } } }
34.535714
105
0.607032
3694be43a12a90c4d80a4132a516594e04cd386c
9,305
package com.sparo.leetcode.tree; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * description: 662. 二叉树最大宽度 * 给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。 * * 每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。 * * 示例 1: * * 输入: * * 1 * / \ * 3 2 * / \ \ * 5 3 9 * * 输出: 4 * 解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。 * 示例 2: * * 输入: * * 1 * / * 3 * / \ * 5 3 * * 输出: 2 * 解释: 最大值出现在树的第 3 层,宽度为 2 (5,3)。 * 示例 3: * * 输入: * * 1 * / \ * 3 2 * / * 5 * * 输出: 2 * 解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)。 * 示例 4: * * 输入: * * 1 * / \ * 3 2 * / \ * 5 9 * / \ * 6 7 * 输出: 8 * 解释: 最大值出现在树的第 4 层,宽度为 8 (6,null,null,null,null,null,null,7)。 * 注意: 答案在32位有符号整数的表示范围内。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/maximum-width-of-binary-tree * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * Created by sdh on 2020-07-19 */ public class WidthOfBinaryTree { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } //20200720 版 // int maxWidth; // LinkedList<Integer> list; // private int wobtRecursion(TreeNode root) { // if(root == null) return 0; // //用于记录最大宽度值 // maxWidth = 1; //root 非空,width至少为1 // //用于记录对应level层第一个节点的索引 // list = new LinkedList<>(); // recurHelper(root, 0, 1); // return maxWidth; // } // // private void recurHelper(TreeNode node, int level, int index) { // if(node == null) return; // if(level==list.size()) { // list.add(index); // } else { // //list 存的是当前层的第一个节点的索引,用当前层其他节点的索引减去第一个节点索引+1即为当前最大宽度值 // maxWidth = Math.max(maxWidth, index-list.get(level)+1); // } // //递归 // recurHelper(node.left, level+1, 2*index); // recurHelper(node.right, level+1, 2*index+1); // } // // // private int wobtTraversalOriginal(TreeNode root) { // if(root == null) return 0; // //队列初始化 // ArrayDeque<TreeNode> queue = new ArrayDeque<>(); // queue.offer(root); // //存储index 的list getLast/getFirst && removeLast peekFirst/peekLast均是deque 接口的api,deque继承queue 接口,queue接口没有以上api,只有基础的 offer/poll/peek/remove/add等 // LinkedList<Integer> list = new LinkedList<>();//因为需要remove所以选择链表 // list.add(1); // int maxWidth = 1; // while(!queue.isEmpty()) { // int size = queue.size(); // //LinkedList 作为 Deque才有的api能力 // maxWidth = Math.max(maxWidth, list.getLast()-list.getFirst()+1); // //取队首作为锚点值 // int pivotIndex = list.peekFirst(); // for(int i = 0; i < size; i++) { // //❌ 同步队列 从队首出队 (错误示范 按照记忆?调用了removeLast!) // int index = list.removeFirst(); // TreeNode node = queue.poll(); // if(node.left!=null) { // queue.offer(node.left); // list.add(index*2-pivotIndex); // } // if(node.right!=null) { // queue.offer(node.right); // list.add(index*2+1-pivotIndex); // } // } // } // return maxWidth; // } // // private int wobtTraversal(TreeNode root) { // if(root == null) return 0; // ArrayDeque<TreeNode> queue = new ArrayDeque<>(); // queue.offer(root); // int maxWidth = 1; // //修改root val // root.val = 1; // while(!queue.isEmpty()) { // int size = queue.size(); // maxWidth = Math.max(maxWidth, queue.peekLast().val-queue.peekFirst().val+1); // //防止超界可设置pivot 值 // int pivotIndex = queue.peekFirst().val; // for(int i = 0; i < size; i++) { // TreeNode node = queue.poll(); // int index = node.val; // if(node.left!=null) { // node.left.val = 2*index-pivotIndex; // queue.offer(node.left); // } // if(node.right!=null) { // node.right.val = 2*index+1-pivotIndex; // queue.offer(node.right); // } // } // } // return maxWidth; // } //如果在尝试dfs/bfs 得到width时 存在超过32层越界int的可能时,可改用double 记录,另对bfs可在每层遍历时记录first值 public int widthOfBinaryTree(TreeNode root) { //递归 稳定1ms 时间最优 空间last // return wobtRecursion(root); //以下两种方法实测 时间效率不如 递归方案,空间效率依次提升 //使用两个额外的队列数据结构处理分别处理遍历+遍历过程中node 的 index维护 稳定2ms 时间last 空间次之 // return wobtTraversal(root); //只使用一个队列维护遍历过程,index 通过改变root的val记录即可!(1-2ms间) 时间次之,空间最优 return wobtTraversalP(root); } //不使用额外的数据结构存储index,减少在遍历时移除的操作,这里改变Node 中val的值为index private int wobtTraversalP(TreeNode root) { if(root == null) return 0; ArrayDeque<TreeNode> queue = new ArrayDeque<>(); queue.offer(root); root.val = 1; // 修改node val 值为对应的index int maxWidth = 1; //root 非null则 width 最小值为1!!! while(!queue.isEmpty()) { maxWidth = Math.max(maxWidth, queue.peekLast().val - queue.peekFirst().val+1); int size = queue.size(); //防止越界处理 🚩 int pivotIndex = queue.peek().val; for(int i=0; i<size; i++) { TreeNode node = queue.poll(); int index = node.val; if(node.left!=null) { // node.left.val = 2*index; node.left.val = 2*index-pivotIndex; queue.offer(node.left); } if(node.right!=null) { // node.right.val = 2*index + 1; node.right.val = 2*index+1-pivotIndex; queue.offer(node.right); } } //最后一层叶子节点判定后,这里queue会null,当queue为null 时 peekLast/peekFirst都会NPE //❌当层遍历完成后获取queue的首尾node 中存的 index得到当前层的width // maxWidth = Math.max(maxWidth, queue.peekLast().val - queue.peekFirst().val+1); //注意+1, 4567/7-4+1 index 的差值+1才是正确的宽度 } return maxWidth; } private int wobtTraversal(TreeNode root) { if(root == null) return 0; //层序遍历 ArrayDeque<TreeNode> queue = new ArrayDeque<>(); queue.offer(root); LinkedList<Integer> list = new LinkedList<>(); int maxWidth = 1; list.add(1); //这里可将index 替换成 list.add 在每次遍历当前节点时remove // int index = 1; //first root index,后序二叉树节点index在root index按照二叉树子节点规律更新 while(!queue.isEmpty()) { int size = queue.size(); // if(list.size()>=2) 移动到这里进行大值的判定! maxWidth = Math.max(list.getLast()-list.getFirst()+1, maxWidth); for(int i = 0; i < size; i++) { //从头取出(遍历完成时会将前一层的index移除,因为计算当前层的前后index关系是通过首位index 关系维护的) int index = list.removeFirst(); TreeNode node = queue.poll(); if(node.left!=null) { queue.offer(node.left); list.add(2*index); } if(node.right!=null) { queue.offer(node.right); list.add(2*index+1); } } //❌ list这里在循环中对应元素的index,队列中的元素移除清空时,list size ==0, LinkedList 中 getLast 和 getFirst 如果 last/first 为null 会报NoSuchElementException 运行时异常 , 所以这里可以将获取大值的判定移到for 循环体之前,当到达二叉树最后一层时,在for前计算完成,for计算完后queue/list均空,此时因为没有后续子节点,所以也没有比较的意义 故改变api调用位置,理解代码和实际使用场景的含义才能更好更合理的规避风险和认识本质 // if(list.size()>=2) // maxWidth = Math.max(list.getLast()-list.getFirst()+1, maxWidth); } return maxWidth; } //用于记录对应层数(对应数组index)的第一个起始位置index,用于持续更新maxWidth List<Integer> list = new ArrayList<>(); //base case ❌ 最少root 非null时置为1 int maxWidth=1; private int wobtRecursion(TreeNode root) { //初始化 root 节点处 level=0, index =1(level 为1 则需要从1位置开始add 和 get) if(root == null) return 0; recurHelper(root, 0, 1); return maxWidth; } private void recurHelper(TreeNode root, int level, int index) { //递归终止条件,屏蔽了之后左右子树中可能存在的null元素干扰,递归中root元素的index皆为有效index if(root == null) return; //说明为该level 对应层的第一个元素,记录当前层的最左index //❌ java 语法基础问题:如果list中对应index位置无元素,会BOIndex异常,这里改用 level 和 size 之间的关系,怎样判断当前递归到的是新的一层? // if(list.get(level)==null) { // if(level>=list.size()) { //说明当前level对应的index还不存在于list中,即level为新递归到的层数 // list.add(index); // } else { // //非第一个元素,通过当前层对应的最左index记录最大width // maxWidth = Math.max(maxWidth, index-list.get(level)+1); // } if(level==list.size()) { list.add(index); } //非第一个元素,通过当前层对应的最左index记录最大width maxWidth = Math.max(maxWidth, index-list.get(level)+1); recurHelper(root.left, level+1, 2*index); recurHelper(root.right, level+1, 2*index+1); } }
32.649123
283
0.526814
c658cf3378e6638183605554d836c40661c603b0
864
package com.ssrs.core.config; import lombok.Data; import org.springframework.stereotype.Component; /** * 支付宝配置类 * @author zhengjie.me * @date 2018/08/24 13:50:06 */ @Data @Component public class Alipay { /** * 应用ID,APPID,收款账号既是APPID对应支付宝账号 */ private String appID; /** * 商户私钥,您的PKCS8格式RSA2私钥 */ private String privateKey; /** * 支付宝公钥 */ private String publicKey; /** * 签名方式 */ private String signType; /** * 支付宝开放安全地址 */ private String gatewayUrl; /** * 编码 */ private String charset; /** * 异步通知地址 */ private String notifyUrl; /** * 订单完成后返回的页面 */ private String returnUrl; /** * 类型 */ private String format="JSON"; /** * 商户号 */ private String sysServiceProviderId; }
13.090909
48
0.540509
319e57194abb20d4bd0ba4fdc88158bf943c0688
1,333
package com.hgys.iptv.model; import static com.querydsl.core.types.PathMetadataFactory.*; import com.querydsl.core.types.dsl.*; import com.querydsl.core.types.PathMetadata; import javax.annotation.Generated; import com.querydsl.core.types.Path; /** * QSysLog is a Querydsl query type for SysLog */ @Generated("com.querydsl.codegen.EntitySerializer") public class QSysLog extends EntityPathBase<SysLog> { private static final long serialVersionUID = -1313341351L; public static final QSysLog sysLog = new QSysLog("sysLog"); public final NumberPath<Integer> id = createNumber("id", Integer.class); public final StringPath ip = createString("ip"); public final StringPath loginName = createString("loginName"); public final StringPath realName = createString("realName"); public final StringPath result = createString("result"); public final DateTimePath<java.sql.Timestamp> time = createDateTime("time", java.sql.Timestamp.class); public final StringPath type = createString("type"); public QSysLog(String variable) { super(SysLog.class, forVariable(variable)); } public QSysLog(Path<? extends SysLog> path) { super(path.getType(), path.getMetadata()); } public QSysLog(PathMetadata metadata) { super(SysLog.class, metadata); } }
26.66
106
0.723931
e5925710a7fb38f3e8c22eb3f52566ff254aca51
163
package com.sunshine.cloudhttp.server; /** * Server * * @author wangjn * @date 2019/3/31 */ public interface Server { void start(); void stop(); }
10.866667
38
0.613497
973b0a6b3a3cd9ce85acd3aabb039bd9de68d4db
1,785
/** * Copyright 2011 Booz Allen Hamilton. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Booz Allen Hamilton * 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.bah.culvert.adapter; import java.util.Iterator; import com.bah.culvert.data.Result; import com.bah.culvert.transactions.Get; import com.bah.culvert.util.BaseConfigurable; /** * Access the local table to perform the specified operations. */ public abstract class LocalTableAdapter extends BaseConfigurable { public static final String TABLE_NAME_SETTING = "culvert.adapter.tablename"; public String getTableName() { return this.getConf().get(TABLE_NAME_SETTING); } /** * Perform the specified get * * @param get on the local table * @return an {@link Iterator} over the results of the get * @throws TableException on failure to use the table */ public abstract Iterator<Result> get(Get get); /** * Gets the start key stored on a region * @return a byte[] representing the start key */ public abstract byte[] getStartKey(); /** * Gets the end key stored on a region * @return a byte[] representing the end key */ public abstract byte[] getEndKey(); }
30.775862
78
0.727171
d30c1b4e732905b7e4f0ea0e65c11d937b795351
913
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.airhacks.items.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQuery; /** * * @author Philip */ @Entity @NamedQuery(name = "SELECT_ALL_PRODUCER", query = "SELECT p FROM Producer p") @NamedQuery(name = "COUNT_ALL_PRODUCER", query = "SELECT count(p) FROM Producer p") public class Producer implements Serializable { @Id private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
20.288889
83
0.662651
143ef0c5e0f2781da9f3613bf4a1aeca665d963c
1,409
package com.midnightnoon.learn2code.springlearn2code; import com.biblia.BibleVerses; import com.midnightnoon.learn2code.springlearn2code.services.HelloWorldService; import com.midnightnoon.learn2code.springlearn2code.services.RestApiService; import com.midnightnoon.learn2code.springlearn2code.services.impl.PrintService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class SpringLearn2CodeApplication { public static void main(String[] args) { ApplicationContext kontext = SpringApplication.run(SpringLearn2CodeApplication.class, args); // String verse = kontext.getBean(BibleVerses.class).getVerse(); // System.out.println(verse); System.out.println(kontext.getBean(RestApiService.class).getTodo(1L)); //ak použijem Application listener (DataInit class) tak uz nepotrebujem pisat kod takto // //ulozim si kontext do premennej aby som ho mohol pouzivat // ApplicationContext context = // SpringApplication.run(SpringLearn2CodeApplication.class, args); // // //takto poviem Springu, ze chcem Bean pre danu triedu // AppRun appRun = context.getBean(AppRun.class); // appRun.run(); // // toto fungovat nebude, lebo som AppRun dotiahol mimo Spring, nemam implementaciu // AppRun appRun = new AppRun(); // appRun.run(); } }
36.128205
94
0.798439
e80adc7d444d54c8bd2ef45bb9a566bd9f8b13e7
4,775
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.webapp.fairscheduler; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.LocalConfigurationProvider; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static java.util.stream.Collectors.toList; /** * This class can generate an XML configuration file of custom resource types. * See createInitialResourceTypes for the default values. All custom resource * type is prefixed with CUSTOM_RESOURCE_PREFIX. Please use the * getConfigurationInputStream method to get an InputStream of the XML. If you * want to have different number of resources in your tests, please see usages * of this class in this test class: * {@link TestRMWebServicesFairSchedulerCustomResourceTypes} * */ public class CustomResourceTypesConfigurationProvider extends LocalConfigurationProvider { private static class CustomResourceTypes { private int count; private String xml; CustomResourceTypes(String xml, int count) { this.xml = xml; this.count = count; } public int getCount() { return count; } public String getXml() { return xml; } } private static final String CUSTOM_RESOURCE_PREFIX = "customResource-"; private static CustomResourceTypes customResourceTypes = createInitialResourceTypes(); private static CustomResourceTypes createInitialResourceTypes() { return createCustomResourceTypes(2); } private static CustomResourceTypes createCustomResourceTypes(int count) { List<String> resourceTypeNames = generateResourceTypeNames(count); List<String> resourceUnitXmlElements = IntStream.range(0, count) .boxed() .map(i -> getResourceUnitsXml(resourceTypeNames.get(i))) .collect(toList()); StringBuilder sb = new StringBuilder("<configuration>\n"); sb.append(getResourceTypesXml(resourceTypeNames)); for (String resourceUnitXml : resourceUnitXmlElements) { sb.append(resourceUnitXml); } sb.append("</configuration>"); return new CustomResourceTypes(sb.toString(), count); } private static List<String> generateResourceTypeNames(int count) { return IntStream.range(0, count) .boxed() .map(i -> CUSTOM_RESOURCE_PREFIX + i) .collect(toList()); } private static String getResourceUnitsXml(String resource) { return "<property>\n" + "<name>yarn.resource-types." + resource + ".units</name>\n" + "<value>k</value>\n" + "</property>\n"; } private static String getResourceTypesXml(List<String> resources) { final String resourceTypes = makeCommaSeparatedString(resources); return "<property>\n" + "<name>yarn.resource-types</name>\n" + "<value>" + resourceTypes + "</value>\n" + "</property>\n"; } private static String makeCommaSeparatedString(List<String> resources) { return resources.stream().collect(Collectors.joining(",")); } @Override public InputStream getConfigurationInputStream(Configuration bootstrapConf, String name) throws YarnException, IOException { if (YarnConfiguration.RESOURCE_TYPES_CONFIGURATION_FILE.equals(name)) { return new ByteArrayInputStream( customResourceTypes.getXml().getBytes()); } else { return super.getConfigurationInputStream(bootstrapConf, name); } } public static void reset() { customResourceTypes = createInitialResourceTypes(); } public static void setNumberOfResourceTypes(int count) { customResourceTypes = createCustomResourceTypes(count); } public static List<String> getCustomResourceTypes() { return generateResourceTypeNames(customResourceTypes.getCount()); } }
33.865248
78
0.73445
552afc95de4f41b7ed4943a10aac992d7bb080e4
7,097
package iurii.job.interview.cracking; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * Stacks and Queues */ public class CrackingCodingInterview3 { /** * 3.1 implement 3 stacks using one array. * This can be done in two ways. * 1) just divide array into 3 equal part (we do not know how stacks can be used). * 2) have pointers to previous blocks. each stack can grow while there are free space. * Problem appears when pop() operations are done and we do not track which blocks are free. * Extra array O(n) can be used to track free blocks. * <p> * Implementation with three equal */ public static class ArrayThreeStack { private int[] array = new int[99]; private int[] head = new int[3]; { head[0] = 0; head[1] = 33; head[2] = 66; } public void push(int stackNumber, int number) { array[head[stackNumber]++] = number; } public int pop(int stackNumber) { if (array.length / 3 * stackNumber > head[stackNumber] - 1) { throw new IllegalStateException(); } return array[--head[stackNumber]]; } } /** * 3.2 Implement stack to support min() operation. * Will use additional stack which will be used for adding value if it is min than the head * On pop operation we will pop from second stack * if min is poped. So head of the stack will contain correct min */ public static class MinStack extends Stack<Integer> { /** * */ private static final long serialVersionUID = -373249160326880405L; private Stack<Integer> minStack = new Stack<Integer>(); @Override public Integer push(Integer value) { if (value <= min()) { minStack.push(value); } return super.push(value); } @Override public Integer pop() { int popValue = super.pop(); if (popValue == minStack.peek()) { minStack.pop(); } return popValue; } public Integer min() { if (minStack.isEmpty()) { return Integer.MAX_VALUE; } else { return minStack.peek(); } } } /** * 3.3 implement Stack of stacks */ public static class SetOfStacks { private List<Stack<Integer>> stacks = new ArrayList<Stack<Integer>>(); private final int capacity; public SetOfStacks(int capacity) { this.capacity = capacity; } public Integer push(Integer value) { Stack<Integer> stack = getCurrentStack(); if (stack == null || stack.size() == capacity) { stack = new Stack<>(); stacks.add(stack); } return stack.push(value); } public Integer pop() { Stack<Integer> stack = getCurrentStack(); if (stack.isEmpty()) { stacks.remove(stack); stack = getCurrentStack(); } return stack.pop(); } private Stack<Integer> getCurrentStack() { if (stacks.isEmpty()) { return null; } else { return stacks.get(stacks.size() - 1); } } } /** * 3.4 implement Hanoi towers */ public static class Tower { private Stack<Integer> tower = new Stack<Integer>(); private final int index; public Tower(int index) { this.index = index; } public int index() { return index; } public void add(int d) { if (!tower.isEmpty() && tower.peek() < d) { throw new IllegalStateException(); } tower.push(d); } public void moveTopTo(Tower t) { t.add(tower.pop()); } public void moveDisks(int n, Tower destination, Tower buffer) { if (n > 0) { moveDisks(n - 1, buffer, destination); moveTopTo(destination); buffer.moveDisks(n - 1, destination, this); } } } /** * 3.5 Implement Queue using two stacks * * https://www.youtube.com/watch?v=m7ZYJkvWwlE * * https://www.glassdoor.com/Interview * /How-to-implement-a-queue-simply-using-two-stacks-and-how-to-implement-a-highly-efficient-queue-using-two-stacks-QTN_41158.htm * * */ public static class MyQueueBasedOnTwoStacks { private Stack<Integer> inbound = new Stack<Integer>(); private Stack<Integer> outbound = new Stack<Integer>(); public Integer push(Integer el) { inbound.push(el); return el; } public Integer pop() { if (outbound.isEmpty()) { while (!inbound.isEmpty()) { outbound.push(inbound.pop()); } } return outbound.pop(); } public Integer peek() { if (outbound.isEmpty()) { while (!inbound.isEmpty()) { outbound.push(inbound.pop()); } } return outbound.peek(); } public int size() { return inbound.size() + outbound.size(); } } /** * 3.5.1 Implement Queue using only one stack (+ Function call stack) * * https://www.youtube.com/watch?v=m7ZYJkvWwlE */ public static class MyQueueBasedOnOneStack { private Stack<Integer> inbound = new Stack<Integer>(); public Integer push(Integer el) { inbound.push(el); return el; } public Integer pop() { if (inbound.size() == 1) { return inbound.pop(); } else { Integer value = inbound.pop(); Integer result = pop(); inbound.push(value); return result; } } public Integer peek() { if (inbound.size() == 1) { return inbound.peek(); } else { Integer value = inbound.pop(); Integer result = peek(); inbound.push(value); return result; } } public int size() { return inbound.size(); } } /** * 3.6 Sort Stack using peek, pop, push, isEmpty. O(n^2) time no extra memory. */ public static Stack<Integer> sort(Stack<Integer> source) { Stack<Integer> result = new Stack<Integer>(); while (!source.isEmpty()) { Integer el = source.pop(); while (!result.isEmpty() && result.peek() < el) { source.push(result.pop()); } result.push(el); } return result; } }
27.191571
133
0.502889
e1bd3f3446917b30c3c31995b7f8acf68daa37a8
210
package com.ingic.template.retrofit; public class WebResponse<T> { private T results; public T getResults() { return results; } public void setResults(T results) { this.results = results; } }
10.5
36
0.690476
1b3834f25637a066984f766218c0521a7e1b15a3
889
package cat.indiketa.degiro.model; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.util.LinkedList; import java.util.List; @Data @Builder public class DCashFunds { private List<DCashFund> cashFunds; public DCashFunds(){ cashFunds = new LinkedList<>(); } public DCashFunds(List<DCashFund> cashFunds){ this.cashFunds = cashFunds; } @Data @Builder public static class DCashFund { private int id; private String currencyCode; private BigDecimal value; public DCashFund(){ } public DCashFund( int id, String currencyCode, BigDecimal value ){ this.id = id; this.currencyCode = currencyCode; this.value = value; } } }
19.326087
49
0.598425
b93a26a8879c9aee86c738a9878af87475890624
11,314
package com.conveyal.r5.speed_test.transit; import com.conveyal.gtfs.model.Stop; import com.conveyal.r5.profile.ProfileRequest; import com.conveyal.r5.profile.StreetPath; import com.conveyal.r5.profile.otp2.api.path.AccessPathLeg; import com.conveyal.r5.profile.otp2.api.path.EgressPathLeg; import com.conveyal.r5.profile.otp2.api.path.Path; import com.conveyal.r5.profile.otp2.api.path.PathLeg; import com.conveyal.r5.profile.otp2.api.path.TransferPathLeg; import com.conveyal.r5.profile.otp2.api.path.TransitPathLeg; import com.conveyal.r5.speed_test.api.model.AgencyAndId; import com.conveyal.r5.speed_test.api.model.Leg; import com.conveyal.r5.speed_test.api.model.Place; import com.conveyal.r5.speed_test.api.model.PolylineEncoder; import com.conveyal.r5.streets.StreetRouter; import com.conveyal.r5.transit.RouteInfo; import com.conveyal.r5.transit.TransitLayer; import com.conveyal.r5.transit.TransportNetwork; import com.conveyal.r5.transit.TripPattern; import com.conveyal.r5.transit.TripSchedule; import com.vividsolutions.jts.geom.Coordinate; import java.time.LocalDate; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.TimeZone; import java.util.stream.Collectors; public class ItineraryMapper2 { private TransportNetwork transportNetwork; private ProfileRequest request; private ItineraryMapper2(ProfileRequest request, TransportNetwork transportNetwork) { this.request = request; this.transportNetwork = transportNetwork; } public static ItinerarySet mapItineraries( ProfileRequest request, Collection<Path<TripSchedule>> paths, EgressAccessRouter streetRouter, TransportNetwork transportNetwork ) { ItineraryMapper2 mapper = new ItineraryMapper2(request, transportNetwork); ItinerarySet itineraries = new ItinerarySet(); for (Path<TripSchedule> p : paths) { StreetPath accessPath = streetRouter.accessPath(p.accessLeg().toStop()); StreetPath egressPath = streetRouter.egressPath(p.egressLeg().fromStop()); SpeedTestItinerary itinerary = mapper.createItinerary(p, accessPath, egressPath); itineraries.add(itinerary); } return itineraries; } private SpeedTestItinerary createItinerary(Path<TripSchedule> path, StreetPath accessPath, StreetPath egressPath) { SpeedTestItinerary itinerary = new SpeedTestItinerary(); if (path == null) { return null; } itinerary.walkDistance = 0.0; itinerary.transitTime = 0; itinerary.waitingTime = 0; itinerary.weight = path.cost(); int numberOfTransits = 0; int accessTime = accessPath.getDuration(); int egressTime = egressPath.getDuration(); List<Coordinate> acessCoords = accessPath.getEdges().stream() .map(t -> new Coordinate(accessPath.getEdge(t).getGeometry().getCoordinate().x, accessPath.getEdge(t).getGeometry().getCoordinate().y)).collect(Collectors.toList()); List<Coordinate> egressCoords = egressPath.getEdges().stream() .map(t -> new Coordinate(egressPath.getEdge(t).getGeometry().getCoordinate().x, egressPath.getEdge(t).getGeometry().getCoordinate().y)).collect(Collectors.toList()); Collections.reverse(egressCoords); // Access leg Leg leg = new Leg(); AccessPathLeg<TripSchedule> accessLeg = path.accessLeg(); Stop firstStop = transitLayer().stopForIndex.get(accessLeg.toStop()); leg.startTime = createCalendar(request.date, accessLeg.fromTime()); leg.endTime = createCalendar(request.date, accessLeg.toTime()); leg.from = new Place(request.fromLon, request.fromLat, "Origin"); leg.from.stopIndex = -1; leg.to = new Place(firstStop.stop_lat, firstStop.stop_lon, firstStop.stop_name); leg.to.stopId = new AgencyAndId("RB", firstStop.stop_id); leg.to.stopIndex = accessLeg.toStop(); leg.mode = "WALK"; leg.legGeometry = PolylineEncoder.createEncodings(acessCoords); leg.distance = distanceMMToMeters(accessPath.getDistance()); itinerary.addLeg(leg); PathLeg<TripSchedule> pathLeg = accessLeg.nextLeg(); int previousArrivalTime = -1; while (pathLeg.isTransitLeg() || pathLeg.isTransferLeg()) { leg = new Leg(); // Transfer leg if present if (pathLeg.isTransferLeg()) { TransferPathLeg it = pathLeg.asTransferLeg(); Stop fromStop = transitLayer().stopForIndex.get(it.fromStop()); Stop toStop = transitLayer().stopForIndex.get(it.toStop()); previousArrivalTime = it.toTime(); StreetPath transferPath = getWalkLegCoordinates(it.fromStop(), it.toStop()); List<Coordinate> transferCoords = transferPath.getEdges().stream() .map(t -> new Coordinate(transferPath.getEdge(t).getGeometry().getCoordinate().x, transferPath .getEdge(t).getGeometry().getCoordinate().y)).collect(Collectors.toList()); leg.startTime = createCalendar(request.date, it.fromTime()); leg.endTime = createCalendar(request.date, previousArrivalTime); leg.mode = "WALK"; leg.from = new Place(fromStop.stop_lat, fromStop.stop_lon, fromStop.stop_name); leg.to = new Place(toStop.stop_lat, toStop.stop_lon, toStop.stop_name); leg.legGeometry = PolylineEncoder.createEncodings(transferCoords); leg.distance = distanceMMToMeters (transferPath.getDistance()); } else { // Transit leg TransitPathLeg<TripSchedule> it = pathLeg.asTransitLeg(); Stop fromStop = transitLayer().stopForIndex.get(it.fromStop()); Stop toStop = transitLayer().stopForIndex.get(it.toStop()); itinerary.transitTime += it.toTime() - it.fromTime(); itinerary.waitingTime += it.fromTime() - previousArrivalTime; previousArrivalTime = it.toTime(); ++numberOfTransits; leg.distance = 0.0; TripSchedule tripSchedule = it.trip(); TripPattern tripPattern = tripSchedule.tripPattern(); RouteInfo routeInfo = transitLayer().routes.get(tripPattern.routeIndex); leg.from = new Place(fromStop.stop_lat, fromStop.stop_lon, fromStop.stop_name); leg.from.stopId = new AgencyAndId("RB", fromStop.stop_id); leg.from.stopIndex = it.fromStop(); leg.to = new Place(toStop.stop_lat, toStop.stop_lon, toStop.stop_name); leg.to.stopId = new AgencyAndId("RB", toStop.stop_id); leg.to.stopIndex = it.toStop(); leg.route = routeInfo.route_short_name; leg.agencyName = routeInfo.agency_name; leg.routeColor = routeInfo.color; leg.tripShortName = tripSchedule.tripId; leg.agencyId = routeInfo.agency_id; leg.routeShortName = routeInfo.route_short_name; leg.routeLongName = routeInfo.route_long_name; leg.mode = TransitLayer.getTransitModes(routeInfo.route_type).toString(); List<Coordinate> transitLegCoordinates = new ArrayList<>(); boolean boarded = false; for (int j = 0; j < tripPattern.stops.length; j++) { if (!boarded && tripSchedule.departures[j] == it.fromTime()) { boarded = true; } if (boarded) { transitLegCoordinates.add(new Coordinate(transitLayer().stopForIndex.get(tripPattern.stops[j]).stop_lon, transitLayer().stopForIndex.get(tripPattern.stops[j]).stop_lat)); } if (boarded && tripSchedule.arrivals[j] == it.toTime()) { break; } } leg.legGeometry = PolylineEncoder.createEncodings(transitLegCoordinates); leg.startTime = createCalendar(request.date, it.fromTime()); leg.endTime = createCalendar(request.date, it.toTime()); } itinerary.addLeg(leg); pathLeg = pathLeg.nextLeg(); } // Egress leg leg = new Leg(); EgressPathLeg<TripSchedule> egressLeg = pathLeg.asEgressLeg(); Stop lastStop = transitLayer().stopForIndex.get(egressLeg.fromStop()); leg.startTime = createCalendar(request.date, egressLeg.fromTime()); leg.endTime = createCalendar(request.date, egressLeg.fromTime() + egressTime); leg.from = new Place(lastStop.stop_lat, lastStop.stop_lon, lastStop.stop_name); leg.from.stopIndex = egressLeg.fromStop(); leg.from.stopId = new AgencyAndId("RB", lastStop.stop_id); leg.to = new Place(request.toLon, request.toLat, "Destination"); leg.mode = "WALK"; leg.legGeometry = PolylineEncoder.createEncodings(egressCoords); leg.distance = distanceMMToMeters (egressPath.getDistance()); itinerary.addLeg(leg); itinerary.startTime = itinerary.legs.get(0).startTime; itinerary.endTime = leg.endTime; itinerary.duration = (itinerary.endTime.getTimeInMillis() - itinerary.startTime.getTimeInMillis())/1000; // The number of transfers is the number of transits minus one, we can NOT count the number of Transfers // in the path or itinerary, because transfers at the same stop does not produce a transfer object, just two // transits following each other. itinerary.transfers = numberOfTransits-1; itinerary.initParetoVector(); return itinerary; } private TransitLayer transitLayer() { return transportNetwork.transitLayer; } private StreetPath getWalkLegCoordinates(int originStop, int destinationStop) { StreetRouter sr = new StreetRouter(transportNetwork.streetLayer); sr.profileRequest = new ProfileRequest(); int originStreetVertex = transitLayer().streetVertexForStop.get(originStop); sr.setOrigin(originStreetVertex); sr.quantityToMinimize = StreetRouter.State.RoutingVariable.DURATION_SECONDS; sr.distanceLimitMeters = 1000; sr.route(); StreetRouter.State transferState = sr.getStateAtVertex(transitLayer().streetVertexForStop .get(destinationStop)); return new StreetPath(transferState, transportNetwork, false); } private Calendar createCalendar(LocalDate date, int timeinSeconds) { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Oslo")); calendar.set(date.getYear(), date.getMonth().getValue(), date.getDayOfMonth() , 0, 0, 0); calendar.add(Calendar.SECOND, timeinSeconds); return calendar; } private double distanceMMToMeters(int distanceMm) { return (double) (distanceMm / 1000); } }
45.075697
181
0.651936
6bf6244684d26bc81ecd85957a5629500b505e1a
3,391
/* * Copyright 2015-2019 52°North Initiative for Geospatial Open Source * Software GmbH * * 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.n52.svalbard.encode; import java.util.Collections; import java.util.Set; import org.apache.xmlbeans.XmlObject; import org.n52.shetland.ogc.sos.Sos2Constants; import org.n52.shetland.ogc.sos.SosConstants; import org.n52.shetland.ogc.sos.delobs.DeleteObservationConstants; import org.n52.shetland.ogc.sos.delobs.DeleteObservationResponse; import org.n52.shetland.w3c.SchemaLocation; import org.n52.svalbard.encode.exception.EncodingException; import org.n52.svalbard.encode.exception.UnsupportedEncoderInputException; import com.google.common.collect.Sets; import net.opengis.sosdo.x10.DeleteObservationResponseDocument; import net.opengis.sosdo.x10.DeleteObservationResponseType; /** * @author <a href="mailto:[email protected]">Eike Hinderk J&uuml;rrens</a> * @since 1.0.0 */ public class DeleteObservationEncoder extends AbstractResponseEncoder<DeleteObservationResponse> { public static final SchemaLocation SCHEMA_LOCATION = new SchemaLocation(DeleteObservationConstants.NS_SOSDO_1_0, DeleteObservationConstants.NS_SOSDO_1_0_SCHEMA_LOCATION); public DeleteObservationEncoder() { super(SosConstants.SOS, Sos2Constants.SERVICEVERSION, DeleteObservationConstants.Operations.DeleteObservation.name(), DeleteObservationConstants.NS_SOSDO_1_0, DeleteObservationConstants.NS_SOSDO_PREFIX, DeleteObservationResponse.class); } @Override public Set<String> getConformanceClasses(String service, String version) { if (SosConstants.SOS.equals(service) && Sos2Constants.SERVICEVERSION.equals(version)) { return Collections.unmodifiableSet(DeleteObservationConstants.CONFORMANCE_CLASSES); } return Collections.emptySet(); } @Override protected XmlObject create(DeleteObservationResponse dor) throws EncodingException { if (dor == null) { throw new UnsupportedEncoderInputException(this, DeleteObservationResponse.class); } String observationId = dor.getObservationId(); DeleteObservationResponseDocument xbDeleteObsDoc = DeleteObservationResponseDocument.Factory .newInstance(getXmlOptions()); DeleteObservationResponseType xbDeleteObservationResponse = xbDeleteObsDoc.addNewDeleteObservationResponse(); xbDeleteObservationResponse.setDeletedObservation(observationId); return xbDeleteObsDoc; } @Override public Set<SchemaLocation> getSchemaLocations() { return Sets.newHashSet(SCHEMA_LOCATION); } @Override protected Set<SchemaLocation> getConcreteSchemaLocations() { return Sets.newHashSet(); } }
39.430233
117
0.747272
b9909239df2438cc2c26cf38a78e8a935eaf8955
1,187
/* * Copyright 2016 Jean-Bernard van Zuylen * * 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.primeoservices.cfgateway.jms.utils; public class CastUtils { /** * This utilities class should never be initialized */ private CastUtils() { } public static boolean toBooleanValue(final Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); return false; } public static int toIntValue(final Object o) { if (o instanceof Integer) return ((Integer) o).intValue(); return 0; } public static long toLongValue(final Object o) { if (o instanceof Long) return ((Long) o).longValue(); return 0; } }
26.377778
75
0.706824
0240158b25f09ce22e04561c3cce22cd908336b0
4,632
package seedu.address.model; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.VALID_ADDRESS_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND; import static seedu.address.testutil.Assert.assertThrows; import static seedu.address.testutil.TypicalAddressBook.getTypicalAddressBook; import static seedu.address.testutil.TypicalProperties.P_ALICE; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import seedu.address.model.property.Buyer; import seedu.address.model.property.Match; import seedu.address.model.property.Property; import seedu.address.model.property.exceptions.DuplicatePropertyException; import seedu.address.testutil.PropertyBuilder; public class AddressBookTest { private final AddressBook addressBook = new AddressBook(); @Test public void constructor() { assertEquals(Collections.emptyList(), addressBook.getPropertyList()); } @Test public void resetData_null_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> addressBook.resetData(null)); } @Test public void resetData_withValidReadOnlyAddressBook_replacesData() { AddressBook newData = getTypicalAddressBook(); addressBook.resetData(newData); assertEquals(newData, addressBook); } @Test public void resetData_withDuplicateProperties_throwsDuplicatePropertyException() { // Two properties with the same identity fields Property editedAlice = new PropertyBuilder(P_ALICE).withAddress(VALID_ADDRESS_BOB).withTags(VALID_TAG_HUSBAND) .build(); List<Property> newProperties = Arrays.asList(P_ALICE, editedAlice); AddressBookStub newData = new AddressBookStub(newProperties); assertThrows(DuplicatePropertyException.class, () -> addressBook.resetData(newData)); } @Test public void hasProperty_nullProperty_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> addressBook.hasProperty(null)); } @Test public void hasProperty_propertyNotInAddressBook_returnsFalse() { assertFalse(addressBook.hasProperty(P_ALICE)); } @Test public void hasProperty_propertyInAddressBook_returnsTrue() { addressBook.addProperty(P_ALICE); assertTrue(addressBook.hasProperty(P_ALICE)); } @Test public void hasProperty_propertyWithSameIdentityFieldsInAddressBook_returnsTrue() { addressBook.addProperty(P_ALICE); Property editedAlice = new PropertyBuilder(P_ALICE).withAddress(VALID_ADDRESS_BOB).withTags(VALID_TAG_HUSBAND) .build(); assertTrue(addressBook.hasProperty(editedAlice)); } @Test public void getPropertyList_modifyList_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> addressBook.getPropertyList().remove(0)); } /** * A stub ReadOnlyAddressBook whose properties list can violate interface constraints. */ private static class AddressBookStub implements ReadOnlyAddressBook { private final ObservableList<Property> properties = FXCollections.observableArrayList(); private final ObservableList<Property> currProperties = FXCollections.observableArrayList(); private final ObservableList<Buyer> buyers = FXCollections.observableArrayList(); private final ObservableList<Buyer> currBuyers = FXCollections.observableArrayList(); private final ObservableList<Match> matches = FXCollections.observableArrayList(); AddressBookStub(Collection<Property> properties) { this.properties.setAll(properties); } @Override public ObservableList<Property> getPropertyList() { return properties; } @Override public ObservableList<Buyer> getBuyerList() { return buyers; } @Override public ObservableList<Property> getCurrPropertyList() { return currProperties; } @Override public ObservableList<Buyer> getCurrBuyerList() { return currBuyers; } @Override public ObservableList<Match> getMatchList() { return matches; } } }
35.906977
118
0.733377
bc0782db937d9ebf069d0a700f6da2bcbb795174
4,037
/* * The MIT License (MIT) * * Copyright (c) 2014 LeanIX GmbH * * 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.smartfacts.mid.api.models; import com.fasterxml.jackson.annotation.JsonProperty; public class DiagramOccurrence { private String id = null; private String elementId = null; private String versionId = null; private String name = null; private String description = null; private String type = null; private Boolean isAttachment = null; private Boolean isDiagram = null; private Boolean hasAttachmentPreview = null; @JsonProperty("id") public String getId() { return id; } @JsonProperty("id") public void setId(String id) { this.id = id; } @JsonProperty("elementId") public String getElementId() { return elementId; } @JsonProperty("elementId") public void setElementId(String elementId) { this.elementId = elementId; } @JsonProperty("versionId") public String getVersionId() { return versionId; } @JsonProperty("versionId") public void setVersionId(String versionId) { this.versionId = versionId; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("description") public String getDescription() { return description; } @JsonProperty("description") public void setDescription(String description) { this.description = description; } @JsonProperty("type") public String getType() { return type; } @JsonProperty("type") public void setType(String type) { this.type = type; } @JsonProperty("isAttachment") public Boolean getIsAttachment() { return isAttachment; } @JsonProperty("isAttachment") public void setIsAttachment(Boolean isAttachment) { this.isAttachment = isAttachment; } @JsonProperty("isDiagram") public Boolean getIsDiagram() { return isDiagram; } @JsonProperty("isDiagram") public void setIsDiagram(Boolean isDiagram) { this.isDiagram = isDiagram; } @JsonProperty("hasAttachmentPreview") public Boolean getHasAttachmentPreview() { return hasAttachmentPreview; } @JsonProperty("hasAttachmentPreview") public void setHasAttachmentPreview(Boolean hasAttachmentPreview) { this.hasAttachmentPreview = hasAttachmentPreview; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DiagramOccurrence {\n"); sb.append(" id: ").append(id).append("\n"); sb.append(" elementId: ").append(elementId).append("\n"); sb.append(" versionId: ").append(versionId).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append(" description: ").append(description).append("\n"); sb.append(" type: ").append(type).append("\n"); sb.append(" isAttachment: ").append(isAttachment).append("\n"); sb.append(" isDiagram: ").append(isDiagram).append("\n"); sb.append(" hasAttachmentPreview: ").append(hasAttachmentPreview).append("\n"); sb.append("}\n"); return sb.toString(); } }
24.466667
82
0.726034
76e2d8f80cc60e69fd24f6b22d903028fcdcba56
1,218
package com.putao.ptx.qrcode.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.widget.TextView; import com.putao.ptx.qrcode.R; import com.putao.ptx.qrcode.base.BaseActivity; public class ScanResultActivity extends BaseActivity { public static final String KEY_CONTENT = "content"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_result); String content = getIntent().getStringExtra(KEY_CONTENT); TextView tv_content = (TextView) findViewById(R.id.tv_content); tv_content.setText(content); //超链接相关字符识别 tv_content.setAutoLinkMask(Linkify.ALL); tv_content.setMovementMethod(LinkMovementMethod.getInstance()); } public static void luncher(Context context, String content) { Intent intent = new Intent(context, ScanResultActivity.class); intent.putExtra(KEY_CONTENT, content); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }
31.230769
71
0.740558
cf5b875211c14c78f20ee09c48d7df0f23d0e3da
4,836
package com.example; import javaemul.internal.annotations.DoNotAutobox; import javaemul.internal.annotations.HasNoSideEffects; import javax.annotation.Generated; import javax.annotation.Nonnull; import javax.annotation.Nullable; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsNonNull; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import jsinterop.base.Js; @Generated("org.realityforge.webtack") @JsType( isNative = true, namespace = JsPackage.GLOBAL, name = "Window" ) public class Window extends EventTarget { /** * The Window.name property gets/sets the name of the window's browsing context. */ @JsNonNull public String name; protected Window() { } @JsProperty( name = "closed" ) public native boolean closed(); /** * The window.isSecureContext read-only property indicates whether a context is capable of using features that require secure contexts. * * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/isSecureContext">Window.isSecureContext - MDN</a> * @see <a href="https://w3c.github.io/webappsec-secure-contexts/">Secure Contexts</a> */ @JsProperty( name = "isSecureContext" ) public native boolean isSecureContext(); @JsProperty( name = "navigator" ) @Nonnull public native Navigator navigator(); public native void postMessage(@DoNotAutobox @Nullable java.lang.Object message, @Nonnull String targetOrigin, @Nonnull JsArray<Transferable2> transfer); @JsOverlay public final void postMessage(@DoNotAutobox @Nullable final java.lang.Object message, @Nonnull final String targetOrigin, @Nonnull final Transferable2... transfer) { _postMessage( message, targetOrigin, transfer ); } @JsMethod( name = "postMessage" ) private native void _postMessage(@DoNotAutobox @Nullable java.lang.Object message, @Nonnull String targetOrigin, @Nonnull Transferable2[] transfer); public native void postMessage(@DoNotAutobox @Nullable java.lang.Object message, @Nonnull String targetOrigin); public native void scroll(double x, double y); public native void scroll(@Nonnull ScrollToOptions options); public native void scroll(); @HasNoSideEffects @JsNonNull public native Object get(@Nonnull String name); @JsOverlay public final void addDOMContentLoadedListener(@Nonnull final EventListener callback, @Nonnull final AddEventListenerOptions options) { addEventListener( "DOMContentLoaded", Js.cast( callback ), options ); } @JsOverlay public final void addDOMContentLoadedListener(@Nonnull final EventListener callback, final boolean useCapture) { addEventListener( "DOMContentLoaded", Js.cast( callback ), useCapture ); } @JsOverlay public final void addDOMContentLoadedListener(@Nonnull final EventListener callback) { addEventListener( "DOMContentLoaded", Js.cast( callback ) ); } @JsOverlay public final void removeDOMContentLoadedListener(@Nonnull final EventListener callback, @Nonnull final EventListenerOptions options) { removeEventListener( "DOMContentLoaded", Js.cast( callback ), options ); } @JsOverlay public final void removeDOMContentLoadedListener(@Nonnull final EventListener callback, final boolean useCapture) { removeEventListener( "DOMContentLoaded", Js.cast( callback ), useCapture ); } @JsOverlay public final void removeDOMContentLoadedListener(@Nonnull final EventListener callback) { removeEventListener( "DOMContentLoaded", Js.cast( callback ) ); } @JsOverlay public final void addFocusListener(@Nonnull final FocusEventListener callback, @Nonnull final AddEventListenerOptions options) { addEventListener( "focus", Js.cast( callback ), options ); } @JsOverlay public final void addFocusListener(@Nonnull final FocusEventListener callback, final boolean useCapture) { addEventListener( "focus", Js.cast( callback ), useCapture ); } @JsOverlay public final void addFocusListener(@Nonnull final FocusEventListener callback) { addEventListener( "focus", Js.cast( callback ) ); } @JsOverlay public final void removeFocusListener(@Nonnull final FocusEventListener callback, @Nonnull final EventListenerOptions options) { removeEventListener( "focus", Js.cast( callback ), options ); } @JsOverlay public final void removeFocusListener(@Nonnull final FocusEventListener callback, final boolean useCapture) { removeEventListener( "focus", Js.cast( callback ), useCapture ); } @JsOverlay public final void removeFocusListener(@Nonnull final FocusEventListener callback) { removeEventListener( "focus", Js.cast( callback ) ); } }
32.24
137
0.747725
f5c2dfc994b072eeeb863567b33413ed4c9cfae7
13,044
package com.espressif.iot.model.device.cache; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.log4j.Logger; import android.content.Context; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import com.espressif.iot.base.application.EspApplication; import com.espressif.iot.device.IEspDevice; import com.espressif.iot.device.cache.IEspDeviceCache; import com.espressif.iot.object.IEspSingletonObject; import com.espressif.iot.type.net.IOTAddress; import com.espressif.iot.user.IEspUser; import com.espressif.iot.user.builder.BEspUser; import com.espressif.iot.util.EspStrings; public class EspDeviceCache implements IEspDeviceCache, IEspSingletonObject { private final static Logger log = Logger.getLogger(EspDeviceCache.class); private Queue<IEspDevice> mTransformedDeviceCacheQueue; private Queue<IEspDevice> mServerLocalDeviceCacheQueue; private Queue<IOTAddress> mLocalDeviceIOTAddressQueue; private Queue<IEspDevice> mStatemachineDeviceCacheQueue; private Queue<IEspDevice> mSharedDeviceCacheQueue; private Queue<IOTAddress> mUpgradeSucLocalDeviceCacheQueue; private Queue<IOTAddress> mStaDeviceIOTAddressQueue; /* * Singleton lazy initialization start */ private EspDeviceCache() { mTransformedDeviceCacheQueue = new ConcurrentLinkedQueue<IEspDevice>(); mServerLocalDeviceCacheQueue = new ConcurrentLinkedQueue<IEspDevice>(); mLocalDeviceIOTAddressQueue = new ConcurrentLinkedQueue<IOTAddress>(); mStatemachineDeviceCacheQueue = new ConcurrentLinkedQueue<IEspDevice>(); mSharedDeviceCacheQueue = new ConcurrentLinkedQueue<IEspDevice>(); mUpgradeSucLocalDeviceCacheQueue = new ConcurrentLinkedQueue<IOTAddress>(); mStaDeviceIOTAddressQueue = new ConcurrentLinkedQueue<IOTAddress>(); } private static class InstanceHolder { static EspDeviceCache instance = new EspDeviceCache(); } public static EspDeviceCache getInstance() { return InstanceHolder.instance; } /* * Singleton lazy initialization end */ @Override public void clear() { synchronized (mTransformedDeviceCacheQueue) { mTransformedDeviceCacheQueue.clear(); } synchronized (mServerLocalDeviceCacheQueue) { mServerLocalDeviceCacheQueue.clear(); } synchronized (mLocalDeviceIOTAddressQueue) { mLocalDeviceIOTAddressQueue.clear(); } synchronized (mStatemachineDeviceCacheQueue) { mStatemachineDeviceCacheQueue.clear(); } synchronized (mSharedDeviceCacheQueue) { mSharedDeviceCacheQueue.clear(); } synchronized (mUpgradeSucLocalDeviceCacheQueue) { mUpgradeSucLocalDeviceCacheQueue.clear(); } synchronized (mStaDeviceIOTAddressQueue) { mStaDeviceIOTAddressQueue.clear(); } } @Override public boolean addTransformedDeviceCache(IEspDevice device) { boolean result; synchronized (mTransformedDeviceCacheQueue) { result = mTransformedDeviceCacheQueue.add(device); } log.info(Thread.currentThread().toString() + "##addTransformedDeviceCache(device=[" + device + "]): " + result); return result; } @Override public boolean addTransformedDeviceCacheList(List<IEspDevice> deviceList) { boolean result; synchronized (mTransformedDeviceCacheQueue) { result = mTransformedDeviceCacheQueue.addAll(deviceList); } log.info(Thread.currentThread().toString() + "##addTransformedDeviceCacheList(deviceList=[" + deviceList + "]): " + result); return result; } @Override public List<IEspDevice> pollTransformedDeviceCacheList() { List<IEspDevice> result = new ArrayList<IEspDevice>(); IEspDevice device = null; synchronized (mTransformedDeviceCacheQueue) { device = mTransformedDeviceCacheQueue.poll(); while (device != null) { result.add(device); device = mTransformedDeviceCacheQueue.poll(); } } log.info(Thread.currentThread().toString() + "##pollTransformedDeviceCacheList(): " + result); return result; } @Override public boolean addServerLocalDeviceCache(IEspDevice device) { boolean result; synchronized (mServerLocalDeviceCacheQueue) { result = mServerLocalDeviceCacheQueue.add(device); } log.info(Thread.currentThread().toString() + "##addServerLocalDeviceCache(device=[" + device + "]): " + result); return result; } @Override public boolean addServerLocalDeviceCacheList(List<IEspDevice> deviceList) { boolean result; synchronized (mServerLocalDeviceCacheQueue) { result = mServerLocalDeviceCacheQueue.addAll(deviceList); } log.info(Thread.currentThread().toString() + "##addServerLocalDeviceCacheList(deviceList=[" + deviceList + "]): " + result); return result; } @Override public List<IEspDevice> pollServerLocalDeviceCacheList() { List<IEspDevice> result = new ArrayList<IEspDevice>(); IEspDevice device = null; synchronized (mServerLocalDeviceCacheQueue) { device = mServerLocalDeviceCacheQueue.poll(); while (device != null) { result.add(device); device = mServerLocalDeviceCacheQueue.poll(); } } log.info(Thread.currentThread().toString() + "##pollServerLocalDeviceCacheList(): " + result); return result; } @Override public boolean addLocalDeviceCacheList(List<IOTAddress> deviceIOTAddressList) { boolean result; synchronized (mLocalDeviceIOTAddressQueue) { result = mLocalDeviceIOTAddressQueue.addAll(deviceIOTAddressList); } log.info(Thread.currentThread().toString() + "##addLocalDeviceCacheList(deviceIOTAddressList=[" + deviceIOTAddressList + "]): " + result); return result; } @Override public List<IOTAddress> pollLocalDeviceCacheList() { List<IOTAddress> result = new ArrayList<IOTAddress>(); IOTAddress iotAddress = null; synchronized (mLocalDeviceIOTAddressQueue) { iotAddress = mLocalDeviceIOTAddressQueue.poll(); while (iotAddress != null) { result.add(iotAddress); iotAddress = mLocalDeviceIOTAddressQueue.poll(); } } log.info(Thread.currentThread().toString() + "##pollLocalDeviceCacheList(): " + result); return result; } @Override public boolean addStatemahchineDeviceCache(IEspDevice device) { boolean result; synchronized (mStatemachineDeviceCacheQueue) { result = mStatemachineDeviceCacheQueue.add(device); } log.info(Thread.currentThread().toString() + "##addStatemahchineDeviceCache(device=[" + device + "]): " + result); return result; } @Override public IEspDevice pollStatemachineDeviceCache() { IEspDevice result = null; synchronized (mStatemachineDeviceCacheQueue) { result = mStatemachineDeviceCacheQueue.poll(); } log.info(Thread.currentThread().toString() + "##pollStatemachineDeviceCache(): " + result); return result; } @Override public boolean addSharedDeviceCache(IEspDevice device) { boolean result; synchronized (mSharedDeviceCacheQueue) { result = mSharedDeviceCacheQueue.add(device); } log.info(Thread.currentThread().toString() + "##addSharedDeviceCache(device=[" + device + "]): " + result); return result; } @Override public IEspDevice pollSharedDeviceCache() { IEspDevice result = null; synchronized (mSharedDeviceCacheQueue) { result = mSharedDeviceCacheQueue.poll(); } log.info(Thread.currentThread().toString() + "##pollSharedDeviceQueue(): " + result); return result; } @Override public boolean addUpgradeSucLocalDeviceCacheList(List<IOTAddress> deviceIOTAddressList) { boolean result; synchronized (mUpgradeSucLocalDeviceCacheQueue) { result = mUpgradeSucLocalDeviceCacheQueue.addAll(deviceIOTAddressList); } log.info(Thread.currentThread().toString() + "##addUpgradeSucLocalDeviceCacheList(deviceIOTAddressList=[" + deviceIOTAddressList + "]): " + result); return result; } @Override public List<IOTAddress> pollUpgradeSucLocalDeviceCacheList() { List<IOTAddress> result = new ArrayList<IOTAddress>(); IOTAddress iotAddress = null; synchronized (mUpgradeSucLocalDeviceCacheQueue) { iotAddress = mUpgradeSucLocalDeviceCacheQueue.poll(); while (iotAddress != null) { result.add(iotAddress); iotAddress = mUpgradeSucLocalDeviceCacheQueue.poll(); } } log.info(Thread.currentThread().toString() + "##pollUpgradeSucLocalDeviceCacheList(): " + result); return result; } @Override public boolean addStaDeviceCache(IOTAddress deviceStaDevice) { boolean result; synchronized (mStaDeviceIOTAddressQueue) { result = mStaDeviceIOTAddressQueue.add(deviceStaDevice); } log.info(Thread.currentThread().toString() + "##addSharedDeviceCache(deviceStaDevice=[" + deviceStaDevice + "]): " + result); return result; } @Override public boolean addStaDeviceCacheList(List<IOTAddress> deviceStaDeviceList) { boolean result; synchronized (mStaDeviceIOTAddressQueue) { result = mStaDeviceIOTAddressQueue.addAll(deviceStaDeviceList); } log.info(Thread.currentThread().toString() + "##devieStaDeviceList(deviceStaDeviceList=[" + deviceStaDeviceList + "]): " + result); return result; } @Override public List<IOTAddress> pollStaDeviceCacheList() { List<IOTAddress> result = new ArrayList<IOTAddress>(); IOTAddress iotAddress = null; synchronized (mStaDeviceIOTAddressQueue) { iotAddress = mStaDeviceIOTAddressQueue.poll(); while (iotAddress != null) { result.add(iotAddress); iotAddress = mStaDeviceIOTAddressQueue.poll(); } } log.info(Thread.currentThread().toString() + "##pollStaDeviceCacheList(): " + result); return result; } @Override public void notifyIUser(NotifyType type) { log.info(Thread.currentThread().toString() + "##notifyIUser(NofityType=[" + type + "])"); Context context = EspApplication.sharedInstance().getApplicationContext(); LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(context); Intent intent = null; switch (type) { case PULL_REFRESH: intent = new Intent(EspStrings.Action.DEVICES_ARRIVE_PULLREFRESH); broadcastManager.sendBroadcast(intent); break; case STATE_MACHINE_UI: intent = new Intent(EspStrings.Action.DEVICES_ARRIVE_STATEMACHINE); broadcastManager.sendBroadcast(intent); break; case STATE_MACHINE_BACKSTATE: IEspUser user = BEspUser.getBuilder().getInstance(); user.doActionDevicesUpdated(true); break; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{mTransforedDeviceCacheQueue: " + mTransformedDeviceCacheQueue + "\n"); sb.append("mServerLocalDeviceCacheQueue: " + mServerLocalDeviceCacheQueue + "\n"); sb.append("mLocalDeviceIOTAddressQueue: " + mLocalDeviceIOTAddressQueue + "\n"); sb.append("mStatemachineDeviceCacheQueue: " + mStatemachineDeviceCacheQueue + "\n"); sb.append("mSharedDeviceCacheQueue: " + mSharedDeviceCacheQueue + "\n"); sb.append("mUpgradeSucLocalDeviceCacheQueue: " + mUpgradeSucLocalDeviceCacheQueue + "\n"); sb.append("mStaDeviceIOTAddressQueue: " + mStaDeviceIOTAddressQueue + "}\n"); return sb.toString(); } }
33.792746
120
0.637381
0a4ba0eb95255409a93d9504f583139857f7e857
1,867
package ai.djl.quarkus.runtime; import java.io.IOException; import ai.djl.Application; import ai.djl.MalformedModelException; import ai.djl.inference.Predictor; import ai.djl.repository.zoo.Criteria; import ai.djl.repository.zoo.ModelNotFoundException; import ai.djl.repository.zoo.ModelZoo; import ai.djl.repository.zoo.ZooModel; import io.quarkus.arc.runtime.BeanContainer; import io.quarkus.runtime.RuntimeValue; import io.quarkus.runtime.annotations.Recorder; /** * A helper to initialize a {@link DjlPredictorProducer}. */ @Recorder public class DjlPredictorRecorder { public RuntimeValue<ZooModel<?, ?>> initializePredictor(DjlModelConfiguration configuration) throws ClassNotFoundException, MalformedModelException, ModelNotFoundException, IOException { Class<?> inCls = Class.forName(configuration.inputClass); Class<?> outCls = Class.forName(configuration.outputClass); Criteria.Builder<?, ?> criteria = Criteria.builder() .setTypes(inCls, outCls) .optFilters(configuration.filters); configuration.application.ifPresent(application -> criteria.optApplication(Application.of(application))); configuration.engine.ifPresent(criteria::optEngine); configuration.groupId.ifPresent(criteria::optGroupId); configuration.artifactId.ifPresent(criteria::optArtifactId); configuration.modelName.ifPresent(criteria::optModelName); ZooModel<?, ?> model = ModelZoo.loadModel(criteria.build()); return new RuntimeValue<>(model); } public void configureDjlPredictorProducer(BeanContainer beanContainer, RuntimeValue<ZooModel<?, ?>> modelHolder) { DjlPredictorProducer predictorProducer = beanContainer.instance(DjlPredictorProducer.class); predictorProducer.initialize(modelHolder.getValue()); } }
40.586957
113
0.746652
d12daafc88ac2beaab36f9431f7de56151735e63
1,536
package me.matteomerola.codicefiscale; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class CityParser { private static String DB_NAME = "dbcf.csv"; private static InputStream INPUT = CityParser.class .getClassLoader().getResourceAsStream(DB_NAME); private static BufferedReader READER = new BufferedReader( new InputStreamReader(INPUT)); private static List<City> CITY_DB; private static List<City> parse() { List<City> cities = new ArrayList<>(); String line; try { line = READER.readLine(); } catch (IOException e) { e.printStackTrace(); return cities; } while (line != null) { try { StringTokenizer tokenizer = new StringTokenizer(line, ";"); String name = tokenizer.nextToken(); String province = tokenizer.nextToken(); String fiscalCode = tokenizer.nextToken(); City city = new City(name, province, fiscalCode); cities.add(city); line = READER.readLine(); } catch (IOException e) { e.printStackTrace(); return cities; } } return cities; } /** * This method returns the list of city that are into the database. * @param refresh A boolean value indicating whether or not to parse again the cvs database. * @return A List of City. */ public static List<City> getCityDb(boolean refresh) { if (CITY_DB == null || refresh) { CITY_DB = parse(); } return CITY_DB; } }
26.033898
92
0.70638
94d8c29fbd73d64a57a3ee70980412ccb06c2a7e
187
package com.sushanqiang.statelayout.bean; /** * desc : 加载数据对象 */ public class LoadingItem extends BaseItem { public LoadingItem(String tip) { setTip(tip); } }
13.357143
43
0.631016
7c3a37130b8039dcca79be7b80fbaf00b03e0eaf
3,057
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * 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.kuali.rice.core.api.search; import org.apache.commons.lang.StringUtils; /** * Represents a search range */ public class Range { private String lowerBoundValue; private String upperBoundValue; private boolean lowerBoundInclusive = true; private boolean upperBoundInclusive = true; public String getLowerBoundValue() { return lowerBoundValue; } public void setLowerBoundValue(String lowerBoundValue) { this.lowerBoundValue = lowerBoundValue; } public String getUpperBoundValue() { return upperBoundValue; } public void setUpperBoundValue(String upperBoundValue) { this.upperBoundValue = upperBoundValue; } public boolean isLowerBoundInclusive() { return lowerBoundInclusive; } public void setLowerBoundInclusive(boolean lowerBoundInclusive) { this.lowerBoundInclusive = lowerBoundInclusive; } public boolean isUpperBoundInclusive() { return upperBoundInclusive; } public void setUpperBoundInclusive(boolean upperBoundInclusive) { this.upperBoundInclusive = upperBoundInclusive; } public String toString() { if (StringUtils.isNotEmpty(lowerBoundValue) && StringUtils.isNotEmpty(upperBoundValue)) { SearchOperator op; if (lowerBoundInclusive && upperBoundInclusive) { op = SearchOperator.BETWEEN; } else if (lowerBoundInclusive && !upperBoundInclusive) { op = SearchOperator.BETWEEN_EXCLUSIVE_UPPER2; } else if (!lowerBoundInclusive && upperBoundInclusive) { op = SearchOperator.BETWEEN_EXCLUSIVE_LOWER; } else { op = SearchOperator.BETWEEN_EXCLUSIVE; } return lowerBoundValue + op.op() + upperBoundValue; } else if (StringUtils.isNotEmpty(lowerBoundValue) && StringUtils.isEmpty(upperBoundValue)) { SearchOperator op = lowerBoundInclusive ? SearchOperator.GREATER_THAN_EQUAL : SearchOperator.GREATER_THAN; return op.op() + lowerBoundValue; } else if (StringUtils.isNotEmpty(upperBoundValue) && StringUtils.isEmpty(lowerBoundValue)) { SearchOperator op = upperBoundInclusive ? SearchOperator.LESS_THAN_EQUAL : SearchOperator.LESS_THAN; return op.op() + upperBoundValue; } else { // both are empty return ""; } } }
35.964706
118
0.689892
bd0230a3e78cf53079831ed0683303985596368a
22,313
package org.telegram.android.fragments; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.Telephony; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import org.telegram.android.R; import org.telegram.android.base.TelegramActivity; import org.telegram.android.core.ContactsSource; import org.telegram.android.core.model.Contact; import org.telegram.android.core.model.LinkType; import org.telegram.android.core.model.PeerType; import org.telegram.android.core.model.User; import org.telegram.android.core.model.update.TLLocalAffectedHistory; import org.telegram.android.core.wireframes.ContactWireframe; import org.telegram.android.fragments.common.BaseContactsFragment; import org.telegram.android.tasks.AsyncAction; import org.telegram.android.tasks.AsyncException; import org.telegram.android.ui.pick.PickIntentClickListener; import org.telegram.android.ui.pick.PickIntentDialog; import org.telegram.android.ui.pick.PickIntentItem; import org.telegram.api.TLAbsInputUser; import org.telegram.api.TLInputPeerContact; import org.telegram.api.TLInputUserContact; import org.telegram.api.messages.TLAffectedHistory; import org.telegram.api.requests.TLRequestContactsBlock; import org.telegram.api.requests.TLRequestContactsDeleteContacts; import org.telegram.api.requests.TLRequestMessagesDeleteHistory; import org.telegram.tl.TLVector; /** * Author: Korshakov Stepan * Created: 30.07.13 11:33 */ public class ContactsFragment extends BaseContactsFragment { private View share; @Override public boolean isSaveInStack() { return true; } @Override protected void onFilterChanged() { if (share != null) { if (isFiltering()) { share.findViewById(R.id.container).setVisibility(View.GONE); } else { share.findViewById(R.id.container).setVisibility(View.VISIBLE); } } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSherlockActivity().getSupportActionBar().setDisplayShowHomeEnabled(false); getSherlockActivity().getSupportActionBar().setTitle(highlightTitleText(R.string.st_contacts_title)); getSherlockActivity().getSupportActionBar().setSubtitle(null); if (!isLoaded()) { return; } inflater.inflate(R.menu.contacts_menu, menu); menu.findItem(R.id.systemContacts).setTitle(highlightMenuText(R.string.st_contacts_menu_book)); menu.findItem(R.id.addContact).setTitle(highlightMenuText(R.string.st_contacts_menu_add_contact)); menu.findItem(R.id.allContacts).setTitle(highlightMenuText(R.string.st_contacts_menu_all_contacts)); menu.findItem(R.id.onlyTContacts).setTitle(highlightMenuText(R.string.st_contacts_menu_only_t)); MenuItem searchItem = menu.findItem(R.id.searchMenu); com.actionbarsherlock.widget.SearchView searchView = (com.actionbarsherlock.widget.SearchView) searchItem.getActionView(); // searchView.setQueryHint(getStringSafe(R.string.st_contacts_filter)); searchView.setQueryHint(""); ((ImageView) searchView.findViewById(R.id.abs__search_button)).setImageResource(R.drawable.st_bar_ic_search); searchView.setOnSuggestionListener(new com.actionbarsherlock.widget.SearchView.OnSuggestionListener() { @Override public boolean onSuggestionSelect(int position) { return false; } @Override public boolean onSuggestionClick(int position) { return false; } }); searchView.setOnQueryTextListener(new com.actionbarsherlock.widget.SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String newText) { doFilter(newText); return true; } }); searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { doFilter(null); ((TelegramActivity) getActivity()).fixBackButton(); return true; } }); if (application.getUserSettings().showOnlyTelegramContacts()) { menu.findItem(R.id.allContacts).setVisible(true); menu.findItem(R.id.onlyTContacts).setVisible(false); } else { menu.findItem(R.id.allContacts).setVisible(false); menu.findItem(R.id.onlyTContacts).setVisible(true); } ((TelegramActivity) getActivity()).fixBackButton(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.onlyTContacts) { application.getUserSettings().setShowOnlyTelegramContacts(true); getSherlockActivity().invalidateOptionsMenu(); reloadData(); return true; } else if (item.getItemId() == R.id.allContacts) { application.getUserSettings().setShowOnlyTelegramContacts(false); getSherlockActivity().invalidateOptionsMenu(); reloadData(); return true; } else if (item.getItemId() == R.id.systemContacts) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setType(ContactsContract.Contacts.CONTENT_TYPE); startPickerActivity(intent); } else if (item.getItemId() == R.id.addContact) { Intent intent = new Intent(Intent.ACTION_INSERT); intent.setType(ContactsContract.Contacts.CONTENT_TYPE); startPickerActivity(intent); } return super.onOptionsItemSelected(item); } @Override protected boolean showOnlyTelegramContacts() { return application.getUserSettings().showOnlyTelegramContacts(); } @Override protected int getLayout() { return R.layout.contacts_list; } @Override protected void onCreateView(View res, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { share = wrap(inflater).inflate(R.layout.contacts_header_share, null); getListView().addHeaderView(share); } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (i == 0) { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, getStringSafe(R.string.st_invite_short)); startPickerActivity(shareIntent, null, "Share by..."); } else { // TODO: Correct fix final ContactWireframe contact = (ContactWireframe) adapterView.getItemAtPosition(i); // final Contact[] contacts = application.getEngine().getUsersEngine().getContactsForLocalId(contact.getContactId()); if (contact.getRelatedUsers().length == 1) { getRootController().openUser(contact.getRelatedUsers()[0].getUid()); } else if (contact.getRelatedUsers().length > 0) { CharSequence[] names = new CharSequence[contact.getRelatedUsers().length]; for (int j = 0; j < names.length; j++) { names[j] = application.getEngine().getUser(contact.getRelatedUsers()[j].getUid()).getDisplayName(); } AlertDialog dialog = new AlertDialog.Builder(getActivity()) .setItems(names, secure(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { getRootController().openUser(contact.getRelatedUsers()[i].getUid()); } })).create(); dialog.setCanceledOnTouchOutside(true); dialog.show(); } else { AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.st_contacts_not_registered_title) .setMessage(getStringSafe(R.string.st_contacts_not_registered_message).replace("{0}", contact.getDisplayName())) .setPositiveButton(R.string.st_yes, secure(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { try { Cursor pCur = application.getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contact.getContactId() + ""}, null); if (pCur.moveToFirst()) { String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(getActivity()); Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + Uri.encode(phoneNo))); intent.putExtra("sms_body", getStringSafe(R.string.st_invite_short)); if (defaultSmsPackageName != null) // Can be null in case that there is no default, then the user would be able to choose any app that supports this intent. { intent.setPackage(defaultSmsPackageName); } startActivity(intent); } else { Intent sendSms = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + phoneNo)); sendSms.putExtra("address", phoneNo); sendSms.putExtra("sms_body", getStringSafe(R.string.st_invite_short)); sendSms.setType("vnd.android-dir/mms-sms"); startPickerActivity(sendSms); } } else { Context context1 = getActivity(); if (context1 != null) { Toast.makeText(context1, R.string.st_error_unable_sms, Toast.LENGTH_SHORT).show(); } } } catch (Exception e) { Context context1 = getActivity(); if (context1 != null) { Toast.makeText(context1, R.string.st_error_unable_sms, Toast.LENGTH_SHORT).show(); } } } })).setNegativeButton(R.string.st_no, null).create(); dialog.setCanceledOnTouchOutside(true); dialog.show(); } } } @Override public boolean onItemLongClick(final AdapterView<?> adapterView, View view, final int i, long l) { if (i == 0) { return false; } final ContactWireframe contact = (ContactWireframe) adapterView.getItemAtPosition(i); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(contact.getDisplayName()); if (contact.getRelatedUsers().length > 0) { builder.setItems(new CharSequence[]{ getStringSafe(R.string.st_contacts_action_view), getStringSafe(R.string.st_contacts_action_share), getStringSafe(R.string.st_contacts_action_delete), getStringSafe(R.string.st_contacts_action_block), getStringSafe(R.string.st_contacts_action_block_and_delete) }, secure(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { viewInBookContact(contact); } else if (i == 1) { shareContact(contact); } else if (i == 2) { deleteContact(contact); } else if (i == 3) { blockContact(contact); } else if (i == 4) { blockDeleteContact(contact); } } })); } else { builder.setItems(new CharSequence[]{ getStringSafe(R.string.st_contacts_action_view), getStringSafe(R.string.st_contacts_action_delete), }, secure(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { viewInBookContact(contact); } else if (i == 1) { deleteContact(contact); } } })); } AlertDialog contextMenu = builder.create(); contextMenu.setCanceledOnTouchOutside(true); contextMenu.show(); return true; } private void viewInBookContact(final ContactWireframe contact) { openUri(Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, contact.getContactId() + "")); } private void shareContact(final ContactWireframe contact) { getRootController().shareContact(contact.getRelatedUsers()[0].getUid()); } private void deleteContact(final ContactWireframe contact) { AlertDialog alertDialog = new AlertDialog.Builder(getActivity()) .setMessage(getStringSafe(R.string.st_contacts_delete).replace("{0}", contact.getDisplayName())) .setPositiveButton(R.string.st_yes, secure(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int b) { runUiTask(new AsyncAction() { @Override public void execute() throws AsyncException { if (contact.getRelatedUsers().length > 0) { TLVector<TLAbsInputUser> inputUsers = new TLVector<TLAbsInputUser>(); for (User c : contact.getRelatedUsers()) { inputUsers.add(new TLInputUserContact(c.getUid())); } rpc(new TLRequestContactsDeleteContacts(inputUsers)); for (User u : contact.getRelatedUsers()) { application.getEngine().getUsersEngine().deleteContact(u.getUid()); application.getSyncKernel().getContactsSync().removeContactLinks(u.getUid()); } } if (contact.getContactId() > 0) { Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, contact.getLookupKey()); application.getContentResolver().delete(uri, null, null); application.getSyncKernel().getContactsSync().removeContact(contact.getContactId()); } application.getSyncKernel().getContactsSync().invalidateContactsSync(); application.getDataSourceKernel().getContactsSource().onBookUpdated(); } @Override public void afterExecute() { reloadData(); } }); } })).setNegativeButton(R.string.st_no, null).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.show(); } private void blockContact(final ContactWireframe contact) { AlertDialog alertDialog = new AlertDialog.Builder(getActivity()) .setMessage(getStringSafe(R.string.st_contacts_block).replace("{0}", contact.getDisplayName())) .setPositiveButton(R.string.st_yes, secure(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { runUiTask(new AsyncAction() { @Override public void execute() throws AsyncException { rpc(new TLRequestContactsBlock(new TLInputUserContact(contact.getRelatedUsers()[0].getUid()))); } }); } })).setNegativeButton(R.string.st_no, null).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.show(); } private void blockDeleteContact(final ContactWireframe contact) { AlertDialog alertDialog = new AlertDialog.Builder(getActivity()) .setMessage(getStringSafe(R.string.st_contacts_block_delete).replace("{0}", contact.getDisplayName())) .setPositiveButton(R.string.st_yes, secure(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { runUiTask(new AsyncAction() { @Override public void execute() throws AsyncException { // Clean history TLAffectedHistory tlAffectedHistory = rpc(new TLRequestMessagesDeleteHistory(new TLInputPeerContact(contact.getRelatedUsers()[0].getUid()), 0)); application.getUpdateProcessor().onMessage(new TLLocalAffectedHistory(tlAffectedHistory)); while (tlAffectedHistory.getOffset() > 0) { tlAffectedHistory = rpc(new TLRequestMessagesDeleteHistory(new TLInputPeerContact(contact.getRelatedUsers()[0].getUid()), tlAffectedHistory.getOffset())); application.getUpdateProcessor().onMessage(new TLLocalAffectedHistory(tlAffectedHistory)); } application.getEngine().deleteHistory(PeerType.PEER_USER, contact.getRelatedUsers()[0].getUid()); // Block user rpc(new TLRequestContactsBlock(new TLInputUserContact(contact.getRelatedUsers()[0].getUid()))); // Deleting from contacts TLVector<TLAbsInputUser> inputUsers = new TLVector<TLAbsInputUser>(); for (User u : contact.getRelatedUsers()) { inputUsers.add(new TLInputUserContact(u.getUid())); } rpc(new TLRequestContactsDeleteContacts(inputUsers)); for (User u : contact.getRelatedUsers()) { application.getEngine().getUsersEngine().deleteContact(u.getUid()); application.getSyncKernel().getContactsSync().removeContactLinks(u.getUid()); } // Deleting local contact if (contact.getContactId() > 0) { Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, contact.getLookupKey()); application.getContentResolver().delete(uri, null, null); application.getSyncKernel().getContactsSync().removeContact(contact.getContactId()); } application.getSyncKernel().getContactsSync().invalidateContactsSync(); application.getDataSourceKernel().getContactsSource().onBookUpdated(); } @Override public void afterExecute() { reloadData(); } }); } })).setNegativeButton(R.string.st_no, null).create(); alertDialog.setCanceledOnTouchOutside(true); alertDialog.show(); } }
49.917226
200
0.560077
56e2832c43e1ce7a638aebf7fe2beffd013899f2
2,284
package br.ufc.mdcc.mpos.persistence; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.util.Log; import br.ufc.mdcc.mpos.R; import br.ufscar.mcc.model.MethodProfile; public class MethodDao extends Dao { private String TABLE_NAME; private String L_ID = "methodid"; private String L_METHODNAME = "methodname"; private String L_CLASSNAME = "classname"; private String L_METHODHASH = "methodhash"; private final String clsname = MethodDao.class.getName(); public MethodDao(Context con) { super(con); TABLE_NAME = con.getString(R.string.name_table_methoddata); } public void insertMethodProfile(MethodProfile profile) { openDatabase(); ContentValues cv = new ContentValues(); cv.put(L_METHODNAME, profile.getMethodName()); cv.put(L_CLASSNAME, profile.getClassName()); cv.put(L_METHODHASH, profile.hashCode()); try { database.insert(TABLE_NAME, null, cv); } catch (SQLException ex) { Log.e(clsname, ex.getMessage()); } closeDatabase(); } public MethodProfile getMethodProfle(String methodName, String className) { String sql = "SELECT METHODID, METHODNAME, CLASSNAME FROM " + TABLE_NAME + " WHERE METHODNAME LIKE '%" + methodName + "%' AND CLASSNAME LIKE '%" + className + "%'"; return getResult(sql); } private MethodProfile getResult(String sql) { openDatabase(); Cursor cursor = database.rawQuery(sql, null); Log.i(clsname, "Consulta '" + sql + "' trouxe " + cursor.getCount() + " resultados"); MethodProfile profile = new MethodProfile(); // obtem todos os indices das colunas da tabela int idx_logid = cursor.getColumnIndex(L_ID); int idx_methodname = cursor.getColumnIndex(L_METHODNAME); int idx_classname = cursor.getColumnIndex(L_CLASSNAME); if (cursor != null && cursor.moveToFirst()) { profile.setMethodId(cursor.getInt(idx_logid)); profile.setMethodName(cursor.getString(idx_methodname)); profile.setClassName(cursor.getString(idx_classname)); Log.i(clsname, "Achado metodo "+profile.getMethodName()); } cursor.close(); closeDatabase(); return profile; } public void clean() { openDatabase(); database.delete(TABLE_NAME, null, null); closeDatabase(); } }
27.853659
95
0.731611
cecdc3c9207314fee95ccfd20fc0e31ee6af7e39
1,315
package com.groupdocs.conversion.examples.quick_start; import com.groupdocs.conversion.licensing.License; import com.groupdocs.conversion.examples.Constants; import java.io.File; /** * This example demonstrates how to set license from file. * * * The SetLicense method attempts to set a license from several locations relative to the executable and GroupDocs.Conversion.dll. * You can also use the additional overload to load a license from a stream, this is useful for instance when the * License is stored as an embedded resource. */ public class SetLicenseFromFile { public static void run() { File file = new File(Constants.LicensePath); if (file.exists()) { License license = new License(); license.setLicense(Constants.LicensePath); System.out.println("License set successfully."); } else { System.out.print("\nWe do not ship any license with this example. " + "\nVisit the GroupDocs site to obtain either a temporary or permanent license. " + "\nLearn more about licensing at https://purchase.groupdocs.com/faqs/licensing. " + "\nLear how to request temporary license at https://purchase.groupdocs.com/temporary-license."); } } }
38.676471
129
0.672243
14a1adfc8eab299ef11253fdeefc02598f4b10a2
8,973
package net.es.nsi.dds.server; import com.google.common.base.Optional; import com.google.common.base.Strings; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import javax.net.ssl.SSLContext; import net.es.nsi.dds.authorization.SecurityFilter; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.http.server.NetworkListener; import org.glassfish.grizzly.http.server.StaticHttpHandler; import org.glassfish.grizzly.ssl.SSLEngineConfigurator; import org.glassfish.jersey.logging.LoggingFeature; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.moxy.xml.MoxyXmlFeature; import org.glassfish.jersey.server.ResourceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author hacksaw */ public class RestServer { private final Logger log = LoggerFactory.getLogger(getClass()); private Optional<HttpServer> server = Optional.absent(); private Optional<SSLContext> sslContext = Optional.absent(); private Optional<String> address = Optional.absent(); private Optional<String> port = Optional.absent(); private Optional<String> packages = Optional.absent(); private Optional<String> staticPath = Optional.absent(); private Optional<String> relativePath = Optional.absent(); private boolean secure = false; private int fileCacheMaxAge = 3600; private final List<Class<?>> interfaces = new ArrayList<>(); public RestServer(String address, String port, SSLContext sslContext) { log.debug("RestServer: creating secure HTTPS server."); this.address = Optional.fromNullable(Strings.emptyToNull(address)); if (!this.address.isPresent()) { throw new IllegalArgumentException("RestServer: Must provide address"); } this.port = Optional.fromNullable(Strings.emptyToNull(port)); if (!this.port.isPresent()) { throw new IllegalArgumentException("RestServer: Must provide port"); } this.sslContext = Optional.fromNullable(sslContext); if (!this.sslContext.isPresent()) { throw new IllegalArgumentException("RestServer: Must provide SslConfigurator"); } secure = true; } public RestServer(String address, String port) { log.debug("RestServer: creating unsecure HTTP server."); this.address = Optional.fromNullable(Strings.emptyToNull(address)); if (!this.address.isPresent()) { throw new IllegalArgumentException("RestServer: Must provide address"); } this.port = Optional.fromNullable(Strings.emptyToNull(port)); if (!this.port.isPresent()) { throw new IllegalArgumentException("RestServer: Must provide port"); } secure = false; } private ResourceConfig getResourceConfig() { ResourceConfig rs = new ResourceConfig(); if (packages.isPresent()) { log.debug("RestServer: adding packages " + packages.get()); rs.packages(packages.get()); } for (Class<?> intf : this.getInterfaces()) { log.debug("RestServer: adding interface " + intf.getCanonicalName()); rs.register(intf); } return rs.registerClasses(SecurityFilter.class) .register(new MoxyXmlFeature()) .register(new LoggingFeature(java.util.logging.Logger.getLogger(RestServer.class.getName()), Level.ALL, LoggingFeature.Verbosity.PAYLOAD_ANY, 10000)); } private URI getServerURI() { if (secure) { return URI.create("https://" + address.get() + ":" + port.get()); } return URI.create("http://" + address.get() + ":" + port.get()); } public boolean start() throws IOException { if (!server.isPresent()) { if (secure) { log.debug("RestServer: Creating secure server."); server = Optional.of(GrizzlyHttpServerFactory.createHttpServer( getServerURI(), getResourceConfig(), true, new SSLEngineConfigurator(sslContext.get()) .setNeedClientAuth(true).setClientMode(false))); } else { log.debug("RestServer: Creating server."); server = Optional.of(GrizzlyHttpServerFactory.createHttpServer( getServerURI(), getResourceConfig())); } NetworkListener listener = server.get().getListener("grizzly"); server.get().getServerConfiguration().setMaxBufferedPostSize(server.get().getServerConfiguration().getMaxBufferedPostSize()*10); if (staticPath.isPresent()) { StaticHttpHandler staticHttpHandler = new StaticHttpHandler(staticPath.get()); server.get().getServerConfiguration().addHttpHandler(staticHttpHandler, relativePath.get()); if (listener != null) { listener.getFileCache().setSecondsMaxAge(fileCacheMaxAge); } } } if (!server.get().isStarted()) { try { log.debug("RestServer: starting server."); server.get().start(); } catch (IOException ex) { log.error("Failed to start HTTP Server", ex); throw ex; } } return true; } public boolean isStarted() { if (server.isPresent()) { return server.get().isStarted(); } return false; } public void stop() { if (server.isPresent() && server.get().isStarted()) { log.debug("RestServer: Stopping server."); server.get().shutdownNow(); } } /** * @return the secure */ public boolean isSecure() { return secure; } /** * @param secure the secure to set * @return */ public RestServer setSecure(boolean secure) { this.secure = secure; return this; } /** * @return the sslContext */ public SSLContext getSslContext() { return sslContext.orNull(); } /** * @param sslContext the sslContext to set * @return */ public RestServer setSslContext(SSLContext sslContext) { this.sslContext = Optional.fromNullable(sslContext); return this; } /** * @return the address */ public String getAddress() { return address.get(); } /** * @param address the address to set * @return */ public RestServer setAddress(String address) throws IllegalArgumentException { this.address = Optional.fromNullable(Strings.emptyToNull(address)); if (!this.address.isPresent()) { throw new IllegalArgumentException("RestServer: Must provide address"); } return this; } /** * @return the port */ public String getPort() { return port.get(); } /** * @param port the port to set * @return */ public RestServer setPort(String port) throws IllegalArgumentException { this.port = Optional.fromNullable(Strings.emptyToNull(port)); if (!this.port.isPresent()) { throw new IllegalArgumentException("RestServer: Must provide port"); } return this; } /** * @return the packages */ public String getPackages() { return packages.orNull(); } /** * @param packages the packages to set * @return */ public RestServer setPackages(String packages) { this.packages = Optional.fromNullable(Strings.emptyToNull(packages)); if (!this.packages.isPresent()) { throw new IllegalArgumentException("RestServer: Must provide packages"); } return this; } public List<Class<?>> getInterfaces() { return Collections.unmodifiableList(interfaces); } public RestServer addInterface(Class<?> intf) { interfaces.add(intf); return this; } public void clearInterfaces() { interfaces.clear(); } public HttpServer getServer() { return server.orNull(); } public RestServer setFileCacheMaxAge(int fileCacheMaxAge) { this.fileCacheMaxAge = fileCacheMaxAge; return this; } public RestServer setStaticPath(String path) { staticPath = Optional.fromNullable(Strings.emptyToNull(path)); return this; } public String getStaticPath() { return staticPath.orNull(); } public RestServer setRelativePath(String path) { relativePath = Optional.fromNullable(Strings.emptyToNull(path)); return this; } public String getRelativePath() { return relativePath.orNull(); } }
30.835052
140
0.619748
8b9460692aba8b0dca3d23adfdb1dd8b6c5c2e3a
455
/** * */ package com.bluelightning.tools.transpiler.nodes; import org.antlr.v4.runtime.ParserRuleContext; /** * @author NOOK * */ public class TranslationOperatorNode extends TranslationNode { String operator; public TranslationOperatorNode(ParserRuleContext ctx, TranslationNode parent, String operator) { super(ctx, parent, "<OPERATOR>" + operator); this.operator = operator; } public String getOperator() { return operator; } }
17.5
97
0.734066
0ba06a5646e335bec88345eeff5c3c80824224c9
2,789
/* * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.lang.invoke; import static java.lang.invoke.LambdaForm.BasicType.*; import static java.lang.invoke.MethodHandleStatics.*; /** * A method handle whose behavior is determined only by its LambdaForm. * @author jrose */ final class SimpleMethodHandle extends BoundMethodHandle { private SimpleMethodHandle(MethodType type, LambdaForm form) { super(type, form); } /*non-public*/ static BoundMethodHandle make(MethodType type, LambdaForm form) { return new SimpleMethodHandle(type, form); } /*non-public*/ static final SpeciesData SPECIES_DATA = SpeciesData.EMPTY; /*non-public*/ public SpeciesData speciesData() { return SPECIES_DATA; } @Override /*non-public*/ BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) { return make(mt, lf); } @Override String internalProperties() { return "\n& Class="+getClass().getSimpleName(); } @Override /*non-public*/ public int fieldCount() { return 0; } @Override /*non-public*/ final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) { return BoundMethodHandle.bindSingle(mt, lf, narg); // Use known fast path. } @Override /*non-public*/ final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) { try { return (BoundMethodHandle) SPECIES_DATA.extendWith(I_TYPE).constructor().invokeBasic(mt, lf, narg); } catch (Throwable ex) { throw uncaughtException(ex); } } @Override /*non-public*/ final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) { try { return (BoundMethodHandle) SPECIES_DATA.extendWith(J_TYPE).constructor().invokeBasic(mt, lf, narg); } catch (Throwable ex) { throw uncaughtException(ex); } } @Override /*non-public*/ final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) { try { return (BoundMethodHandle) SPECIES_DATA.extendWith(F_TYPE).constructor().invokeBasic(mt, lf, narg); } catch (Throwable ex) { throw uncaughtException(ex); } } @Override /*non-public*/ final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) { try { return (BoundMethodHandle) SPECIES_DATA.extendWith(D_TYPE).constructor().invokeBasic(mt, lf, narg); } catch (Throwable ex) { throw uncaughtException(ex); } } }
27.343137
111
0.645034
67e9c462c50ff0e3c3e8b22d50b05a763fe806eb
22,739
package top.yokey.shopaisdk.bean; import com.google.gson.annotations.SerializedName; import java.io.Serializable; @SuppressWarnings("ALL") public class MemberBean implements Serializable { @SerializedName("user_name") private String userName = ""; @SerializedName("avatar") private String avatar = ""; @SerializedName("level") private String level = ""; @SerializedName("level_name") private String levelName = ""; @SerializedName("favorites_store") private String favoritesStore = ""; @SerializedName("favorites_goods") private String favoritesGoods = ""; @SerializedName("order_nopay_count") private String orderNopayCount = ""; @SerializedName("order_noreceipt_count") private String orderNoreceiptCount = ""; @SerializedName("order_notakes_count") private String orderNotakesCount = ""; @SerializedName("order_noeval_count") private String orderNoevalCount = ""; @SerializedName("return") private String returnX = ""; @SerializedName("is_fxuser") private String isFxuser = ""; @SerializedName("member_info_all") private MemberInfoAllBean memberInfoAll = null; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getLevelName() { return levelName; } public void setLevelName(String levelName) { this.levelName = levelName; } public String getFavoritesStore() { return favoritesStore; } public void setFavoritesStore(String favoritesStore) { this.favoritesStore = favoritesStore; } public String getFavoritesGoods() { return favoritesGoods; } public void setFavoritesGoods(String favoritesGoods) { this.favoritesGoods = favoritesGoods; } public String getOrderNopayCount() { return orderNopayCount; } public void setOrderNopayCount(String orderNopayCount) { this.orderNopayCount = orderNopayCount; } public String getOrderNoreceiptCount() { return orderNoreceiptCount; } public void setOrderNoreceiptCount(String orderNoreceiptCount) { this.orderNoreceiptCount = orderNoreceiptCount; } public String getOrderNotakesCount() { return orderNotakesCount; } public void setOrderNotakesCount(String orderNotakesCount) { this.orderNotakesCount = orderNotakesCount; } public String getOrderNoevalCount() { return orderNoevalCount; } public void setOrderNoevalCount(String orderNoevalCount) { this.orderNoevalCount = orderNoevalCount; } public String getReturnX() { return returnX; } public void setReturnX(String returnX) { this.returnX = returnX; } public String getIsFxuser() { return isFxuser; } public void setIsFxuser(String isFxuser) { this.isFxuser = isFxuser; } public MemberInfoAllBean getMemberInfoAll() { return memberInfoAll; } public void setMemberInfoAll(MemberInfoAllBean memberInfoAll) { this.memberInfoAll = memberInfoAll; } public static class MemberInfoAllBean { @SerializedName("member_id") private String memberId = ""; @SerializedName("member_name") private String memberName = ""; @SerializedName("member_truename") private String memberTruename = ""; @SerializedName("member_avatar") private String memberAvatar = ""; @SerializedName("member_sex") private String memberSex = ""; @SerializedName("member_birthday") private String memberBirthday = ""; @SerializedName("member_passwd") private String memberPasswd = ""; @SerializedName("member_paypwd") private String memberPaypwd = ""; @SerializedName("member_email") private String memberEmail = ""; @SerializedName("member_email_bind") private String memberEmailBind = ""; @SerializedName("member_mobile") private String memberMobile = ""; @SerializedName("member_mobile_bind") private String memberMobileBind = ""; @SerializedName("member_qq") private String memberQq = ""; @SerializedName("member_ww") private String memberWw = ""; @SerializedName("member_login_num") private String memberLoginNum = ""; @SerializedName("member_time") private String memberTime = ""; @SerializedName("member_login_time") private String memberLoginTime = ""; @SerializedName("member_old_login_time") private String memberOldLoginTime = ""; @SerializedName("member_login_ip") private String memberLoginIp = ""; @SerializedName("member_old_login_ip") private String memberOldLoginIp = ""; @SerializedName("member_qqopenid") private String memberQqopenid = ""; @SerializedName("member_qqinfo") private String memberQqinfo = ""; @SerializedName("member_sinaopenid") private String memberSinaopenid = ""; @SerializedName("member_sinainfo") private String memberSinainfo = ""; @SerializedName("weixin_unionid") private String weixinUnionid = ""; @SerializedName("weixin_info") private String weixinInfo = ""; @SerializedName("member_points") private String memberPoints = ""; @SerializedName("available_predeposit") private String availablePredeposit = ""; @SerializedName("freeze_predeposit") private String freezePredeposit = ""; @SerializedName("available_rc_balance") private String availableRcBalance = ""; @SerializedName("freeze_rc_balance") private String freezeRcBalance = ""; @SerializedName("inform_allow") private String informAllow = ""; @SerializedName("is_buy") private String isBuy = ""; @SerializedName("is_allowtalk") private String isAllowtalk = ""; @SerializedName("member_state") private String memberState = ""; @SerializedName("member_snsvisitnum") private String memberSnsvisitnum = ""; @SerializedName("member_areaid") private String memberAreaid = ""; @SerializedName("member_cityid") private String memberCityid = ""; @SerializedName("member_provinceid") private String memberProvinceid = ""; @SerializedName("member_areainfo") private String memberAreainfo = ""; @SerializedName("member_privacy") private String memberPrivacy = ""; @SerializedName("member_exppoints") private String memberExppoints = ""; @SerializedName("invite_one") private String inviteOne = ""; @SerializedName("invite_two") private String inviteTwo = ""; @SerializedName("invite_three") private String inviteThree = ""; @SerializedName("inviter_id") private String inviterId = ""; @SerializedName("trad_amount") private String tradAmount = ""; @SerializedName("auth_message") private String authMessage = ""; @SerializedName("fx_state") private String fxState = ""; @SerializedName("bill_user_name") private String billUserName = ""; @SerializedName("bill_type_code") private String billTypeCode = ""; @SerializedName("bill_type_number") private String billTypeNumber = ""; @SerializedName("bill_bank_name") private String billBankName = ""; @SerializedName("freeze_trad") private String freezeTrad = ""; @SerializedName("fx_code") private String fxCode = ""; @SerializedName("fx_time") private String fxTime = ""; @SerializedName("fx_handle_time") private String fxHandleTime = ""; @SerializedName("fx_show") private String fxShow = ""; @SerializedName("quit_time") private String quitTime = ""; @SerializedName("fx_apply_times") private String fxApplyTimes = ""; @SerializedName("fx_quit_times") private String fxQuitTimes = ""; @SerializedName("member_reg_ip") private String memberRegIp = ""; @SerializedName("registration_id") private String registrationId = ""; @SerializedName("client_type") private String clientType = ""; @SerializedName("openid") private String openid = ""; @SerializedName("token") private String token = ""; @SerializedName("level_name") private String levelName = ""; @SerializedName("store_id") private String storeId = ""; public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getMemberTruename() { return memberTruename; } public void setMemberTruename(String memberTruename) { this.memberTruename = memberTruename; } public String getMemberAvatar() { return memberAvatar; } public void setMemberAvatar(String memberAvatar) { this.memberAvatar = memberAvatar; } public String getMemberSex() { return memberSex; } public void setMemberSex(String memberSex) { this.memberSex = memberSex; } public String getMemberBirthday() { return memberBirthday; } public void setMemberBirthday(String memberBirthday) { this.memberBirthday = memberBirthday; } public String getMemberPasswd() { return memberPasswd; } public void setMemberPasswd(String memberPasswd) { this.memberPasswd = memberPasswd; } public String getMemberPaypwd() { return memberPaypwd; } public void setMemberPaypwd(String memberPaypwd) { this.memberPaypwd = memberPaypwd; } public String getMemberEmail() { return memberEmail; } public void setMemberEmail(String memberEmail) { this.memberEmail = memberEmail; } public String getMemberEmailBind() { return memberEmailBind; } public void setMemberEmailBind(String memberEmailBind) { this.memberEmailBind = memberEmailBind; } public String getMemberMobile() { return memberMobile; } public void setMemberMobile(String memberMobile) { this.memberMobile = memberMobile; } public String getMemberMobileBind() { return memberMobileBind; } public void setMemberMobileBind(String memberMobileBind) { this.memberMobileBind = memberMobileBind; } public String getMemberQq() { return memberQq; } public void setMemberQq(String memberQq) { this.memberQq = memberQq; } public String getMemberWw() { return memberWw; } public void setMemberWw(String memberWw) { this.memberWw = memberWw; } public String getMemberLoginNum() { return memberLoginNum; } public void setMemberLoginNum(String memberLoginNum) { this.memberLoginNum = memberLoginNum; } public String getMemberTime() { return memberTime; } public void setMemberTime(String memberTime) { this.memberTime = memberTime; } public String getMemberLoginTime() { return memberLoginTime; } public void setMemberLoginTime(String memberLoginTime) { this.memberLoginTime = memberLoginTime; } public String getMemberOldLoginTime() { return memberOldLoginTime; } public void setMemberOldLoginTime(String memberOldLoginTime) { this.memberOldLoginTime = memberOldLoginTime; } public String getMemberLoginIp() { return memberLoginIp; } public void setMemberLoginIp(String memberLoginIp) { this.memberLoginIp = memberLoginIp; } public String getMemberOldLoginIp() { return memberOldLoginIp; } public void setMemberOldLoginIp(String memberOldLoginIp) { this.memberOldLoginIp = memberOldLoginIp; } public String getMemberQqopenid() { return memberQqopenid; } public void setMemberQqopenid(String memberQqopenid) { this.memberQqopenid = memberQqopenid; } public String getMemberQqinfo() { return memberQqinfo; } public void setMemberQqinfo(String memberQqinfo) { this.memberQqinfo = memberQqinfo; } public String getMemberSinaopenid() { return memberSinaopenid; } public void setMemberSinaopenid(String memberSinaopenid) { this.memberSinaopenid = memberSinaopenid; } public String getMemberSinainfo() { return memberSinainfo; } public void setMemberSinainfo(String memberSinainfo) { this.memberSinainfo = memberSinainfo; } public String getWeixinUnionid() { return weixinUnionid; } public void setWeixinUnionid(String weixinUnionid) { this.weixinUnionid = weixinUnionid; } public String getWeixinInfo() { return weixinInfo; } public void setWeixinInfo(String weixinInfo) { this.weixinInfo = weixinInfo; } public String getMemberPoints() { return memberPoints; } public void setMemberPoints(String memberPoints) { this.memberPoints = memberPoints; } public String getAvailablePredeposit() { return availablePredeposit; } public void setAvailablePredeposit(String availablePredeposit) { this.availablePredeposit = availablePredeposit; } public String getFreezePredeposit() { return freezePredeposit; } public void setFreezePredeposit(String freezePredeposit) { this.freezePredeposit = freezePredeposit; } public String getAvailableRcBalance() { return availableRcBalance; } public void setAvailableRcBalance(String availableRcBalance) { this.availableRcBalance = availableRcBalance; } public String getFreezeRcBalance() { return freezeRcBalance; } public void setFreezeRcBalance(String freezeRcBalance) { this.freezeRcBalance = freezeRcBalance; } public String getInformAllow() { return informAllow; } public void setInformAllow(String informAllow) { this.informAllow = informAllow; } public String getIsBuy() { return isBuy; } public void setIsBuy(String isBuy) { this.isBuy = isBuy; } public String getIsAllowtalk() { return isAllowtalk; } public void setIsAllowtalk(String isAllowtalk) { this.isAllowtalk = isAllowtalk; } public String getMemberState() { return memberState; } public void setMemberState(String memberState) { this.memberState = memberState; } public String getMemberSnsvisitnum() { return memberSnsvisitnum; } public void setMemberSnsvisitnum(String memberSnsvisitnum) { this.memberSnsvisitnum = memberSnsvisitnum; } public String getMemberAreaid() { return memberAreaid; } public void setMemberAreaid(String memberAreaid) { this.memberAreaid = memberAreaid; } public String getMemberCityid() { return memberCityid; } public void setMemberCityid(String memberCityid) { this.memberCityid = memberCityid; } public String getMemberProvinceid() { return memberProvinceid; } public void setMemberProvinceid(String memberProvinceid) { this.memberProvinceid = memberProvinceid; } public String getMemberAreainfo() { return memberAreainfo; } public void setMemberAreainfo(String memberAreainfo) { this.memberAreainfo = memberAreainfo; } public String getMemberPrivacy() { return memberPrivacy; } public void setMemberPrivacy(String memberPrivacy) { this.memberPrivacy = memberPrivacy; } public String getMemberExppoints() { return memberExppoints; } public void setMemberExppoints(String memberExppoints) { this.memberExppoints = memberExppoints; } public String getInviteOne() { return inviteOne; } public void setInviteOne(String inviteOne) { this.inviteOne = inviteOne; } public String getInviteTwo() { return inviteTwo; } public void setInviteTwo(String inviteTwo) { this.inviteTwo = inviteTwo; } public String getInviteThree() { return inviteThree; } public void setInviteThree(String inviteThree) { this.inviteThree = inviteThree; } public String getInviterId() { return inviterId; } public void setInviterId(String inviterId) { this.inviterId = inviterId; } public String getTradAmount() { return tradAmount; } public void setTradAmount(String tradAmount) { this.tradAmount = tradAmount; } public String getAuthMessage() { return authMessage; } public void setAuthMessage(String authMessage) { this.authMessage = authMessage; } public String getFxState() { return fxState; } public void setFxState(String fxState) { this.fxState = fxState; } public String getBillUserName() { return billUserName; } public void setBillUserName(String billUserName) { this.billUserName = billUserName; } public String getBillTypeCode() { return billTypeCode; } public void setBillTypeCode(String billTypeCode) { this.billTypeCode = billTypeCode; } public String getBillTypeNumber() { return billTypeNumber; } public void setBillTypeNumber(String billTypeNumber) { this.billTypeNumber = billTypeNumber; } public String getBillBankName() { return billBankName; } public void setBillBankName(String billBankName) { this.billBankName = billBankName; } public String getFreezeTrad() { return freezeTrad; } public void setFreezeTrad(String freezeTrad) { this.freezeTrad = freezeTrad; } public String getFxCode() { return fxCode; } public void setFxCode(String fxCode) { this.fxCode = fxCode; } public String getFxTime() { return fxTime; } public void setFxTime(String fxTime) { this.fxTime = fxTime; } public String getFxHandleTime() { return fxHandleTime; } public void setFxHandleTime(String fxHandleTime) { this.fxHandleTime = fxHandleTime; } public String getFxShow() { return fxShow; } public void setFxShow(String fxShow) { this.fxShow = fxShow; } public String getQuitTime() { return quitTime; } public void setQuitTime(String quitTime) { this.quitTime = quitTime; } public String getFxApplyTimes() { return fxApplyTimes; } public void setFxApplyTimes(String fxApplyTimes) { this.fxApplyTimes = fxApplyTimes; } public String getFxQuitTimes() { return fxQuitTimes; } public void setFxQuitTimes(String fxQuitTimes) { this.fxQuitTimes = fxQuitTimes; } public String getMemberRegIp() { return memberRegIp; } public void setMemberRegIp(String memberRegIp) { this.memberRegIp = memberRegIp; } public String getRegistrationId() { return registrationId; } public void setRegistrationId(String registrationId) { this.registrationId = registrationId; } public String getClientType() { return clientType; } public void setClientType(String clientType) { this.clientType = clientType; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getLevelName() { return levelName; } public void setLevelName(String levelName) { this.levelName = levelName; } public String getStoreId() { return storeId; } public void setStoreId(String storeId) { this.storeId = storeId; } } }
27.495768
72
0.599103
1e8546ba3d4f738b73aa801263b006299c2af3bb
2,680
//quick sort program in java. class Sort { void merge(int arr[], int left, int middle, int right) { int low = middle - left + 1; //size of the left subarray int high = right - middle; //size of the right subarray int L[] = new int[low]; //create the left and right subarray int R[] = new int[high]; int i = 0, j = 0; for (i = 0; i < low; i++) //copy elements into left subarray { L[i] = arr[left + i]; } for (j = 0; j < high; j++) //copy elements into right subarray { R[j] = arr[middle + 1 + j]; } int k = left; //get starting index for sort i = 0; //reset loop variables before performing merge j = 0; while (i < low && j < high) //merge the left and right subarrays { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < low) //merge the remaining elements from the left subarray { arr[k] = L[i]; i++; k++; } while (j < high) //merge the remaining elements from right subarray { arr[k] = R[j]; j++; k++; } } void mergeSort(int arr[], int left, int right) //helper function that creates the sub cases for sorting { int middle; if (left < right) { //sort only if the left index is lesser than the right index (meaning that sorting is done) middle = (left + right) / 2; mergeSort(arr, left, middle); //left subarray mergeSort(arr, middle + 1, right); //right subarray merge(arr, left, middle, right); //merge the two subarrays } } void display(int arr[]) //display the array { for (int i=0; i<arr.length; ++i) { System.out.print(arr[i]+" "); } } public static void main(String args[]) { int arr[] = { 9, 3, 1, 5, 13, 12 }; Sort ob = new Sort(); ob.mergeSort(arr, 0, arr.length - 1); ob.display(arr); } }
30.454545
147
0.387687
a16521bdc8a10f50ad36536bc7f176566aad9b13
29,321
package me.songbx.service; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import me.songbx.impl.AnnotationReadImpl; import me.songbx.model.MapSingleRecord; import me.songbx.model.Strand; import me.songbx.model.CDS.Cds; import me.songbx.model.CDS.CdsLiftSequence; import me.songbx.model.Transcript.Transcript; import me.songbx.model.Transcript.TranscriptLiftStartEndSequenceAasequenceIndel; import me.songbx.util.StandardGeneticCode; import me.songbx.util.exception.codingNotFound; import me.songbx.util.exception.codingNotThree; /** * the sranscriptLiftStartEndSequenceAasequenceIndels in every collectors are * validated. The validation include length%3=0, start with start code, end with * end code, no middle stop code, And the splice site are AG, GT or same with * COL * * @author song * @version 1.0, 2014-07-09 */ public class AnnotationReadIncludeOrfLostService { private StandardGeneticCode standardGeneticCode = new StandardGeneticCode(); private AnnotationReadImpl annotationReadImpl; private ChromoSomeReadService targetChromeSomeRead; private ChromoSomeReadService referenceChromeSomeRead; private MapFileService mapFile; private HashMap<String, ArrayList<TranscriptLiftStartEndSequenceAasequenceIndel>> transcriptArrayList = new HashMap<String, ArrayList<TranscriptLiftStartEndSequenceAasequenceIndel>>(); private HashMap<String, TranscriptLiftStartEndSequenceAasequenceIndel> transcriptHashMap = new HashMap<String, TranscriptLiftStartEndSequenceAasequenceIndel>(); public AnnotationReadIncludeOrfLostService(){ } public AnnotationReadIncludeOrfLostService( ChromoSomeReadService targetChromeSomeRead, ChromoSomeReadService referenceChromeSomeRead, MapFileService mapFile) { this.targetChromeSomeRead = targetChromeSomeRead; this.referenceChromeSomeRead = referenceChromeSomeRead; this.mapFile = mapFile; } public synchronized void builtAnnotationReadImpl(String fileLocation) { annotationReadImpl = new AnnotationReadImpl(fileLocation); } public synchronized void updateInformation(boolean wantmRnaSequence, boolean wantFullCNDnaSequence, boolean wantCdsList, boolean wantSnpMapfilerecords, boolean wantIndelMapfilerecords, boolean wantIndelMapfilerecordsSeq/*, int minIntron*/) { ArrayList<TranscriptLiftStartEndSequenceAasequenceIndel> temptranscriptArrayList = new ArrayList<TranscriptLiftStartEndSequenceAasequenceIndel>(); HashMap<String, HashSet<Transcript>> sstranscriptHashSet = annotationReadImpl .getTranscriptHashSet(); Iterator<String> chrNamesIt = sstranscriptHashSet.keySet().iterator(); while (chrNamesIt.hasNext()) { String key = chrNamesIt.next(); for (Transcript transcript : sstranscriptHashSet.get(key)) { TranscriptLiftStartEndSequenceAasequenceIndel transcriptLiftStartEndSequenceAasequenceIndel = new TranscriptLiftStartEndSequenceAasequenceIndel( transcript); System.out.println(transcript.getName()); for (Cds cds : transcript.getCdsHashSet()) { CdsLiftSequence cdsLiftSequence = new CdsLiftSequence(cds); cdsLiftSequence = this.updateCdsLiftSequence( cdsLiftSequence, key); transcriptLiftStartEndSequenceAasequenceIndel .getCdsLiftSequenceArrayList().add(cdsLiftSequence); } temptranscriptArrayList .add(transcriptLiftStartEndSequenceAasequenceIndel); } } for (TranscriptLiftStartEndSequenceAasequenceIndel transcriptLiftStartEndSequenceAasequenceIndel : temptranscriptArrayList) { transcriptLiftStartEndSequenceAasequenceIndel = updateTranscriptLiftStartEndSequenceAasequenceIndel( transcriptLiftStartEndSequenceAasequenceIndel, wantmRnaSequence, wantFullCNDnaSequence, wantCdsList, wantSnpMapfilerecords, wantIndelMapfilerecords, wantIndelMapfilerecordsSeq); String name = transcriptLiftStartEndSequenceAasequenceIndel .getChromeSomeName(); String metaInformation = ""; boolean orfLOst = true; //System.out.println(transcriptLiftStartEndSequenceAasequenceIndel.getName()); boolean ifSelectTaur10 = ifSpliceSitesOk( transcriptLiftStartEndSequenceAasequenceIndel, name); if (ifSelectTaur10) { metaInformation += "_spliceSitesConserved"; String cdsSequenceString = transcriptLiftStartEndSequenceAasequenceIndel .getSequence(); //if( ifIntronEnoughLarge(transcriptLiftStartEndSequenceAasequenceIndel, minIntron) ){ // metaInformation = "_intronsLargeEnough"; if (cdsSequenceString.length() < 3) { metaInformation += "_exonLengthLessThan3"; } else { metaInformation += "_exonLengthMoreThan3"; if (ifLengthCouldbeDivedBYThree(cdsSequenceString)) { metaInformation += "_exonLengthIsMultipleOf3"; if (ifNewStopCOde(cdsSequenceString)) { metaInformation += "_premutareStopCodon"; } else { metaInformation += "_noPrematureStopCodon"; if (ifEndWithStopCode(cdsSequenceString)) { metaInformation += "_endWithStopCodon"; if (ifStartWithStartCode(cdsSequenceString)) { metaInformation += "_startWithStartCodon_ConservedFunction"; orfLOst = false; } else { metaInformation += "_notWithStartCodon"; } } else { metaInformation += "_notEndWithStopCodon"; } } } else { metaInformation += "_exonLengthIsNotMultipleOf3"; } } // }else { // metaInformation += "_exonLengthIsNotMultipleOf3"; // } } else { metaInformation = "_intronsNotLargeEnough"; } metaInformation += "_col" + transcriptLiftStartEndSequenceAasequenceIndel.getStart() + "-" + transcriptLiftStartEndSequenceAasequenceIndel.getEnd(); metaInformation += "_local" + transcriptLiftStartEndSequenceAasequenceIndel .getLiftStart() + "-" + transcriptLiftStartEndSequenceAasequenceIndel .getLiftEnd(); metaInformation += "_" + transcriptLiftStartEndSequenceAasequenceIndel.getStrand(); transcriptLiftStartEndSequenceAasequenceIndel.setOrfLost(orfLOst); transcriptLiftStartEndSequenceAasequenceIndel .setMetaInformation(metaInformation); metaInformation = null; if (!transcriptArrayList.containsKey(name)) { transcriptArrayList .put(name, new ArrayList<TranscriptLiftStartEndSequenceAasequenceIndel>()); } transcriptArrayList.get(name).add( transcriptLiftStartEndSequenceAasequenceIndel); transcriptHashMap.put( transcriptLiftStartEndSequenceAasequenceIndel.getName(), transcriptLiftStartEndSequenceAasequenceIndel); if(!wantmRnaSequence){ transcriptLiftStartEndSequenceAasequenceIndel.setSequence(null); } if(!wantCdsList){ transcriptLiftStartEndSequenceAasequenceIndel.setCdsLiftSequenceArrayList(null); } } temptranscriptArrayList = null; } private synchronized CdsLiftSequence updateCdsLiftSequence( CdsLiftSequence cdsLiftSequence, String chName) { cdsLiftSequence.setLiftEnd(mapFile.getChangedFromBasement(chName, cdsLiftSequence.getEnd())); cdsLiftSequence.setLiftStart(mapFile.getChangedFromBasement(chName, cdsLiftSequence.getStart())); //System.out.println("chName: " + chName + " cdsLiftSequence.getLiftStart(): " + cdsLiftSequence.getLiftStart() + " cdsLiftSequence.getLiftEnd(): " + cdsLiftSequence.getLiftEnd()); //System.out.println("cdsLiftSequence.getTranscript().getStrand(): " + cdsLiftSequence.getTranscript().getStrand() ); //System.out.println("ChrLength: " + targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()); cdsLiftSequence.setSequence(targetChromeSomeRead.getSubSequence(chName, cdsLiftSequence.getLiftStart(), cdsLiftSequence.getLiftEnd(), cdsLiftSequence.getTranscript().getStrand())); return cdsLiftSequence; } private synchronized TranscriptLiftStartEndSequenceAasequenceIndel updateTranscriptLiftStartEndSequenceAasequenceIndel( TranscriptLiftStartEndSequenceAasequenceIndel transcriptLiftStartEndSequenceAasequenceIndel, boolean wantmRnaSequence, boolean wantFullCNDnaSequence, boolean wantCdsList, boolean wantSnpMapfilerecords, boolean wantIndelMapfilerecords, boolean wantIndelMapfilerecordsSeq) { String chName = transcriptLiftStartEndSequenceAasequenceIndel .getChromeSomeName(); int start = 0; int end = 0; int liftStart = 0; int liftEnd = 0; int i = 0; ArrayList<CdsLiftSequence> cdsLiftSequenceArrayList = new ArrayList<CdsLiftSequence>(); // transfer // hashset // to // arraylist for (CdsLiftSequence cdsLiftSequence : transcriptLiftStartEndSequenceAasequenceIndel .getCdsLiftSequenceArrayList()) { cdsLiftSequenceArrayList.add(cdsLiftSequence); if (0 == i) { start = cdsLiftSequence.getStart(); end = cdsLiftSequence.getEnd(); liftStart = cdsLiftSequence.getLiftStart(); liftEnd = cdsLiftSequence.getLiftEnd(); } else { if (start > cdsLiftSequence.getStart()) { start = cdsLiftSequence.getStart(); liftStart = cdsLiftSequence.getLiftStart(); }// end if if (end < cdsLiftSequence.getEnd()) { end = cdsLiftSequence.getEnd(); liftEnd = cdsLiftSequence.getLiftEnd(); }// end if }// end else i++; }// end for transcriptLiftStartEndSequenceAasequenceIndel.setStart(start); transcriptLiftStartEndSequenceAasequenceIndel.setEnd(end); transcriptLiftStartEndSequenceAasequenceIndel.setLiftStart(liftStart); transcriptLiftStartEndSequenceAasequenceIndel.setLiftEnd(liftEnd); String fullSequence = targetChromeSomeRead.getSubSequence(chName, liftStart, liftEnd, transcriptLiftStartEndSequenceAasequenceIndel.getStrand()); Collections.sort(cdsLiftSequenceArrayList); StringBuffer sequenceStringBuffer = new StringBuffer(); for (CdsLiftSequence c : cdsLiftSequenceArrayList) { sequenceStringBuffer.append(c.getSequence()); if (mapFile.getIndelRecords().containsKey(chName)) { ArrayList<MapSingleRecord> records = mapFile.getAllRecords() .get(chName); for (MapSingleRecord mapSingleRecord : records) { if (c.getStart() <= mapSingleRecord.getBasement() - 1 && mapSingleRecord.getBasement() < c.getEnd()) { if (mapSingleRecord.getChanged() != 0) { if (wantIndelMapfilerecords) { if (wantIndelMapfilerecordsSeq) { transcriptLiftStartEndSequenceAasequenceIndel .getMapSingleRecords().add( mapSingleRecord); } else { MapSingleRecord newMapSingleRecord = new MapSingleRecord( mapSingleRecord.getBasement(), mapSingleRecord.getChanged()); transcriptLiftStartEndSequenceAasequenceIndel .getMapSingleRecords().add( newMapSingleRecord); mapSingleRecord=null; } }else{ mapSingleRecord=null; } transcriptLiftStartEndSequenceAasequenceIndel .setIndeled(true); } else if (wantSnpMapfilerecords) { transcriptLiftStartEndSequenceAasequenceIndel .getMapSingleRecords().add(mapSingleRecord); }else{ mapSingleRecord=null; }// end if } }// end for }// end if }// end for // Collections.sort(transcriptLiftStartEndSequenceAasequenceIndel.getMapSingleRecords()); String sequence = sequenceStringBuffer.toString(); sequenceStringBuffer = new StringBuffer(); if (!ifLengthCouldbeDivedBYThree(sequence)) { Pattern p = Pattern.compile("^\\wATG"); Matcher m = p.matcher(sequence); if (m.find()) { sequence = sequence.substring(1, sequence.length()); fullSequence = fullSequence.substring(1, fullSequence.length()); cdsLiftSequenceArrayList.get(0).setSequence( cdsLiftSequenceArrayList .get(0) .getSequence() .substring( 1, cdsLiftSequenceArrayList.get(0) .getSequence().length())); if (transcriptLiftStartEndSequenceAasequenceIndel.getStrand() == Strand.POSITIVE) { transcriptLiftStartEndSequenceAasequenceIndel .setLiftStart(liftStart + 1); cdsLiftSequenceArrayList.get(0).setLiftStart(liftStart + 1); } else { transcriptLiftStartEndSequenceAasequenceIndel .setLiftEnd(liftEnd - 1); cdsLiftSequenceArrayList.get(0).setLiftEnd(liftEnd - 1); } } } if (!ifLengthCouldbeDivedBYThree(sequence)) { Pattern p1 = Pattern.compile("TAA\\w$"); Matcher m1 = p1.matcher(sequence); Pattern p2 = Pattern.compile("TAG\\w$"); Matcher m2 = p2.matcher(sequence); Pattern p3 = Pattern.compile("TGA\\w$"); Matcher m3 = p3.matcher(sequence); if (m1.find() || m2.find() || m3.find()) { sequence = sequence.substring(0, sequence.length() - 1); fullSequence = fullSequence.substring(0, fullSequence.length() - 1); cdsLiftSequenceArrayList.get( cdsLiftSequenceArrayList.size() - 1).setSequence( cdsLiftSequenceArrayList .get(cdsLiftSequenceArrayList.size() - 1) .getSequence() .substring( 0, cdsLiftSequenceArrayList .get(cdsLiftSequenceArrayList .size() - 1) .getSequence().length() - 1)); if (transcriptLiftStartEndSequenceAasequenceIndel.getStrand() == Strand.POSITIVE) { transcriptLiftStartEndSequenceAasequenceIndel .setLiftEnd(liftEnd - 1); cdsLiftSequenceArrayList.get( cdsLiftSequenceArrayList.size() - 1).setLiftEnd( liftEnd - 1); } else { transcriptLiftStartEndSequenceAasequenceIndel .setLiftStart(liftStart + 1); cdsLiftSequenceArrayList.get( cdsLiftSequenceArrayList.size() - 1).setLiftStart( liftStart + 1); } } } //get the intron sequence for sweep analysis: begin //StringBuffer intronSequenceSB = new StringBuffer(); /* int sweepExtendLength = 100; if(transcriptLiftStartEndSequenceAasequenceIndel.getStrand() == Strand.POSITIVE){ int start1=cdsLiftSequenceArrayList.get(0).getLiftStart()-sweepExtendLength; int end1=cdsLiftSequenceArrayList.get(0).getLiftStart()-1; if(start1<1){ start1 = 1; } if(end1 >= targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()){ end1 = targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()-1; } intronSequenceSB.append(targetChromeSomeRead.getSubSequence(chName, start1, end1, Strand.POSITIVE)); if(cdsLiftSequenceArrayList.size()>1){ for(int ij=0; ij < (cdsLiftSequenceArrayList.size()-1); ij++){ if(cdsLiftSequenceArrayList.get(ij).getLiftEnd()+1 < cdsLiftSequenceArrayList.get(ij+1).getLiftStart()-1){ intronSequenceSB.append(targetChromeSomeRead.getSubSequence(chName, cdsLiftSequenceArrayList.get(ij).getLiftEnd()+1, cdsLiftSequenceArrayList.get(ij+1).getLiftStart()-1, Strand.POSITIVE)); } } } int start2 = cdsLiftSequenceArrayList.get( cdsLiftSequenceArrayList.size()-1 ).getLiftEnd()+1; int end2 = cdsLiftSequenceArrayList.get( cdsLiftSequenceArrayList.size()-1 ).getLiftEnd()+sweepExtendLength; if(start2<1){ start2 = 1; } if(end2 >= targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()){ end2 = targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()-1; } intronSequenceSB.append(targetChromeSomeRead.getSubSequence(chName, start2, end2, Strand.POSITIVE)); }else{ int start1=cdsLiftSequenceArrayList.get(0).getLiftEnd()+1; int end1=cdsLiftSequenceArrayList.get(0).getLiftEnd()+sweepExtendLength; if(start1<1){ start1 = 1; } if(start1 >= targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()){ start1 = targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()-1; } if(end1 >= targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()){ end1 = targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()-1; } intronSequenceSB.append(targetChromeSomeRead.getSubSequence(chName, start1, end1, Strand.NEGTIVE)); if(cdsLiftSequenceArrayList.size()>1){ for(int ij=0; ij < (cdsLiftSequenceArrayList.size()-1); ij++){ if(cdsLiftSequenceArrayList.get(ij).getLiftStart()-1 > cdsLiftSequenceArrayList.get(ij+1).getLiftEnd()+1){ intronSequenceSB.append(targetChromeSomeRead.getSubSequence(chName, cdsLiftSequenceArrayList.get(ij+1).getLiftEnd()+1, cdsLiftSequenceArrayList.get(ij).getLiftStart()-1, Strand.NEGTIVE)); } } } int end2 = cdsLiftSequenceArrayList.get( cdsLiftSequenceArrayList.size()-1 ).getLiftStart()-1; int start2 = cdsLiftSequenceArrayList.get( cdsLiftSequenceArrayList.size()-1 ).getLiftStart()-sweepExtendLength; if(start2<1){ start2 = 1; } if(end2 >= targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()){ end2 = targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()-1; } intronSequenceSB.append(targetChromeSomeRead.getSubSequence(chName, start2, end2, Strand.NEGTIVE)); }*/ /* int sweepExtendLength = 554000; if(transcriptLiftStartEndSequenceAasequenceIndel.getStrand() == Strand.POSITIVE){ int start1=cdsLiftSequenceArrayList.get(0).getLiftStart()-sweepExtendLength; if(start1<1){ start1 = 1; } int end2 = cdsLiftSequenceArrayList.get( cdsLiftSequenceArrayList.size()-1 ).getLiftEnd()+sweepExtendLength; if(end2 >= targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()){ end2 = targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()-1; } intronSequenceSB.append(targetChromeSomeRead.getSubSequence(chName, start1, end2, Strand.POSITIVE)); }else{ int start2 = cdsLiftSequenceArrayList.get( cdsLiftSequenceArrayList.size()-1 ).getLiftStart()-sweepExtendLength; if(start2<1){ start2 = 1; } int end1=cdsLiftSequenceArrayList.get(0).getLiftEnd()+sweepExtendLength; if(end1 >= targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()){ end1 = targetChromeSomeRead.getChromoSomeById(chName).getSequence().length()-1; } intronSequenceSB.append(targetChromeSomeRead.getSubSequence(chName, start2, end1, Strand.NEGTIVE)); } transcriptLiftStartEndSequenceAasequenceIndel.setNeutralSelectionSequence(intronSequenceSB.toString()); * */ //get the intron sequence for sweep analysis: end if (wantCdsList) { transcriptLiftStartEndSequenceAasequenceIndel .setCdsLiftSequenceArrayList(cdsLiftSequenceArrayList); } else { //transcriptLiftStartEndSequenceAasequenceIndel // .setCdsLiftSequenceArrayList(null); transcriptLiftStartEndSequenceAasequenceIndel .setCdsLiftSequenceArrayList(cdsLiftSequenceArrayList); cdsLiftSequenceArrayList=null; } if (wantmRnaSequence) { transcriptLiftStartEndSequenceAasequenceIndel.setSequence(sequence); } else { transcriptLiftStartEndSequenceAasequenceIndel.setSequence(sequence); sequence = null; } if (wantFullCNDnaSequence) { transcriptLiftStartEndSequenceAasequenceIndel .setFullequence(fullSequence); } else { transcriptLiftStartEndSequenceAasequenceIndel.setFullequence(null); fullSequence=null; } return transcriptLiftStartEndSequenceAasequenceIndel; } public synchronized boolean ifLengthCouldbeDivedBYThree(String cdsSequence) { if (0 != cdsSequence.length() % 3) { return false; } return true; } public synchronized boolean ifNewStopCOde(String cdsSequence) { for (int jj = 0; jj < cdsSequence.length() - 3; jj += 3) { try { if ('*' == standardGeneticCode.getGeneticCode( cdsSequence.substring(jj, jj + 3), (0 == jj))) {// new // stop // code return true; } } catch (codingNotThree | codingNotFound e) { // e.printStackTrace(); } } return false; } public synchronized boolean ifEndWithStopCode(String cdsSequence) { try { if (('*' != standardGeneticCode.getGeneticCode( cdsSequence.substring(cdsSequence.length() - 3, cdsSequence.length()), false)) && 'X' != standardGeneticCode.getGeneticCode(cdsSequence .substring(cdsSequence.length() - 3, cdsSequence.length()), false)) { return false; // stop code disappeared } } catch (codingNotThree e) { // e.printStackTrace(); } catch (codingNotFound e) { // e.printStackTrace(); } return true; } public synchronized boolean ifStartWithStartCode(String cdsSequence) { try { if (('M' != standardGeneticCode.getGeneticCode( cdsSequence.substring(0, 3), true)) && 'X' != standardGeneticCode.getGeneticCode( cdsSequence.substring(0, 3), true)) { return false; // start code disappeared } } catch (codingNotThree e) { // e.printStackTrace(); } catch (codingNotFound e) { // e.printStackTrace(); } return true; } private synchronized boolean ifIntronEnoughLarge( TranscriptLiftStartEndSequenceAasequenceIndel t2, int minIntron ){ for (int iiii = 1; iiii < t2.getCdsLiftSequenceArrayList().size(); iiii++) { if (t2.getStrand() == Strand.POSITIVE) { int le = t2.getCdsLiftSequenceArrayList().get(iiii - 1).getEnd(); int ts = t2.getCdsLiftSequenceArrayList().get(iiii).getStart(); if( (ts - le - 1) < minIntron ){ return false; } }else{ int ts = t2.getCdsLiftSequenceArrayList().get(iiii - 1).getStart(); int le = t2.getCdsLiftSequenceArrayList().get(iiii).getEnd(); if( (le - ts - 1) < minIntron ){ return false; } } } return true; } private synchronized boolean ifSpliceSitesOk( TranscriptLiftStartEndSequenceAasequenceIndel t2, String chromeSomeName) { for (int iiii = 1; iiii < t2.getCdsLiftSequenceArrayList().size(); iiii++) { int le; int ts; String s1; String s2; int let; int tst; String s1t; String s2t; if (t2.getStrand() == Strand.POSITIVE) { le = t2.getCdsLiftSequenceArrayList().get(iiii - 1).getEnd(); ts = t2.getCdsLiftSequenceArrayList().get(iiii).getStart(); s1 = referenceChromeSomeRead.getSubSequence(chromeSomeName, le + 1, le + 2, t2.getStrand()); s2 = referenceChromeSomeRead.getSubSequence(chromeSomeName, ts - 2, ts - 1, t2.getStrand()); let = t2.getCdsLiftSequenceArrayList().get(iiii - 1) .getLiftEnd(); tst = t2.getCdsLiftSequenceArrayList().get(iiii).getLiftStart(); s1t = targetChromeSomeRead.getSubSequence(chromeSomeName, let + 1, let + 2, t2.getStrand()); s2t = targetChromeSomeRead.getSubSequence(chromeSomeName, tst - 2, tst - 1, t2.getStrand()); } else { le = t2.getCdsLiftSequenceArrayList().get(iiii - 1).getStart(); ts = t2.getCdsLiftSequenceArrayList().get(iiii).getEnd(); // System.out.println(""+chromeSomeName+"\t"+(le-2)+"\t"+(le-1)+"\t"+t2.getStrand()); s1 = referenceChromeSomeRead.getSubSequence(chromeSomeName, le - 2, le - 1, t2.getStrand()); s2 = referenceChromeSomeRead.getSubSequence(chromeSomeName, ts + 2, ts + 1, t2.getStrand()); let = t2.getCdsLiftSequenceArrayList().get(iiii - 1) .getLiftStart(); tst = t2.getCdsLiftSequenceArrayList().get(iiii).getLiftEnd(); s1t = targetChromeSomeRead.getSubSequence(chromeSomeName, let - 2, let - 1, t2.getStrand()); s2t = targetChromeSomeRead.getSubSequence(chromeSomeName, tst + 2, tst + 1, t2.getStrand()); } /*System.out.println("chromeSomeName: " + chromeSomeName + " ts: " + ts + " t2.getStrand(): " + t2.getStrand()); System.out.println(referenceChromeSomeRead.getChromoSomeById(chromeSomeName).getSequence()); System.out.println(s2); */ s2 = this.agIUPACcodesTranslation(s2); s1 = this.gtIUPACcodesTranslation(s1); s2t = this.agIUPACcodesTranslation(s2t); s1t = this.gtIUPACcodesTranslation(s1t); // System.err.println("at:s1:"+s1); // System.err.println("ag:s2:"+s2); // System.err.println("gt:s1t:"+s1t); // System.err.println("ag:s2t:"+s2t); ArrayList<String> donors = new ArrayList<String>(); ArrayList<String> acceptors = new ArrayList<String>(); donors.add("GT"); acceptors.add("AG"); donors.add("GC"); acceptors.add("AG"); donors.add("CT"); acceptors.add("AG"); donors.add("GG"); acceptors.add("AG"); donors.add("GA"); acceptors.add("AG"); donors.add("CA"); acceptors.add("AG"); donors.add("GT"); acceptors.add("CG"); donors.add("GT"); acceptors.add("GG"); donors.add("TG"); acceptors.add("AG"); donors.add("GT"); acceptors.add("TG"); donors.add("AT"); acceptors.add("AG"); donors.add("TC"); acceptors.add("AG"); donors.add("GT"); acceptors.add("AC"); donors.add("CC"); acceptors.add("AG"); donors.add("TT"); acceptors.add("AG"); donors.add("GT"); acceptors.add("AA"); donors.add("AA"); acceptors.add("AG"); donors.add("GT"); acceptors.add("AT"); donors.add("GT"); acceptors.add("GC"); donors.add("AC"); acceptors.add("AG"); donors.add("AG"); acceptors.add("AG"); donors.add("CT"); acceptors.add("AT"); donors.add("GT"); acceptors.add("CC"); donors.add("GA"); acceptors.add("CT"); donors.add("GT"); acceptors.add("CT"); donors.add("GT"); acceptors.add("GA"); donors.add("CC"); acceptors.add("GC"); donors.add("GG"); acceptors.add("GT"); donors.add("GT"); acceptors.add("GT"); donors.add("GT"); acceptors.add("TC"); donors.add("CT"); acceptors.add("TT"); donors.add("GT"); acceptors.add("TT"); for( int di = 0; di<donors.size(); ++di ){ if( donors.get(di).equals(s1t) && acceptors.get(di).equals(s2t) ){ return true; } } if ( (( "GT".equals(s1t) || "GC".equals(s1t) || "CT".equals(s1t) || "GG".equals(s1t)) && "AG".equals(s2t)) || ("GT".equals(s1t) && ("CG".equals(s2t) || "TG".equals(s2t))) ) { return true; } else { // System.err.println("222"); if (!s1t.equals(s1)) { return false; // System.err.println("333"); } if (!s2t.equals(s2)) { return false; // System.err.println("444"); } } } return true; } private synchronized String agIUPACcodesTranslation(String ag) { String agString = ag; if ( agString.length()==2 && ('A' == ag.charAt(0) || 'R' == ag.charAt(0) || 'W' == ag.charAt(0) || 'M' == ag.charAt(0) || 'D' == ag.charAt(0) || 'H' == ag.charAt(0) || 'V' == ag.charAt(0) || 'N' == ag .charAt(0)) && ('G' == ag.charAt(1) || 'K' == ag.charAt(1) || 'R' == ag.charAt(1) || 'S' == ag.charAt(1) || 'B' == ag.charAt(1) || 'D' == ag.charAt(1) || 'V' == ag.charAt(1) || 'N' == ag.charAt(1))) { agString = "AG"; } return agString; } private synchronized String gtIUPACcodesTranslation(String gt) { String gtString = gt; if ( gtString.length()==2 && ('G' == gtString.charAt(0) || 'K' == gtString.charAt(0) || 'R' == gtString.charAt(0) || 'S' == gtString.charAt(0) || 'B' == gtString.charAt(0) || 'D' == gtString.charAt(0) || 'V' == gtString.charAt(0) || 'N' == gtString.charAt(0)) && ('T' == gtString.charAt(1) || 'K' == gtString.charAt(1) || 'Y' == gtString.charAt(1) || 'W' == gtString.charAt(1) || 'U' == gtString.charAt(1) || 'B' == gtString.charAt(1) || 'D' == gtString.charAt(1) || 'H' == gtString.charAt(1) || 'N' == gtString .charAt(1))) { gtString = "GT"; } return gtString; } public synchronized StandardGeneticCode getStandardGeneticCode() { return standardGeneticCode; } public synchronized void setStandardGeneticCode( StandardGeneticCode standardGeneticCode) { this.standardGeneticCode = standardGeneticCode; } public synchronized AnnotationReadImpl getAnnotationReadImpl() { return annotationReadImpl; } public synchronized void setAnnotationReadImpl( AnnotationReadImpl annotationReadImpl) { this.annotationReadImpl = annotationReadImpl; } public synchronized ChromoSomeReadService getTargetChromeSomeRead() { return targetChromeSomeRead; } public synchronized void setTargetChromeSomeRead( ChromoSomeReadService targetChromeSomeRead) { this.targetChromeSomeRead = targetChromeSomeRead; } public synchronized ChromoSomeReadService getReferenceChromeSomeRead() { return referenceChromeSomeRead; } public synchronized void setReferenceChromeSomeRead( ChromoSomeReadService referenceChromeSomeRead) { this.referenceChromeSomeRead = referenceChromeSomeRead; } public synchronized MapFileService getMapFile() { return mapFile; } public synchronized void setMapFile(MapFileService mapFile) { this.mapFile = mapFile; } public synchronized HashMap<String, ArrayList<TranscriptLiftStartEndSequenceAasequenceIndel>> getTranscriptArrayList() { return transcriptArrayList; } public synchronized void setTranscriptArrayList( HashMap<String, ArrayList<TranscriptLiftStartEndSequenceAasequenceIndel>> transcriptArrayList) { this.transcriptArrayList = transcriptArrayList; } public synchronized HashMap<String, TranscriptLiftStartEndSequenceAasequenceIndel> getTranscriptHashMap() { return transcriptHashMap; } public synchronized void setTranscriptHashMap( HashMap<String, TranscriptLiftStartEndSequenceAasequenceIndel> transcriptHashMap) { this.transcriptHashMap = transcriptHashMap; } }
37.882429
185
0.71147
4913337f9986248e823bef4afba6deadc8328b19
1,788
package io.github.pleuvoir.requestresponse; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.AMQP.BasicProperties; import io.github.pleuvoir.kit.RabbitMQKit; public class Consumer { static String QUEUE = "replyto"; public static void main(String[] args) throws IOException, TimeoutException { Channel channel = RabbitMQKit.createConnection().createChannel(); channel.exchangeDeclare(Producer.EXCHANGE, BuiltinExchangeType.DIRECT); channel.queueDeclare(QUEUE, false, false, false, null); channel.queueBind(QUEUE, Producer.EXCHANGE, Producer.ROUTINGKEY); System.out.println("Consumer 等待接收消息 .."); DefaultConsumer consumer = new DefaultConsumer(channel){ @Override // properties 由生产者发送时所带的属性值 public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { String message = new String(body); System.out.println("接收到消息[routekey]" + envelope.getRoutingKey() + "=" + message); System.out.println("replyTo:" + properties.getReplyTo() + " correlationId:" + properties.getMessageId()); // 将消息重发回这个队列 固定写法 AMQP.BasicProperties replyProps = new AMQP.BasicProperties. Builder() .replyTo(properties.getReplyTo()) .correlationId(properties.getMessageId()) .build(); // 如果使用 RabbitMQ 内置的交换机 队列名 = 路由键 channel.basicPublish("", replyProps.getReplyTo(), replyProps, ("回复:" + message).getBytes()); } }; channel.basicConsume(QUEUE, true, consumer); } }
31.928571
109
0.732662
3fc43355b82e96b108d725d47d4e8cdafeb910ec
1,305
package cg; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; public class Demo2 { public static void main(String[] args) { // TODO Auto-generated method stub //generic collection // Set<String> col= new HashSet<String>(); // Set<String> col= new LinkedHashSet<String>();// ordered => maintains intertion order //No duplicates // Set<String> col= new TreeSet<String>(); // does not accept 'null' as an object // throws NullPointerException // sorted elements// unordered collection List<String> col= new ArrayList<String>(); col.add("Ram"); col.add("Sham"); col.add("Abdul"); // col.add(55);// new Integer(55);//autoboxing // col.add(null); col.add("Ganesh"); col.add("Ram"); System.out.println(col.size()); System.out.println(col); System.out.println("-------------------------------"); for(String s: col) { System.out.println(s); } System.out.println("-------------------------------"); Iterator<String> it = col.iterator(); while(it.hasNext()) { String ss=it.next(); System.out.println(ss); } } }
27.1875
116
0.586207
f8832d972489cac99dfdfd12d0dc36356a5ca9f3
2,515
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.analysis.tokenattributes; import java.util.Collections; import java.util.HashMap; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.TestUtil; public class TestSimpleAttributeImpl extends LuceneTestCase { // this checks using reflection API if the defaults are correct public void testAttributes() { TestUtil.assertAttributeReflection( new PositionIncrementAttributeImpl(), Collections.singletonMap( PositionIncrementAttribute.class.getName() + "#positionIncrement", 1)); TestUtil.assertAttributeReflection( new PositionLengthAttributeImpl(), Collections.singletonMap(PositionLengthAttribute.class.getName() + "#positionLength", 1)); TestUtil.assertAttributeReflection( new FlagsAttributeImpl(), Collections.singletonMap(FlagsAttribute.class.getName() + "#flags", 0)); TestUtil.assertAttributeReflection( new TypeAttributeImpl(), Collections.singletonMap( TypeAttribute.class.getName() + "#type", TypeAttribute.DEFAULT_TYPE)); TestUtil.assertAttributeReflection( new PayloadAttributeImpl(), Collections.singletonMap(PayloadAttribute.class.getName() + "#payload", null)); TestUtil.assertAttributeReflection( new KeywordAttributeImpl(), Collections.singletonMap(KeywordAttribute.class.getName() + "#keyword", false)); TestUtil.assertAttributeReflection( new OffsetAttributeImpl(), new HashMap<String, Object>() { { put(OffsetAttribute.class.getName() + "#startOffset", 0); put(OffsetAttribute.class.getName() + "#endOffset", 0); } }); } }
43.362069
98
0.722068
9e594a42ebc71c30d09d7dc633910535746c900c
18,229
/** * @company 杭州盘石 * @copyright Copyright (c) 2018 - 2019 */ package io.renren.api.rockmobi.payment.ph.util; import com.alibaba.fastjson.JSONObject; import io.renren.common.utils.DateUtils; import io.renren.common.utils.LoggerUtils; import io.renren.common.utils.RandomUtil; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.util.Date; import java.util.Map; import java.util.UUID; /** * @author 闫迎军(YanYingJun) * @version $Id: HttpUtil, v0.1 2019年02月12日 14:39闫迎军(YanYingJun) Exp $ */ public class HttpUtil { private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class); @Value("${ph.sm.server_id}") private static String smsServiceId; @Value("${ph.sm.sp_password}") private static String smsSpPassword; @Value("${ph.sm.partner_id}") private static String smspartnerId; /** * 拼接字符串 * @return */ public static String CombiningStrings(String url, Map<String,Object> params){ String apiUrl = url; StringBuffer param = new StringBuffer(); int i = 0; for (String key : params.keySet()) { if (i == 0) { param.append("?"); } else { param.append("&"); } param.append(key).append("=").append(params.get(key)); i++; } return apiUrl += param; } /** * 从请求头中获取手机号码 * @param request * @return */ public static String getBsnlMsisdn(HttpServletRequest request){ //south west String msisdn = request.getHeader("x-msisdn"); if (StringUtils.isEmpty(msisdn)) { msisdn=request.getHeader("msisdn"); } if (StringUtils.isEmpty(msisdn)) { msisdn=request.getHeader("x-Mobile"); } if (StringUtils.isEmpty(msisdn)) { msisdn=request.getHeader("header-x_msisdn"); } return msisdn; } /** * 获取request用户 IP * * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { if (request == null) { return "unknown"; } String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } /** * 利用HttpURLConnection对象,我们可以从网络中获取网页数据 * @param path * @return * @throws Exception */ public static InputStream getRemoteFileIs(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据. conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); //得到网络返回的输入流 return is; } public static String doGet(String url) { String strResult = null; try { HttpGet httpRequest = new HttpGet(url); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpResponse httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { strResult = EntityUtils.toString(httpResponse.getEntity()); } else if (httpResponse.getStatusLine().getStatusCode() == 400) { strResult = "error"; } else if (httpResponse.getStatusLine().getStatusCode() == 500) { strResult = "error"; } else { strResult = "error"; } if (httpResponse.getStatusLine().getStatusCode() != 200) { HttpEntity entiy = httpResponse.getEntity(); if (entiy != null) { LoggerUtils.info(LOGGER, "request url: {"+ url +"}, response: {"+ httpResponse.getStatusLine() +"}, {"+ EntityUtils.toString(entiy) +"}"); } else { LoggerUtils.info(LOGGER, "request url: {"+ url +"}, response: {"+ httpResponse.getStatusLine() +"}"); } } } catch (Exception e) { strResult = "error"; LoggerUtils.error(LOGGER, "http doGet error.", e); } return strResult; } /** * 发送POST请求 * @param url * @param requestData * @return */ public static String doPost(String url, String requestData){ CloseableHttpClient httpClient = null; try { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClient = httpClientBuilder.build(); HttpPost httppost = new HttpPost(url); HttpEntity re = new StringEntity(requestData, "UTF-8"); httppost.setHeader("Content-Type","application/soap+xml; charset=utf-8"); httppost.setEntity(re); //调用接口 HttpResponse response = httpClient.execute(httppost); //调用状态 if(response.getStatusLine().getStatusCode() == 200) { String xmlString = EntityUtils.toString(response.getEntity()); LoggerUtils.info(LOGGER, "HttpClient请求返回的结果:" + xmlString); return xmlString; } } catch (Exception e) { LoggerUtils.info(LOGGER, "HttpClient请求返回结果异常,异常信息:" + e.getMessage()); } finally { try { //关闭连接 httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 使用SOAP1.1发送消息 * * @param postUrl * @param soapXml * @param soapAction * @return */ public static String doPostSoap1_1(String postUrl, String soapXml, String soapAction) { int socketTimeout = 30000;// 请求超时时间 int connectTimeout = 30000;// 传输超时时间 String retStr = ""; // 创建HttpClientBuilder HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // HttpClient CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); HttpPost httpPost = new HttpPost(postUrl); // 设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(socketTimeout) .setConnectTimeout(connectTimeout).build(); httpPost.setConfig(requestConfig); try { httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8"); httpPost.setHeader("SOAPAction", soapAction); StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8")); httpPost.setEntity(data); CloseableHttpResponse response = closeableHttpClient .execute(httpPost); HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { // 打印响应内容 String result = EntityUtils.toString(httpEntity, "UTF-8"); Map map = XmlUtil.parse(result); retStr = JSONObject.toJSONString(map); LoggerUtils.info(LOGGER, "response string:" + result); LoggerUtils.info(LOGGER, "response xml:" + result); } // 释放资源 closeableHttpClient.close(); } catch (Exception e) { LoggerUtils.error(LOGGER, "exception in doPostSoap1_1,异常原因:" + e.getMessage()); } return retStr; } /** * 从输入流中读取数据 * * @param inStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray(); outStream.close(); inStream.close(); return data; } public static String doPostSms(String postUrl, String json) { String retStr = ""; String uuid = UUID.randomUUID().toString(); // 创建HttpClientBuilder HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // HttpClient CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); HttpPost httpPost = new HttpPost(postUrl); try { httpPost.setHeader("Authorization", "WSSE realm=CDP,profile=UsernameToken"); httpPost.setHeader("X-WSSE", "UsernameToken Username=00"+smspartnerId+",PasswordDigest="+smsSpPassword+",Nonce="+uuid+",Created="+ DateUtils.format(new Date(), DateUtils.DATE_TIME4_PATTERN)); httpPost.setHeader("X-RequestHeader", "request ServiceId=00"+smsServiceId+",ProductId"); //httpPost.setHeader("Content-length", ); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); StringEntity data = new StringEntity(json, Charset.forName("UTF-8")); httpPost.setEntity(data); CloseableHttpResponse response = closeableHttpClient .execute(httpPost); HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { // 打印响应内容 retStr = EntityUtils.toString(httpEntity, "UTF-8"); LoggerUtils.info(LOGGER, "response:" + retStr); } response.close(); // 释放资源 closeableHttpClient.close(); } catch (Exception e) { LoggerUtils.error(LOGGER, "exception in doPostSoap1_1", e); } return retStr; } public static String doPostSmsSub(String postUrl, String json, String spPassword, String smsServiceId, String productId, String type, String phoneNo) { return doPostSmsSub(postUrl, json, spPassword, smsServiceId, productId, type, phoneNo, null); } /** * 菲律宾短信订阅发送请求 * @param postUrl * @param json * @param spPassword * @param smsServiceId * @param productId * @param messageId * @return */ public static String doPostSmsSub(String postUrl, String json, String spPassword, String smsServiceId, String productId, String type, String phoneNo, String messageId) { String retStr = ""; String nonce = String.valueOf(RandomUtil.getUpperCode(30, RandomUtil.SecurityCodeLevel.Medium, true)); String created = DateUtils.format(new Date(), DateUtils.DATE_TIME4_PATTERN); String passwordDigst = null; try { String passwordSHA = nonce + created + spPassword; byte[] passwordDigstSHA = DigestUtils.sha1(passwordSHA.getBytes("utf-8")); passwordDigst = Base64.encodeBase64String(passwordDigstSHA); } catch (Exception e) { LoggerUtils.error(LOGGER, "passwordDigst BASE64加密异常,异常信息:" + e.getMessage()); } // 创建HttpClientBuilder HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // HttpClient CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); HttpPost httpPost = new HttpPost(postUrl); try { httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); //httpPost.setHeader("Content-length", String.valueOf(json.length())); //httpPost.setHeader("Host", "168.63.246.122:80"); httpPost.setHeader("Authorization", "WSSE realm=\"CDP\",profile=\"UsernameToken\""); httpPost.setHeader("X-WSSE", "UsernameToken Username=\"006409\",PasswordDigest=\""+passwordDigst+"\",Nonce=\""+nonce+"\",Created=\""+created+"\"" ); if (type.equals("inbound")) { httpPost.setHeader("X-RequestHeader", "request ServiceId=\"" + smsServiceId + "\"");//\"++ \""); } else { httpPost.setHeader("X-RequestHeader", "request ProductId=\"" + productId + "\",ServiceId=\"" + smsServiceId + "\",FA=\"" + "tel:" + phoneNo + "\"" + (StringUtils.isEmpty(messageId) ? "" : ",LinkId=\"" + messageId + "\"")); } StringEntity data = new StringEntity(json, Charset.forName("UTF-8")); httpPost.setEntity(data); CloseableHttpResponse response = closeableHttpClient .execute(httpPost); HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { // 打印响应内容 retStr = EntityUtils.toString(httpEntity, "UTF-8"); LoggerUtils.info(LOGGER, "response:" + retStr); } response.close(); // 释放资源 closeableHttpClient.close(); } catch (Exception e) { LoggerUtils.error(LOGGER, "exception in doPostSoap1_1", e); } return retStr; } public static String doDelete(String type, String uri, String smsServiceId, String productId,String smsSpPassword, String phoneNo) { String retStr = ""; String nonce = String.valueOf(RandomUtil.getUpperCode(30, RandomUtil.SecurityCodeLevel.Medium, true)); String created = DateUtils.format(new Date(), DateUtils.DATE_TIME4_PATTERN); String passwordDigst = null; try { String passwordSHA = nonce + created + smsSpPassword; byte[] passwordDigstSHA = DigestUtils.sha1(passwordSHA.getBytes("utf-8")); passwordDigst = Base64.encodeBase64String(passwordDigstSHA); } catch (Exception e) { LoggerUtils.error(LOGGER, "passwordDigst BASE64加密异常,异常信息:" + e.getMessage()); } CloseableHttpClient client = null; HttpDelete httpDelete = null; String result = null; try { // 创建HttpClientBuilder HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // HttpClient client = httpClientBuilder.build(); httpDelete = new HttpDelete(uri); httpDelete.setHeader("Content-Type", "application/json;charset=UTF-8"); httpDelete.setHeader("Authorization", "WSSE realm=\"CDP\",profile=\"UsernameToken\""); httpDelete.setHeader("X-WSSE", "UsernameToken Username=\"006409\",PasswordDigest=\""+passwordDigst+"\",Nonce=\""+nonce+"\",Created=\""+created+"\"" ); if(type.equals("inbound")){ httpDelete.setHeader("X-RequestHeader", "request ServiceId=\""+smsServiceId+"\"");//\"++ \""); }else{ httpDelete.setHeader("X-RequestHeader", "request ProductId=\""+ productId +"\",ServiceId=\""+smsServiceId+"\",FA=\""+"tel:"+phoneNo+"\""); } CloseableHttpResponse response = client.execute(httpDelete); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); if (200 == response.getStatusLine().getStatusCode()) { LoggerUtils.info(LOGGER, "远程调用成功.msg={" + result + "}"); } } catch (Exception e) { LOGGER.error("远程调用失败,errorMsg={}", e.getMessage()); } finally { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } /** * 描述:获取 post 请求的 byte[] 数组 * <pre> * 举例: * </pre> * @param request * @return * @throws IOException */ public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if(contentLength<0){ return null; } byte buffer[] = new byte[contentLength]; for (int i = 0; i < contentLength;) { int readlen = request.getInputStream().read(buffer, i, contentLength - i); if (readlen == -1) { break; } i += readlen; } return buffer; } /** * 描述:获取 post 请求内容 * <pre> * 举例: * </pre> * @param request * @return * @throws IOException */ public static String getRequestPostStr(HttpServletRequest request) throws IOException { byte buffer[] = getRequestPostBytes(request); String charEncoding = request.getCharacterEncoding(); if (charEncoding == null) { charEncoding = "UTF-8"; } return new String(buffer, charEncoding); } }
38.296218
203
0.588952
8d7ae94da65175c971c0b25be9c51a5b1dc8f1a5
1,374
package com.mans.sbugram.models.requests; import com.mans.sbugram.models.Post; import org.json.JSONObject; import java.util.Objects; public class SendPostRequest extends Request { public final String username; public final String password; public final Post post; public SendPostRequest(String username, String password, Post post) { this.username = username; this.password = password; this.post = post; } @Override public JSONObject toJSON() { JSONObject result = new JSONObject(); JSONObject data = new JSONObject(); data.put("username", username); data.put("password", password); data.put("post", post.toJSON()); result.put("request_type", this.getRequestType().name()); result.put("data", data); return result; } @Override public RequestType getRequestType() { return RequestType.SEND_POST; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SendPostRequest that = (SendPostRequest) o; return username.equals(that.username) && password.equals(that.password) && post.equals(that.post); } @Override public int hashCode() { return Objects.hash(username, password, post); } }
25.924528
106
0.637555
f4b67b6111574b3d2a35b9abb7ce410a8fb193f3
2,932
package net.fosterzor.openfire.crowd.auth; import com.atlassian.crowd.model.user.User; import com.atlassian.crowd.service.client.CrowdClient; import org.jivesoftware.openfire.auth.InternalUnauthenticatedException; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; /** * Created by IntelliJ IDEA. * User: bpfoster * Date: 1/6/12 * Time: 11:55 AM * To change this template use File | Settings | File Templates. */ @RunWith(PowerMockRunner.class) public class CrowdAuthProviderTest { private CrowdAuthProvider authProvider; private CrowdClient crowdClient; @Before public void setUp() throws Exception { crowdClient = mock(CrowdClient.class); authProvider = new CrowdAuthProvider(crowdClient); } @Test public void testProperties() { assertTrue(authProvider.isPlainSupported()); assertFalse(authProvider.isDigestSupported()); assertFalse(authProvider.supportsPasswordRetrieval()); } @Test(expected = InternalUnauthenticatedException.class) public void testDigestAuthenticate() throws Exception { authProvider.authenticate("abc", "def", "ghi"); } @Test(expected = UnsupportedOperationException.class) public void testGetPassword() throws Exception { authProvider.getPassword("anything"); } @Test(expected = UnsupportedOperationException.class) public void testSetPassword() throws Exception { authProvider.setPassword("anything", "anythingElse"); } @Test public void testPlaintextAuthentication() throws Exception { String password = "password"; String username = "username"; User user = mock(User.class); when(crowdClient.authenticateUser(username, password)).thenReturn(user); authProvider.authenticate(username, password); } @Test(expected = UnauthorizedException.class) public void testFailedAuthenticationWithNull() throws Exception { String password = "password"; String username = "username"; when(crowdClient.authenticateUser(username, password)).thenReturn(null); authProvider.authenticate(username, password); } @Test(expected = UnauthorizedException.class) public void testFailedAuthenticationWithException() throws Exception { String password = "password"; String username = "username"; when(crowdClient.authenticateUser(username, password)).thenThrow(new com.atlassian.crowd.exception.UserNotFoundException(username)); authProvider.authenticate(username, password); } }
34.494118
140
0.735334
b44cc68dace94504e00184e19e663ff65c4c76db
5,753
/* * 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 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package br.ufrn.imd.obd.enums; /** * Names of all available commands. */ public enum AvailableCommand { AIR_INTAKE_TEMP("Air Intake Temperature", "01 0F"), AMBIENT_AIR_TEMP("Ambient Air Temperature", "01 46"), ENGINE_COOLANT_TEMP("Engine Coolant Temperature", "01 05"), BAROMETRIC_PRESSURE("Barometric Pressure", "01 33"), FUEL_PRESSURE("Fuel Pressure", "01 0A"), INTAKE_MANIFOLD_PRESSURE("Intake Manifold Pressure", "01 0B"), ENGINE_LOAD("Engine Load", "01 04"), ENGINE_RUNTIME("Engine Runtime", "01 1F"), ENGINE_RPM("Engine RPM", "01 0C"), SPEED("Vehicle Speed", "01 0D"), MAF("Mass Air Flow", "01 10"), THROTTLE_POS("Throttle Position", "01 11"), TROUBLE_CODES("Trouble Codes", "03"), PENDING_TROUBLE_CODES("Pending Trouble Codes", "07"), PERMANENT_TROUBLE_CODES("Permanent Trouble Codes", "0A"), RESET_TROUBLE_CODES("Reset Trouble Codes", "04"), FUEL_LEVEL("Fuel Level", "01 2F"), ETHANOL_LEVEL("Ethanol Level", "01 52"), FUEL_TYPE("Fuel Type", "01 51"), FUEL_CONSUMPTION_RATE("Fuel Consumption Rate", "01 5E"), TIMING_ADVANCE("Timing Advance", "01 0E"), DTC_NUMBER("Diagnostic Trouble Codes", "01 01"), EQUIV_RATIO("Command Equivalence Ratio", "01 44"), DISTANCE_TRAVELED_AFTER_CODES_CLEARED("Distance since codes cleared", "01 31"), CONTROL_MODULE_VOLTAGE("Control Module Power Supply", "01 42"), FUEL_RAIL_PRESSURE("Fuel Rail Pressure", "01 23"), VIN("Vehicle Identification Number (VIN)", "09 02"), DISTANCE_TRAVELED_MIL_ON("Distance traveled with MIL on", "01 21"), TIME_TRAVELED_MIL_ON("Time run with MIL on", "01 4D"), TIME_SINCE_TC_CLEARED("Time since trouble codes cleared", "01 4E"), REL_THROTTLE_POS("Relative throttle position", "01 45"), PIDS_01_20("Available PIDs 01-20", "01 00"), PIDS_21_40("Available PIDs 21-40", "01 20"), PIDS_41_60("Available PIDs 41-60", "01 40"), ABS_LOAD("Absolute load", "01 43"), ENGINE_OIL_TEMP("Engine oil temperature", "01 5C"), AIR_FUEL_RATIO("Air/Fuel Ratio", "01 44"), WIDEBAND_AIR_FUEL_RATIO("Wideband Air/Fuel Ratio", "01 34"), DESCRIBE_PROTOCOL("Describe protocol", "AT DP"), DESCRIBE_PROTOCOL_NUMBER("Describe protocol number", "AT DPN"), IGNITION_MONITOR("Ignition monitor", "AT IGN"), SHORT_TERM_BANK_1("Short Term Fuel Trim Bank 1", "01 06"), LONG_TERM_BANK_1("Long Term Fuel Trim Bank 1", "01 07"), SHORT_TERM_BANK_2("Short Term Fuel Trim Bank 2", "01 08"), LONG_TERM_BANK_2("Long Term Fuel Trim Bank 2", "01 09"), ADAPTIVE_TIMING_OFF("Adaptive Timing Control Off", "AT AT 0"), ADAPTIVE_TIMING_AUTO_1("Adaptive Timing Control Auto 1", "AT AT 1"), ADAPTIVE_TIMING_AUTO_2("Adaptive Timing Control Auto 2", "AT AT 2"), PROTOCOL_CLOSE("Protocol Close", "AT PC"), ECHO_OFF("Echo Off", "AT E0"), HEADERS_OFF("Headers disabled", "AT H0"), LINE_FEED_OFF("Line Feed Off", "AT L0"), SPACES_OFF("Spaces Off", "AT S0"), RESET_OBD("Reset OBD", "AT Z"), WARM_START("WarmStart OBD", "AT WS"), SET_TIMEOUT("Set Timeout", "AT ST 0"), PROTOCOL_AUTO("Select Protocol - Auto", "AT SP 0"), PROTOCOL_SAE_J1850_PWM("Select Protocol - SAE J1850 PWM", "AT SP 1"), PROTOCOL_SAE_J1850_VPW("Select Protocol - SAE J1850 VPW", "AT SP 2"), PROTOCOL_ISO_9141_2("Select Protocol - ISO 9141-2", "AT SP 3"), PROTOCOL_ISO_14230_4_KWP("Select Protocol - ISO 14230-4 (KWP 5BAUD)", "AT SP 4"), PROTOCOL_ISO_14230_4_KWP_FAST("Select Protocol - ISO 14230-4 (KWP FAST)", "AT SP 5"), PROTOCOL_ISO_15765_4_CAN("Select Protocol - ISO 15765-4 (CAN 11/500)", "AT SP 6"), PROTOCOL_ISO_15765_4_CAN_B("Select Protocol - ISO 15765-4 (CAN 29/500)", "AT SP 7"), PROTOCOL_ISO_15765_4_CAN_C("Select Protocol - ISO 15765-4 (CAN 11/250)", "AT SP 8"), PROTOCOL_ISO_15765_4_CAN_D("Select Protocol - ISO 15765-4 (CAN 29/250)", "AT SP 9"), PROTOCOL_SAE_J1939_CAN("Select Protocol - SAE J1939 (CAN 29/250)", "AT SP A"), CUSTOM_COMMAND("Custom Command", ""); private final String value; private String command; /** * @param value Command description */ AvailableCommand(String value, String command) { this.value = value; this.command = command; } /** * <p>Getter for the field <code>value</code>.</p> * * @return a {@link String} object. */ public final String getValue() { return value; } /** * <p>Getter for the field <code>command</code>.</p> * * @return a {@link String} object. */ public final String getCommand() { return command; } @Override public String toString() { return this.value + " [" + this.command + "]"; } public static class CustomCommand { private CustomCommand() { } public static AvailableCommand getTimeout(int timeout) { SET_TIMEOUT.command = "AT ST " + Integer.toHexString(0xFF & timeout); return SET_TIMEOUT; } public static AvailableCommand rawCommand(String command) { CUSTOM_COMMAND.command = command; return CUSTOM_COMMAND; } } }
41.388489
89
0.663828
2a860dee1c3943a1d4a7ecd7765bfc552c45b7f1
730
package com.gradle.enterprise.api.client; public class FailedRequestException extends ApiClientException { private final int httpStatusCode; private final String responseBody; public FailedRequestException(String message, int httpStatusCode, String responseBody) { this(message, httpStatusCode, responseBody, null); } public FailedRequestException(String message, int httpStatusCode, String responseBody, Throwable cause) { super(message, cause); this.httpStatusCode = httpStatusCode; this.responseBody = responseBody; } public int httpStatusCode() { return httpStatusCode; } public String getResponseBody() { return responseBody; } }
27.037037
109
0.717808
f7a4a40b5fd592a16d2d69c8b81f19e2bf335a0c
5,437
package com.palyrobotics.frc2022.subsystems; import com.palyrobotics.frc2022.config.subsystem.ClimberConfig; import com.palyrobotics.frc2022.robot.Commands; import com.palyrobotics.frc2022.robot.HardwareAdapter; import com.palyrobotics.frc2022.robot.RobotState; import com.palyrobotics.frc2022.util.config.Configs; import com.palyrobotics.frc2022.util.control.ControllerOutput; import com.palyrobotics.frc2022.util.control.Spark; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMaxLowLevel; public class Climber extends SubsystemBase { /* * POSITION_CONTROL = telescoping arm goes to a position, specified in inches with commands.climberArmWantedPosition * LOCKED = telescoping arm applies a small output after reaching the desired position, to prevent it from moving * MANUAL = operator manually moves the telescoping arm * IDLE = telescoping arm output is 0 */ public enum ArmState { POSITION_CONTROL, LOCKED, MANUAL, IDLE, RE_ZERO } public enum SwingerState { POSITION_CONTROL, LOCKED, MANUAL, IDLE } private static final Climber sInstance = new Climber(); private HardwareAdapter.ClimberHardware hardware = HardwareAdapter.ClimberHardware.getInstance(); private ControllerOutput mTelescopeLeftArmOutput = new ControllerOutput(); private ControllerOutput mTelescopeRightArmOutput = new ControllerOutput(); private ControllerOutput mSwingerOutput = new ControllerOutput(); private static final ClimberConfig mConfig = Configs.get(ClimberConfig.class); private Climber() { } public static Climber getInstance() { return sInstance; } @Override public void update(Commands commands, RobotState state) { updateTelescopeArm(commands, state); updateSwingerArm(commands, state); } private void updateTelescopeArm(Commands commands, RobotState state) { switch (commands.climberArmWantedState) { case POSITION_CONTROL: mTelescopeLeftArmOutput.setTargetPositionProfiled(commands.climberArmWantedPosition, mConfig.armVelocityGains); mTelescopeRightArmOutput.setTargetPositionProfiled(commands.climberArmWantedPosition, mConfig.armVelocityGains); break; case LOCKED: break; case MANUAL: mTelescopeLeftArmOutput.setPercentOutput(commands.climberLeftArmWantedPercentOutput); mTelescopeRightArmOutput.setPercentOutput(commands.climberLeftArmWantedPercentOutput); break; case RE_ZERO: if (commands.canRezeroLeftArm) { mTelescopeLeftArmOutput.setPercentOutput(mConfig.rezeroOutput); } else { mTelescopeLeftArmOutput.setIdle(); } if (commands.canRezeroRightArm) { mTelescopeRightArmOutput.setPercentOutput(mConfig.rezeroOutput); } else { mTelescopeRightArmOutput.setIdle(); } break; case IDLE: mTelescopeLeftArmOutput.setIdle(); mTelescopeRightArmOutput.setIdle(); break; } } private void updateSwingerArm(Commands commands, RobotState state) { switch (commands.climberSwingerWantedState) { case POSITION_CONTROL: mSwingerOutput.setTargetPositionProfiled(commands.swingerArmWantedPosition, mConfig.swingerVelocityGains); break; case LOCKED: break; case MANUAL: mSwingerOutput.setPercentOutput(commands.climberSwingerWantedPercentOutput); break; case IDLE: mSwingerOutput.setIdle(); break; } } @Override public void writeHardware(RobotState state) { hardware.telescopeArmLeftSpark.setOutput(mTelescopeLeftArmOutput); hardware.telescopeArmRightSpark.setOutput(mTelescopeRightArmOutput); hardware.swingerArmMasterSpark.setOutput(mSwingerOutput); } @Override public void configureHardware() { for (Spark spark : hardware.sparks) { spark.restoreFactoryDefaults(); } hardware.telescopeArmLeftSpark.setInverted(false); hardware.telescopeArmRightSpark.setInverted(true); hardware.swingerArmMasterSpark.setInverted(false); hardware.swingerArmSlaveSpark.follow(hardware.swingerArmMasterSpark, false); hardware.telescopeArmLeftEncoder.setPositionConversionFactor(1.0); hardware.telescopeArmLeftEncoder.setVelocityConversionFactor(1.0); hardware.telescopeArmLeftEncoder.setPositionConversionFactor(1.0); hardware.telescopeArmRightEncoder.setVelocityConversionFactor(1.0); hardware.swingerArmMasterEncoder.setPositionConversionFactor(1.0); hardware.swingerArmMasterEncoder.setVelocityConversionFactor(1.0); hardware.swingerArmSlaveEncoder.setPositionConversionFactor(1.0); hardware.swingerArmSlaveEncoder.setVelocityConversionFactor(1.0); hardware.telescopeArmLeftSpark.setIdleMode(CANSparkMax.IdleMode.kBrake); hardware.telescopeArmRightSpark.setIdleMode(CANSparkMax.IdleMode.kBrake); hardware.swingerArmMasterSpark.setIdleMode(CANSparkMax.IdleMode.kBrake); hardware.swingerArmSlaveSpark.setIdleMode(CANSparkMax.IdleMode.kBrake); hardware.telescopeArmLeftSpark.getEncoder().setPosition(0.0); hardware.telescopeArmRightSpark.getEncoder().setPosition(0.0); hardware.swingerArmMasterEncoder.setPosition(0.0); hardware.swingerArmSlaveEncoder.setPosition(0.0); hardware.telescopeArmLeftSpark.setPeriodicFramePeriod(CANSparkMaxLowLevel.PeriodicFrame.kStatus1, 40); hardware.telescopeArmRightSpark.setPeriodicFramePeriod(CANSparkMaxLowLevel.PeriodicFrame.kStatus1, 40); hardware.swingerArmMasterSpark.setPeriodicFramePeriod(CANSparkMaxLowLevel.PeriodicFrame.kStatus1, 40); hardware.swingerArmSlaveSpark.setPeriodicFramePeriod(CANSparkMaxLowLevel.PeriodicFrame.kStatus1, 40); } }
38.560284
116
0.814052
0f5232246912cf6be66cb0cf6bdec2cdb84b55d5
1,440
package edu.sumdu.tss.elephant.helper.utils; import edu.sumdu.tss.elephant.helper.exception.BackupException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.junit.jupiter.api.Assertions.*; class CmdUtilTest { private final PrintStream standardOut = System.out; private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); @BeforeEach public void setUp() { System.setOut(new PrintStream(outputStreamCaptor)); } @AfterEach public void tearDown() { System.setOut(standardOut); } @Test void execTest() { String command = "clear"; CmdUtil.exec(command); assertEquals("Perform: clear", outputStreamCaptor.toString() .trim()); } @Test void execBackExTest(){ String command = "sudo"; assertThrows(BackupException.class, () -> { CmdUtil.exec(command); }); } @Test void execBackIoExTest(){ String command = "."; assertThrows(BackupException.class, () -> { CmdUtil.exec(command); }); } @Test void execBackInterExTest(){ String command = ";"; assertThrows(BackupException.class, () -> { CmdUtil.exec(command); }); } }
23.225806
89
0.630556
48ccc56f9f0fada1ffa26f4ee277c1e8fff371f3
19,222
package com.example.c.testwebapi; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import java.util.List; public class MainActivity extends ActionBarActivity { public static String[] types = new String[]{"any", "Public","Hotels","Restaurants","Sport","Education","Medical","Security","IT", "Other"}; public static ServerSDK _ServerCaller; Button myServices,newService,myFriends,favoriteServices,favoriteOffers ,requestedOffers, myRequestsIMade,myRequestsAsOwner; AlertWindow alert; TextView statuslabel; ListView main_servicetableLayout; List<Data.Friend> freinds; List<Data.Service> services; List<Data.Offer> offers; List<Data.Request> requests; int lasttype = 0; public void RestoreData(){ SharedPreferences settings = getSharedPreferences("X", 0); ServerSDK._User = new Data.User( settings.getString("at", "X"), settings.getString("username", ""), settings.getString("fname", ""), settings.getString("lname", ""), settings.getBoolean("type", true)); if (ServerSDK._User.accesstoken.equals("X")) ServerSDK._User = null; ServerSDK.serverAdrress = settings.getString("serverAddress", ServerSDK.serverAdrress); } @Override protected void onStop(){ super.onStop(); if(ServerSDK._User == null) { clearStoredData(); return; } SharedPreferences settings = getSharedPreferences("X", 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("at", ServerSDK._User.accesstoken); editor.putString("username", ServerSDK._User.username); editor.putString("fname", ServerSDK._User.fname); editor.putString("lname", ServerSDK._User.lname); editor.putBoolean("type", ServerSDK._User.typeisSP); editor.putString("serverAddress", ServerSDK.serverAdrress); editor.commit(); } public void clearStoredData(){ SharedPreferences settings = getSharedPreferences("X", 0); SharedPreferences.Editor editor = settings.edit(); editor.remove("at"); editor.commit(); } @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ServerCaller.context = getBaseContext(); statuslabel = (TextView)findViewById(R.id.statuslabel); if (_ServerCaller == null) _ServerCaller = new ServerSDK(this); RestoreData(); if (ServerSDK._User == null) startActivityForResult(new Intent(MainActivity.this, Login.class), 1); else print("welcome " + ServerSDK._User.username); if (alert == null) alert = new AlertWindow(this); main_servicetableLayout = (ListView) findViewById(R.id.main_servicetableLayout); newService = (Button) findViewById(R.id.newService); myServices = (Button) findViewById(R.id.myServices); myFriends = (Button) findViewById(R.id.myFriends); favoriteServices = (Button) findViewById(R.id.favoriteServices); favoriteOffers = (Button) findViewById(R.id.favoriteOffers); requestedOffers = (Button) findViewById(R.id.requestedOffers); myRequestsIMade = (Button) findViewById(R.id.myRequestsIMade); myRequestsAsOwner = (Button) findViewById(R.id.myRequestsAsOwner); favoriteServices.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { print("loading . . ."); _ServerCaller.GetMyFavoriteServices(new OnOprationDoing() { @Override public void OnSuccess(String result) { try { services = ExtracterDataFromJson.getServices(result); main_servicetableLayout.setAdapter(new ServicesArrayAdapter(getApplicationContext(), services)); lasttype = 2; print(""); } catch (Exception e) { OnFail(0, e.getMessage()); } } @Override public void OnFail(int code, String result) { print(result); } }); } }); favoriteOffers.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { print("loading . . ."); _ServerCaller.GetMyLikedOffers(new OnOprationDoing() { @Override public void OnSuccess(String result) { try { offers = ExtracterDataFromJson.getOffers(result); main_servicetableLayout.setAdapter(new OffersArrayAdapter(getApplicationContext(), offers)); lasttype = 3; print(""); } catch (Exception e) { OnFail(0, e.getMessage()); } } @Override public void OnFail(int code, String result) { print(result); } }); } }); requestedOffers.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { print("loading . . ."); _ServerCaller.GetMyRequstedOffers(new OnOprationDoing() { @Override public void OnSuccess(String result) { try { offers = ExtracterDataFromJson.getOffers(result); main_servicetableLayout.setAdapter(new OffersArrayAdapter(getApplicationContext(), offers)); lasttype = 3; print(""); } catch (Exception e) { OnFail(0, e.getMessage()); } } @Override public void OnFail(int code, String result) { print(result); } }); } }); myRequestsIMade.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { print("loading . . ."); _ServerCaller.GetMyRequests(new OnOprationDoing() { @Override public void OnSuccess(String result) { try { requests = ExtracterDataFromJson.getRequests(result); main_servicetableLayout.setAdapter(new RequestsArrayAdapter(getApplicationContext(), requests)); lasttype = 4; print(""); } catch (Exception e) { OnFail(0, e.getMessage()); } } @Override public void OnFail(int code, String result) { print(result); } }); } }); myRequestsAsOwner.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { print("loading . . ."); _ServerCaller.GetRequestsToAdmin(new OnOprationDoing() { @Override public void OnSuccess(String result) { try { requests = ExtracterDataFromJson.getRequests(result); main_servicetableLayout.setAdapter(new RequestsArrayAdapter(getApplicationContext(), requests)); lasttype = 4; print(""); } catch (Exception e) { OnFail(0, e.getMessage()); } } @Override public void OnFail(int code, String result) { print(result); } }); } }); newService.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, CreateServices.class)); } }); myServices.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { print("loading . . ."); _ServerCaller.GetMyServices(new OnOprationDoing() { @Override public void OnSuccess(String result) { try { services = ExtracterDataFromJson.getServices(result); main_servicetableLayout.setAdapter(new ServicesArrayAdapter(getApplicationContext(), services)); lasttype = 2; print(""); } catch (Exception e) { OnFail(0, e.getMessage()); } } @Override public void OnFail(int code, String result) { print(result); } }); } }); main_servicetableLayout.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (lasttype == 1) alert.AlertFriendHandler(freinds.get(position), true); else if (lasttype == 2) alert.AlertServicesHandler(services.get(position), true); else if (lasttype == 3) alert.AlertOffersHandler(offers.get(position), true); else if (lasttype == 4) alert.AlertRequestsHandler(requests.get(position)); } }); main_servicetableLayout.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (lasttype == 1) alert.AlertFriendHandler(freinds.get(position), false); else if (lasttype == 2) alert.AlertServicesHandler(services.get(position), false); else if (lasttype == 3) alert.AlertOffersHandler(offers.get(position), false); return true; } }); myFriends.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { print("loading . . ."); _ServerCaller.GetFriends(new OnOprationDoing() { @Override public void OnSuccess(String result) { try { freinds = ExtracterDataFromJson.getFriends(result); main_servicetableLayout.setAdapter(new FriendsArrayAdapter(getApplicationContext(), freinds)); lasttype = 1; print(""); } catch (Exception e) { OnFail(0, e.getMessage()); } } @Override public void OnFail(int code, String result) { print(result); } }); } }); checkUserTypeToHideItemsThatHeDontAllowedToDoIt(); getLocation(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if(resultCode == RESULT_OK){ if (data.getBooleanExtra("loginSuccess", true)) checkUserTypeToHideItemsThatHeDontAllowedToDoIt(); } } } public void checkUserTypeToHideItemsThatHeDontAllowedToDoIt() // nice name { int visiblity = (ServerSDK._User == null || ServerSDK._User.typeisSP) ? View.VISIBLE : View.GONE; Button b1 = (Button) findViewById(R.id.myRequestsAsOwner); Button b2 = (Button) findViewById(R.id.myServices); Button b3 = (Button) findViewById(R.id.newService); b1.setVisibility(visiblity); b2.setVisibility(visiblity); b3.setVisibility(visiblity); } public void print(String str) { //Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(); statuslabel.setText(str); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_setting) { startActivity(new Intent(MainActivity.this,Settings.class)); } if (item.getItemId() == R.id.action_search) { startActivity(new Intent(MainActivity.this, Search.class)); } if (item.getItemId() == R.id.action_logout) { new AlertDialog.Builder(this) .setTitle("Logout") .setMessage("are you sure ?") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { print("loading . . ."); _ServerCaller.logout(new OnOprationDoing() { @Override public void OnSuccess(String result) { print(""); } @Override public void OnFail(int code, String result) { print(result); } @Override public void afterFinish() { _ServerCaller._User = null; clearStoredData(); startActivityForResult(new Intent(MainActivity.this, Login.class), 1); } }); } }) .setNegativeButton(android.R.string.no, null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } return super.onOptionsItemSelected(item); } public void getLocation() { LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); String provider = LocationManager.GPS_PROVIDER; if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) provider = LocationManager.NETWORK_PROVIDER; else if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { print("Location Service turned off in your device, pleace tune it on"); //return; } locationManager.requestLocationUpdates(provider, 5000, 10, new LocationListener() { @Override public void onLocationChanged(Location location) { ServerSDK._myLatitude = location.getLatitude(); ServerSDK._myLongitude = location.getLongitude(); // String longitude = "Longitude: " + location.getLongitude(); // String latitude = "Latitude: " + location.getLatitude(); // // // To get city name from coordinates // String cityName = null; // Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault()); // List<Address> addresses; // try // { // addresses = gcd.getFromLocation(location.getLatitude(), // location.getLongitude(), 1); // if (addresses.size() > 0) // System.out.println(addresses.get(0).getLocality()); // cityName = addresses.get(0).getLocality(); // } catch (IOException e) // { // print("bad error"); // } // print(longitude + "\n" + latitude + "\n\nMy Current City is: " + cityName); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }); } }
34.822464
143
0.482624
ff35ecd94e2b5d5dc153768257214b4b360042bc
440
package repositories; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import org.springframework.stereotype.Repository; @Repository public interface MasterFileParser { public String getKindNameOf(int kind) throws FileNotFoundException, IOException; public int getKindCodeOf(String kindName) throws FileNotFoundException, IOException; public List<String> getKindNames() throws IOException; }
27.5
85
0.834091
fbdb9c0b35f5197cd75c7481c2e416a502a28af9
3,181
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.camel.component.zookeepermaster package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|zookeepermaster package|; end_package begin_import import|import name|com operator|. name|fasterxml operator|. name|jackson operator|. name|annotation operator|. name|JsonProperty import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|zookeepermaster operator|. name|group operator|. name|NodeState import|; end_import begin_class DECL|class|CamelNodeState specifier|public class|class name|CamelNodeState extends|extends name|NodeState block|{ annotation|@ name|JsonProperty DECL|field|consumer name|String name|consumer decl_stmt|; annotation|@ name|JsonProperty DECL|field|started name|boolean name|started decl_stmt|; DECL|method|CamelNodeState () specifier|public name|CamelNodeState parameter_list|() block|{ } DECL|method|CamelNodeState (String id) specifier|public name|CamelNodeState parameter_list|( name|String name|id parameter_list|) block|{ name|super argument_list|( name|id argument_list|) expr_stmt|; block|} DECL|method|CamelNodeState (String id, String container) specifier|public name|CamelNodeState parameter_list|( name|String name|id parameter_list|, name|String name|container parameter_list|) block|{ name|super argument_list|( name|id argument_list|, name|container argument_list|) expr_stmt|; block|} DECL|method|getConsumer () specifier|public name|String name|getConsumer parameter_list|() block|{ return|return name|consumer return|; block|} DECL|method|setConsumer (String consumer) specifier|public name|void name|setConsumer parameter_list|( name|String name|consumer parameter_list|) block|{ name|this operator|. name|consumer operator|= name|consumer expr_stmt|; block|} DECL|method|isStarted () specifier|public name|boolean name|isStarted parameter_list|() block|{ return|return name|started return|; block|} DECL|method|setStarted (boolean started) specifier|public name|void name|setStarted parameter_list|( name|boolean name|started parameter_list|) block|{ name|this operator|. name|started operator|= name|started expr_stmt|; block|} block|} end_class end_unit
18.934524
810
0.799749
dbfb3bdfe6738364b097b45ee63ffaf9bba48223
240
package com.doktorum.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Doctor { @Id private int id; private String name; private String surname; private Date age; }
13.333333
32
0.754167
00992f69592cccc4e65a5cdfc411d83fdc6c4fd7
888
package cn.fiona.pet.account.vo; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; /** * uuid 视图对象 * * Created by tom on 16/6/28. */ public class UuidVO implements Serializable{ private String uuid; public UuidVO() {} public UuidVO(Object source) { try { BeanUtils.copyProperties(this, source); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
20.651163
56
0.641892
dfa15e29ccfbf48befc9769ff54046582a1d6181
687
package com.kenshine.service; import com.kenshine.domain.DocBean; import org.springframework.data.domain.Page; import java.util.Iterator; import java.util.List; /** * @author :kenshine * @date :Created in 2021/10/25 9:24 * @description:业务逻辑层 * @modified By: * @version: $ */ public interface IElasticService { void createIndex(); void deleteIndex(String index); void save(DocBean docBean); void saveAll(List<DocBean> list); Iterator<DocBean> findAll(); Page<DocBean> findByContent(String content); Page<DocBean> findByFirstCode(String firstCode); Page<DocBean> findBySecordCode(String secordCode); Page<DocBean> query(String key); }
19.083333
54
0.714702
b6ddf43403d7d4f72b9a5bb2442a24328ab9f0cf
3,496
/******************************************************************************* * Copyright (C) 2015 Brocade Communications Systems, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * https://github.com/brocade/vTM-eclipse/LICENSE * This software is distributed "AS IS". * * Contributors: * Brocade Communications Systems - Main Implementation ******************************************************************************/ package com.zeus.eclipsePlugin.filesystem; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import com.zeus.eclipsePlugin.ZDebug; import com.zeus.eclipsePlugin.ZXTMPlugin; import com.zeus.eclipsePlugin.model.ModelElement; import com.zeus.eclipsePlugin.model.ModelListener; import com.zeus.eclipsePlugin.model.ZXTM; import com.zeus.eclipsePlugin.model.ModelElement.Event; import com.zeus.eclipsePlugin.model.ModelElement.State; import com.zeus.eclipsePlugin.project.ZXTMProject; import com.zeus.eclipsePlugin.project.operations.RefreshResourceOp; import com.zeus.eclipsePlugin.swt.SWTUtil; /** * Listens to the model and refreshes the rules directory when something * changes. */ public class ZXTMFileSystemRefresher implements ModelListener { /** * Adds this as a listener to the new child and runs the main update method. */ /* Override */ public void childAdded( ModelElement parent, ModelElement child ) { child.addListener( this ); modelUpdated( child, ModelElement.Event.CHANGED ); } /** * Refreshes the correct rules directory for this element's ZXTM. */ /* Override */ public void modelUpdated( ModelElement element, Event event ) { ZDebug.print( 2, "modelUpdated( ", element, ", ", event, " )" ); // Find the ZXTM for the current element ModelElement current = element; while( current != null && current.getModelType() != ModelElement.Type.ZXTM ){ current = current.getModelParent(); } if( current == null ) return; ZXTM zxtm = (ZXTM) current; ZDebug.print( 2, "Parent ZXTM: ", zxtm ); // Get the project for this ZXTM IProject project = ZXTMProject.getProjectForZXTM( zxtm ); if( project == null || !project.isOpen() || !project.isAccessible() ) { ZDebug.print( 4, "Could not project to refresh for ZXTM: ", zxtm ); return; } // Refresh the rules directory try { ZDebug.print( 4, "Refreshing project: ", project.getName() ); IFolder rulesFolder = project.getFolder( ZXTMFileSystem.RULE_PATH ); if( ZXTMPlugin.isEclipseLoaded() && rulesFolder.exists() ) { SWTUtil.progressBackground( new RefreshResourceOp( rulesFolder, IResource.DEPTH_ONE ), false ); } } catch( InvocationTargetException e ) { ZDebug.printStackTrace( e, "Failed to referesh project: ", project ); } } /** This just runs the main update method. */ /* Override */ public void stateChanged( ModelElement element, State state ) { modelUpdated( element, ModelElement.Event.CHANGED ); } }
34.96
83
0.641018
41cc0b37270a87c7817a0a078e0e9b67ee94350e
21,582
package io.swagger.codegen.languages; import io.swagger.codegen.*; import io.swagger.models.Info; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Swagger; import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; public class ApexClientCodegen extends AbstractJavaCodegen { private static final String CLASS_PREFIX = "classPrefix"; private static final String API_VERSION = "apiVersion"; private static final String BUILD_METHOD = "buildMethod"; private static final String NAMED_CREDENTIAL = "namedCredential"; private static final Logger LOGGER = LoggerFactory.getLogger(ApexClientCodegen.class); private String classPrefix = "Swag"; private String apiVersion = "39.0"; private String buildMethod = "sfdx"; private String namedCredential = classPrefix; private String srcPath = "force-app/main/default/"; public ApexClientCodegen() { super(); importMapping.clear(); testFolder = sourceFolder = srcPath; embeddedTemplateDir = templateDir = "apex"; outputFolder = "generated-code" + File.separator + "apex"; apiPackage = "classes"; modelPackage = "classes"; testPackage = "force-app.main.default.classes"; modelNamePrefix = classPrefix; dateLibrary = ""; apiTemplateFiles.put("api.mustache", ".cls"); apiTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml"); apiTestTemplateFiles.put("api_test.mustache", ".cls"); apiTestTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml"); modelTemplateFiles.put("model.mustache", ".cls"); modelTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml"); modelTestTemplateFiles.put("model_test.mustache", ".cls"); modelTestTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml"); cliOptions.add(CliOption.newString(CLASS_PREFIX, "Prefix for generated classes. Set this to avoid overwriting existing classes in your org.")); cliOptions.add(CliOption.newString(API_VERSION, "The Metadata API version number to use for components in this package.")); cliOptions.add(CliOption.newString(BUILD_METHOD, "The build method for this package.")); cliOptions.add(CliOption.newString(NAMED_CREDENTIAL, "The named credential name for the HTTP callouts")); supportingFiles.add(new SupportingFile("Swagger.cls", srcPath + "classes", "Swagger.cls")); supportingFiles.add(new SupportingFile("cls-meta.mustache", srcPath + "classes", "Swagger.cls-meta.xml")); supportingFiles.add(new SupportingFile("SwaggerTest.cls", srcPath + "classes", "SwaggerTest.cls")); supportingFiles.add(new SupportingFile("cls-meta.mustache", srcPath + "classes", "SwaggerTest.cls-meta.xml")); supportingFiles.add(new SupportingFile("SwaggerResponseMock.cls", srcPath + "classes", "SwaggerResponseMock.cls")); supportingFiles.add(new SupportingFile("cls-meta.mustache", srcPath + "classes", "SwaggerResponseMock.cls-meta.xml")); typeMapping.put("BigDecimal", "Double"); typeMapping.put("binary", "String"); typeMapping.put("ByteArray", "Blob"); typeMapping.put("date", "Date"); typeMapping.put("DateTime", "Datetime"); typeMapping.put("file", "Blob"); typeMapping.put("float", "Double"); typeMapping.put("number", "Double"); typeMapping.put("short", "Integer"); typeMapping.put("UUID", "String"); setReservedWordsLowerCase( Arrays.asList("abstract", "activate", "and", "any", "array", "as", "asc", "autonomous", "begin", "bigdecimal", "blob", "break", "bulk", "by", "byte", "case", "cast", "catch", "char", "class", "collect", "commit", "const", "continue", "convertcurrency", "date", "decimal", "default", "delete", "desc", "do", "else", "end", "enum", "exception", "exit", "export", "extends", "false", "final", "finally", "float", "for", "from", "future", "global", "goto", "group", "having", "hint", "if", "implements", "import", "inner", "insert", "instanceof", "int", "interface", "into", "join", "last_90_days", "last_month", "last_n_days", "last_week", "like", "limit", "list", "long", "loop", "map", "merge", "new", "next_90_days", "next_month", "next_n_days", "next_week", "not", "null", "nulls", "number", "object", "of", "on", "or", "outer", "override", "package", "parallel", "pragma", "private", "protected", "public", "retrieve", "return", "returning", "rollback", "savepoint", "search", "select", "set", "short", "sort", "stat", "static", "super", "switch", "synchronized", "system", "testmethod", "then", "this", "this_month", "this_week", "throw", "today", "tolabel", "tomorrow", "transaction", "trigger", "true", "try", "type", "undelete", "update", "upsert", "using", "virtual", "webservice", "when", "where", "while", "yesterday" )); languageSpecificPrimitives = new HashSet<String>( Arrays.asList("Blob", "Boolean", "Date", "Datetime", "Decimal", "Double", "ID", "Integer", "Long", "Object", "String", "Time" )); } @Override public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(CLASS_PREFIX)) { setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); } additionalProperties.put(CLASS_PREFIX, classPrefix); if (additionalProperties.containsKey(API_VERSION)) { setApiVersion(toApiVersion((String) additionalProperties.get(API_VERSION))); } additionalProperties.put(API_VERSION, apiVersion); if (additionalProperties.containsKey(BUILD_METHOD)) { setBuildMethod((String)additionalProperties.get(BUILD_METHOD)); } additionalProperties.put(BUILD_METHOD, buildMethod); if (additionalProperties.containsKey(NAMED_CREDENTIAL)) { setNamedCredential((String)additionalProperties.get(NAMED_CREDENTIAL)); } additionalProperties.put(NAMED_CREDENTIAL, namedCredential); postProcessOpts(); } @Override public String escapeReservedWord(String name) { // Identifiers must start with a letter return "r" + super.escapeReservedWord(name); } @Override public String toModelName(String name) { String modelName = super.toModelName(name); // Max length is 40; save the last 4 for "Test" if (modelName.length() > 36) { modelName = modelName.substring(0, 36); } return modelName; } @Override public String toDefaultValue(Property p) { String out = null; if (p instanceof ArrayProperty) { Property inner = ((ArrayProperty) p).getItems(); out = String.format( "new List<%s>()", inner == null ? "Object" : getTypeDeclaration(inner) ); } else if (p instanceof BooleanProperty) { // true => "true", false => "false", null => "null" out = String.valueOf(((BooleanProperty) p).getDefault()); } else if (p instanceof LongProperty) { Long def = ((LongProperty) p).getDefault(); out = def == null ? out : def.toString() + "L"; } else if (p instanceof MapProperty) { Property inner = ((MapProperty) p).getAdditionalProperties(); String s = inner == null ? "Object" : getTypeDeclaration(inner); out = String.format("new Map<String, %s>()", s); } else if (p instanceof StringProperty) { StringProperty sp = (StringProperty) p; String def = sp.getDefault(); if (def != null) { out = sp.getEnum() == null ? String.format("'%s'", escapeText(def)) : def; } } else { out = super.toDefaultValue(p); } // we'll skip over null defaults in the model template to avoid redundant initialization return "null".equals(out) ? null : out; } @Override public void setParameterExampleValue(CodegenParameter p) { if (Boolean.TRUE.equals(p.isLong)) { p.example = "2147483648L"; } else if (Boolean.TRUE.equals(p.isFile)) { p.example = "Blob.valueOf('Sample text file\\nContents')"; } else if (Boolean.TRUE.equals(p.isDate)) { p.example = "Date.newInstance(1960, 2, 17)"; } else if (Boolean.TRUE.equals(p.isDateTime)) { p.example = "Datetime.newInstanceGmt(2013, 11, 12, 3, 3, 3)"; } else if (Boolean.TRUE.equals(p.isListContainer)) { p.example = "new " + p.dataType + "{" + p.items.example + "}"; } else if (Boolean.TRUE.equals(p.isMapContainer)) { p.example = "new " + p.dataType + "{" + p.items.example + "}"; } else if (Boolean.TRUE.equals(p.isString)) { p.example = "'" + p.example + "'"; } else if ("".equals(p.example) || p.example == null) { // Get an example object from the generated model p.example = p.dataType + ".getExample()"; } } @Override public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) { CodegenModel cm = super.fromModel(name, model, allDefinitions); if (cm.interfaces == null) { cm.interfaces = new ArrayList<String>(); } Boolean hasDefaultValues = false; // for (de)serializing properties renamed for Apex (e.g. reserved words) List<Map<String, String>> propertyMappings = new ArrayList<>(); for (CodegenProperty p : cm.allVars) { hasDefaultValues |= p.defaultValue != null; if (!p.baseName.equals(p.name)) { Map<String, String> mapping = new HashMap<>(); mapping.put("externalName", p.baseName); mapping.put("internalName", p.name); propertyMappings.add(mapping); } } cm.vendorExtensions.put("hasPropertyMappings", !propertyMappings.isEmpty()); cm.vendorExtensions.put("hasDefaultValues", hasDefaultValues); cm.vendorExtensions.put("propertyMappings", propertyMappings); if (!propertyMappings.isEmpty()) { cm.interfaces.add("Swagger.MappedProperties"); } return cm; } @Override public void postProcessParameter(CodegenParameter parameter) { if (parameter.isBodyParam && parameter.isListContainer) { // items of array bodyParams are being nested an extra level too deep for some reason parameter.items = parameter.items.items; setParameterExampleValue(parameter); } } @Override public void preprocessSwagger(Swagger swagger) { Info info = swagger.getInfo(); String calloutLabel = info.getTitle(); additionalProperties.put("calloutLabel", calloutLabel); String sanitized = sanitizeName(calloutLabel); additionalProperties.put("calloutName", sanitized); supportingFiles.add(new SupportingFile("namedCredential.mustache", srcPath + "/namedCredentials", sanitized + ".namedCredential" )); if (additionalProperties.get(BUILD_METHOD).equals("sfdx")) { generateSfdxSupportingFiles(); } else if (additionalProperties.get(BUILD_METHOD).equals("ant")) { generateAntSupportingFiles(); } } @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) { Boolean hasFormParams = false; for (Parameter p : operation.getParameters()) { if ("formData".equals(p.getIn())) { hasFormParams = true; break; } } // only support serialization into JSON and urlencoded forms for now operation.setConsumes( Collections.singletonList(hasFormParams ? "application/x-www-form-urlencoded" : "application/json")); // only support deserialization from JSON for now operation.setProduces(Collections.singletonList("application/json")); CodegenOperation op = super.fromOperation( path, httpMethod, operation, definitions, swagger); if (op.getHasExamples()) { // prepare examples for Apex test classes Property responseProperty = findMethodResponse(operation.getResponses()).getSchema(); String deserializedExample = toExampleValue(responseProperty); for (Map<String, String> example : op.examples) { example.put("example", escapeText(example.get("example"))); example.put("deserializedExample", deserializedExample); } } return op; } @Override public String escapeQuotationMark(String input) { return input.replace("'", "\\'"); } public void setBuildMethod(String buildMethod) { if (buildMethod.equals("ant")) { this.srcPath = "deploy/"; } else { this.srcPath = "src/"; } testFolder = sourceFolder = srcPath; this.buildMethod = buildMethod; } public void setNamedCredential(String namedCredential) { this.namedCredential = namedCredential; } public void setClassPrefix(String classPrefix) { // the best thing we can do without namespacing in Apex modelNamePrefix = classPrefix; this.classPrefix = classPrefix; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } private String toApiVersion(String apiVersion) { if (apiVersion.matches("^\\d{2}(\\.0)?$")) { return apiVersion.substring(0, 2) + ".0"; } else { LOGGER.warn(String.format("specified API version is invalid: %s - defaulting to %s", apiVersion, this.apiVersion)); return this.apiVersion; } } private void postProcessOpts() { supportingFiles.add( new SupportingFile("client.mustache", srcPath + "classes", classPrefix + "Client.cls")); supportingFiles.add(new SupportingFile("cls-meta.mustache", srcPath + "classes", classPrefix + "Client.cls-meta.xml" )); } @Override public String escapeText(String input) { if (input == null) { return input; } return input.replace("'", "\\'").replace("\n", "\\n").replace("\r", "\\r"); } @Override public String toModelTestFilename(String name) { return toModelName(name) + "Test"; } @Override public String toExampleValue(Property p) { if (p == null) { return ""; } Object obj = p.getExample(); String example = obj == null ? "" : obj.toString(); if (p instanceof ArrayProperty) { example = "new " + getTypeDeclaration(p) + "{" + toExampleValue( ((ArrayProperty) p).getItems()) + "}"; } else if (p instanceof BooleanProperty) { example = String.valueOf(!"false".equals(example)); } else if (p instanceof ByteArrayProperty) { if (example.isEmpty()) { example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"; } ((ByteArrayProperty) p).setExample(example); example = "EncodingUtil.base64Decode('" + example + "')"; } else if (p instanceof DateProperty) { if (example.matches("^\\d{4}(-\\d{2}){2}")) { example = example.substring(0, 10).replaceAll("-0?", ", "); } else if (example.isEmpty()) { example = "2000, 1, 23"; } else { LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 date. Defaulting to '2000-01-23'. [%s]", p .getName(), example)); example = "2000, 1, 23"; } example = "Date.newInstance(" + example + ")"; } else if (p instanceof DateTimeProperty) { if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) { example = example.substring(0, 19).replaceAll("[-T:]0?", ", "); } else if (example.isEmpty()) { example = "2000, 1, 23, 4, 56, 7"; } else { LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 datetime. Defaulting to '2000-01-23T04-56-07Z'. [%s]", p .getName(), example)); example = "2000, 1, 23, 4, 56, 7"; } example = "Datetime.newInstanceGmt(" + example + ")"; } else if (p instanceof DecimalProperty) { example = example.replaceAll("[^-0-9.]", ""); example = example.isEmpty() ? "1.3579" : example; } else if (p instanceof FileProperty) { if (example.isEmpty()) { example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"; ((FileProperty) p).setExample(example); } example = "EncodingUtil.base64Decode(" + example + ")"; } else if (p instanceof EmailProperty) { if (example.isEmpty()) { example = "[email protected]"; ((EmailProperty) p).setExample(example); } example = "'" + example + "'"; } else if (p instanceof LongProperty) { example = example.isEmpty() ? "123456789L" : example + "L"; } else if (p instanceof MapProperty) { example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue( ((MapProperty) p).getAdditionalProperties()) + "}"; } else if (p instanceof ObjectProperty) { example = example.isEmpty() ? "null" : example; } else if (p instanceof PasswordProperty) { example = example.isEmpty() ? "password123" : escapeText(example); ((PasswordProperty) p).setExample(example); example = "'" + example + "'"; } else if (p instanceof RefProperty) { example = getTypeDeclaration(p) + ".getExample()"; } else if (p instanceof StringProperty) { StringProperty sp = (StringProperty) p; List<String> enums = sp.getEnum(); if (enums != null && example.isEmpty()) { example = enums.get(0); sp.setExample(example); } else if (example.isEmpty()) { example = "aeiou"; } else { example = escapeText(example); sp.setExample(example); } example = "'" + example + "'"; } else if (p instanceof UUIDProperty) { example = example.isEmpty() ? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'" : "'" + escapeText(example) + "'"; } else if (p instanceof BaseIntegerProperty) { example = example.matches("^-?\\d+$") ? example : "123"; } return example; } @Override public String toApiName(String name) { return camelize(classPrefix + super.toApiName(name)); } @Override public void updateCodegenPropertyEnum(CodegenProperty var) { super.updateCodegenPropertyEnum(var); if (var.isEnum && var.example != null) { String example = var.example.replace("'", ""); example = toEnumVarName(example, var.datatype); var.example = toEnumDefaultValue(example, var.datatypeWithEnum); } } @Override public CodegenType getTag() { return CodegenType.CLIENT; } @Override public String getName() { return "apex"; } @Override public String getHelp() { return "Generates an Apex API client library (beta)."; } private void generateAntSupportingFiles() { supportingFiles.add(new SupportingFile("package.mustache", "deploy", "package.xml")); supportingFiles.add(new SupportingFile("package.mustache", "undeploy", "destructiveChanges.xml")); supportingFiles.add(new SupportingFile("build.mustache", "build.xml")); supportingFiles.add(new SupportingFile("build.properties", "build.properties")); supportingFiles.add(new SupportingFile("remove.package.mustache", "undeploy", "package.xml")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); writeOptional(outputFolder, new SupportingFile("README_ant.mustache", "README.md")); } private void generateSfdxSupportingFiles() { supportingFiles.add(new SupportingFile("sfdx.mustache", "", "sfdx-oss-manifest.json")); writeOptional(outputFolder, new SupportingFile("README_sfdx.mustache", "README.md")); } }
42.821429
161
0.590631
c99007895ee7d6691ebc26718281d75aa9dd550f
20,004
package console.common; import console.exception.ConsoleMessageException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.BinaryExpression; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitorAdapter; import net.sf.jsqlparser.expression.Function; import net.sf.jsqlparser.expression.NotExpression; import net.sf.jsqlparser.expression.operators.conditional.OrExpression; import net.sf.jsqlparser.expression.operators.relational.ComparisonOperator; import net.sf.jsqlparser.expression.operators.relational.InExpression; import net.sf.jsqlparser.expression.operators.relational.IsNullExpression; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.expression.operators.relational.LikeExpression; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.create.table.ColumnDefinition; import net.sf.jsqlparser.statement.create.table.CreateTable; import net.sf.jsqlparser.statement.create.table.Index; import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.insert.Insert; import net.sf.jsqlparser.statement.select.Limit; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.select.SelectExpressionItem; import net.sf.jsqlparser.statement.select.SelectItem; import net.sf.jsqlparser.statement.select.SubSelect; import net.sf.jsqlparser.statement.update.Update; import net.sf.jsqlparser.util.TablesNamesFinder; import org.fisco.bcos.web3j.precompile.crud.Condition; import org.fisco.bcos.web3j.precompile.crud.Entry; import org.fisco.bcos.web3j.precompile.crud.EnumOP; import org.fisco.bcos.web3j.precompile.crud.Table; public class CRUDParseUtils { public static final String PRIMARY_KEY = "primary key"; public static void parseCreateTable(String sql, Table table) throws JSQLParserException, ConsoleMessageException { Statement statement = CCJSqlParserUtil.parse(sql); CreateTable createTable = (CreateTable) statement; // parse table name String tableName = createTable.getTable().getName(); table.setTableName(tableName); // parse key from index boolean keyFlag = false; List<Index> indexes = createTable.getIndexes(); if (indexes != null) { if (indexes.size() > 1) { throw new ConsoleMessageException( "Please provide only one primary key for the table."); } keyFlag = true; Index index = indexes.get(0); String type = index.getType().toLowerCase(); if (PRIMARY_KEY.equals(type)) { table.setKey(index.getColumnsNames().get(0)); } else { throw new ConsoleMessageException( "Please provide only one primary key for the table."); } } List<ColumnDefinition> columnDefinitions = createTable.getColumnDefinitions(); // parse key from ColumnDefinition for (int i = 0; i < columnDefinitions.size(); i++) { List<String> columnSpecStrings = columnDefinitions.get(i).getColumnSpecStrings(); if (columnSpecStrings == null) { continue; } else { if (columnSpecStrings.size() == 2 && "primary".equals(columnSpecStrings.get(0)) && "key".equals(columnSpecStrings.get(1))) { String key = columnDefinitions.get(i).getColumnName(); if (keyFlag) { if (!table.getKey().equals(key)) { throw new ConsoleMessageException( "Please provide only one primary key for the table."); } } else { keyFlag = true; table.setKey(key); } break; } } } if (!keyFlag) { throw new ConsoleMessageException("Please provide a primary key for the table."); } // parse value field List<String> fieldsList = new ArrayList<>(); for (int i = 0; i < columnDefinitions.size(); i++) { String columnName = columnDefinitions.get(i).getColumnName(); if (fieldsList.contains(columnName)) { throw new ConsoleMessageException( "Please provide the field '" + columnName + "' only once."); } else { fieldsList.add(columnName); } } if (!fieldsList.contains(table.getKey())) { throw new ConsoleMessageException( "Please provide the field '" + table.getKey() + "' in column definition."); } else { fieldsList.remove(table.getKey()); } StringBuffer fields = new StringBuffer(); for (int i = 0; i < fieldsList.size(); i++) { fields.append(fieldsList.get(i)); if (i != fieldsList.size() - 1) { fields.append(","); } } table.setValueFields(fields.toString()); } public static boolean parseInsert(String sql, Table table, Entry entry) throws JSQLParserException, ConsoleMessageException { Statement statement = CCJSqlParserUtil.parse(sql); Insert insert = (Insert) statement; if (insert.getSelect() != null) { throw new ConsoleMessageException("The insert select clause is not supported."); } // parse table name String tableName = insert.getTable().getName(); table.setTableName(tableName); // parse columns List<Column> columns = insert.getColumns(); ItemsList itemsList = insert.getItemsList(); String items = itemsList.toString(); String[] rawItem = items.substring(1, items.length() - 1).split(","); String[] itemArr = new String[rawItem.length]; for (int i = 0; i < rawItem.length; i++) { itemArr[i] = rawItem[i].trim(); } if (columns != null) { if (columns.size() != itemArr.length) { throw new ConsoleMessageException("Column count doesn't match value count."); } List<String> columnNames = new ArrayList<>(); for (Column column : columns) { String columnName = trimQuotes(column.toString()); if (columnNames.contains(columnName)) { throw new ConsoleMessageException( "Please provide the field '" + columnName + "' only once."); } else { columnNames.add(columnName); } } for (int i = 0; i < columnNames.size(); i++) { entry.put(columnNames.get(i), trimQuotes(itemArr[i])); } return false; } else { for (int i = 0; i < itemArr.length; i++) { entry.put(i + "", trimQuotes(itemArr[i])); } return true; } } public static void parseSelect( String sql, Table table, Condition condition, List<String> selectColumns) throws JSQLParserException, ConsoleMessageException { Statement statement; statement = CCJSqlParserUtil.parse(sql); Select selectStatement = (Select) statement; // parse table name TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); List<String> tableList = tablesNamesFinder.getTableList(selectStatement); if (tableList.size() != 1) { throw new ConsoleMessageException("Please provide only one table name."); } table.setTableName(tableList.get(0)); // parse where clause PlainSelect selectBody = (PlainSelect) selectStatement.getSelectBody(); if (selectBody.getOrderByElements() != null) { throw new ConsoleMessageException("The order clause is not supported."); } if (selectBody.getGroupBy() != null) { throw new ConsoleMessageException("The group clause is not supported."); } if (selectBody.getHaving() != null) { throw new ConsoleMessageException("The having clause is not supported."); } if (selectBody.getJoins() != null) { throw new ConsoleMessageException("The join clause is not supported."); } if (selectBody.getTop() != null) { throw new ConsoleMessageException("The top clause is not supported."); } if (selectBody.getDistinct() != null) { throw new ConsoleMessageException("The distinct clause is not supported."); } Expression expr = selectBody.getWhere(); condition = handleExpression(condition, expr); Limit limit = selectBody.getLimit(); if (limit != null) { parseLimit(condition, limit); } // parse select item List<SelectItem> selectItems = selectBody.getSelectItems(); for (SelectItem item : selectItems) { if (item instanceof SelectExpressionItem) { SelectExpressionItem selectExpressionItem = (SelectExpressionItem) item; Expression expression = selectExpressionItem.getExpression(); if (expression instanceof Function) { Function func = (Function) expression; throw new ConsoleMessageException( "The " + func.getName() + " function is not supported."); } } selectColumns.add(item.toString()); } } private static Condition handleExpression(Condition condition, Expression expr) throws ConsoleMessageException { if (expr instanceof BinaryExpression) { condition = getWhereClause((BinaryExpression) (expr), condition); } if (expr instanceof OrExpression) { throw new ConsoleMessageException("The OrExpression is not supported."); } if (expr instanceof NotExpression) { throw new ConsoleMessageException("The NotExpression is not supported."); } if (expr instanceof InExpression) { throw new ConsoleMessageException("The InExpression is not supported."); } if (expr instanceof LikeExpression) { throw new ConsoleMessageException("The LikeExpression is not supported."); } if (expr instanceof SubSelect) { throw new ConsoleMessageException("The SubSelect is not supported."); } if (expr instanceof IsNullExpression) { throw new ConsoleMessageException("The IsNullExpression is not supported."); } Map<String, Map<EnumOP, String>> conditions = condition.getConditions(); Set<String> keys = conditions.keySet(); for (String key : keys) { Map<EnumOP, String> value = conditions.get(key); EnumOP operation = value.keySet().iterator().next(); String itemValue = value.values().iterator().next(); String newValue = trimQuotes(itemValue); value.put(operation, newValue); conditions.put(key, value); } condition.setConditions(conditions); return condition; } public static String trimQuotes(String str) { char[] value = str.toCharArray(); int len = value.length; int st = 1; char[] val = value; /* avoid getfield opcode */ while ((st < len) && (val[st] == '"' || val[st] == '\'')) { st++; } while ((st < len) && (val[len - 1] == '"' || val[len - 1] == '\'')) { len--; } String string = ((st > 1) || (len < value.length)) ? str.substring(st, len) : str; return string; } public static void parseUpdate(String sql, Table table, Entry entry, Condition condition) throws JSQLParserException, ConsoleMessageException { Statement statement = CCJSqlParserUtil.parse(sql); Update update = (Update) statement; // parse table name List<net.sf.jsqlparser.schema.Table> tables = update.getTables(); String tableName = tables.get(0).getName(); table.setTableName(tableName); // parse cloumns List<Column> columns = update.getColumns(); List<Expression> expressions = update.getExpressions(); int size = expressions.size(); String[] values = new String[size]; for (int i = 0; i < size; i++) { values[i] = expressions.get(i).toString(); } for (int i = 0; i < columns.size(); i++) { entry.put(trimQuotes(columns.get(i).toString()), trimQuotes(values[i])); } // parse where clause Expression where = update.getWhere(); if (where != null) { BinaryExpression expr2 = (BinaryExpression) (where); handleExpression(condition, expr2); } Limit limit = update.getLimit(); parseLimit(condition, limit); } public static void parseRemove(String sql, Table table, Condition condition) throws JSQLParserException, ConsoleMessageException { Statement statement = CCJSqlParserUtil.parse(sql); Delete delete = (Delete) statement; // parse table name net.sf.jsqlparser.schema.Table sqlTable = delete.getTable(); table.setTableName(sqlTable.getName()); // parse where clause Expression where = delete.getWhere(); if (where != null) { BinaryExpression expr = (BinaryExpression) (where); handleExpression(condition, expr); } Limit limit = delete.getLimit(); parseLimit(condition, limit); } private static void parseLimit(Condition condition, Limit limit) throws ConsoleMessageException { if (limit != null) { Expression offset = limit.getOffset(); Expression count = limit.getRowCount(); try { if (offset != null) { condition.Limit( Integer.parseInt(offset.toString()), Integer.parseInt(count.toString())); } else { condition.Limit(Integer.parseInt(count.toString())); } } catch (NumberFormatException e) { throw new ConsoleMessageException( "Please provide limit parameters by non-negative integer mode, " + Common.NonNegativeIntegerRange + "."); } } } private static Condition getWhereClause(Expression expr, Condition condition) { expr.accept( new ExpressionVisitorAdapter() { @Override protected void visitBinaryExpression(BinaryExpression expr) { if (expr instanceof ComparisonOperator) { String key = trimQuotes(expr.getLeftExpression().toString()); String operation = expr.getStringExpression(); String value = trimQuotes(expr.getRightExpression().toString()); switch (operation) { case "=": condition.EQ(key, value); break; case "!=": condition.NE(key, value); break; case ">": condition.GT(key, value); break; case ">=": condition.GE(key, value); break; case "<": condition.LT(key, value); break; case "<=": condition.LE(key, value); break; default: break; } } super.visitBinaryExpression(expr); } }); return condition; } public static void invalidSymbol(String sql) throws ConsoleMessageException { if (sql.contains(";")) { throw new ConsoleMessageException("SyntaxError: Unexpected Chinese semicolon."); } else if (sql.contains("“") || sql.contains("”") || sql.contains("‘") || sql.contains("’")) { throw new ConsoleMessageException("SyntaxError: Unexpected Chinese quotes."); } else if (sql.contains(",")) { throw new ConsoleMessageException("SyntaxError: Unexpected Chinese comma."); } } public static void checkTableParams(Table table) throws ConsoleMessageException { if (table.getTableName().length() > Common.SYS_TABLE_KEY_MAX_LENGTH) { throw new ConsoleMessageException( "The table name length is greater than " + Common.SYS_TABLE_KEY_MAX_LENGTH + "."); } if (table.getKey().length() > Common.SYS_TABLE_KEY_FIELD_NAME_MAX_LENGTH) { throw new ConsoleMessageException( "The table primary key name length is greater than " + Common.SYS_TABLE_KEY_FIELD_NAME_MAX_LENGTH + "."); } String[] valueFields = table.getValueFields().split(","); for (String valueField : valueFields) { if (valueField.length() > Common.USER_TABLE_FIELD_NAME_MAX_LENGTH) { throw new ConsoleMessageException( "The table field name length is greater than " + Common.USER_TABLE_FIELD_NAME_MAX_LENGTH + "."); } } if (table.getValueFields().length() > Common.SYS_TABLE_VALUE_FIELD_MAX_LENGTH) { throw new ConsoleMessageException( "The table total field name length is greater than " + Common.SYS_TABLE_VALUE_FIELD_MAX_LENGTH + "."); } } public static void checkUserTableParam(Entry entry, Table descTable) throws ConsoleMessageException { Map<String, String> fieldsMap = entry.getFields(); Set<String> keys = fieldsMap.keySet(); for (String key : keys) { if (key.equals(descTable.getKey())) { if (fieldsMap.get(key).length() > Common.USER_TABLE_KEY_VALUE_MAX_LENGTH) { throw new ConsoleMessageException( "The table primary key value length is greater than " + Common.USER_TABLE_KEY_VALUE_MAX_LENGTH + "."); } } else { if (fieldsMap.get(key).length() > Common.USER_TABLE_FIELD_VALUE_MAX_LENGTH) { throw new ConsoleMessageException( "The table field '" + key + "' value length is greater than 16M - 1."); } } } } }
43.298701
99
0.562238
b0340c3242c74bc7e6abada8c5d861b0e6494ebc
81
open module listenablefuture { // exports com.google.guava.listenablefuture; }
27
48
0.777778
6b6304527296c07d36067ae7cae4462d9f7fb9e2
6,928
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sentry.provider.db.log.entity; import java.io.IOException; import java.io.StringWriter; import org.apache.sentry.provider.db.log.util.Constants; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.MappingJsonFactory; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ContainerNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AuditMetadataLogEntity implements JsonLogEntity { private static final Logger LOGGER = LoggerFactory .getLogger(AuditMetadataLogEntity.class); private static final JsonFactory factory = new MappingJsonFactory(); private String serviceName; private String userName; private String impersonator; private String ipAddress; private String operation; private String eventTime; private String operationText; private String allowed; private String databaseName; private String tableName; private String columnName; private String resourcePath; private String objectType; public AuditMetadataLogEntity() { } public AuditMetadataLogEntity(String serviceName, String userName, String impersonator, String ipAddress, String operation, String eventTime, String operationText, String allowed, String databaseName, String tableName, String columnName, String resourcePath, String objectType) { this.serviceName = serviceName; this.userName = userName; this.impersonator = impersonator; this.ipAddress = ipAddress; this.operation = operation; this.eventTime = eventTime; this.operationText = operationText; this.allowed = allowed; this.databaseName = databaseName; this.tableName = tableName; this.columnName = columnName; this.resourcePath = resourcePath; this.objectType = objectType; } @Override public String toJsonFormatLog() { StringWriter stringWriter = new StringWriter(); JsonGenerator json = null; try { json = factory.createJsonGenerator(stringWriter); json.writeStartObject(); json.writeStringField(Constants.LOG_FIELD_SERVICE_NAME, serviceName); json.writeStringField(Constants.LOG_FIELD_USER_NAME, userName); json.writeStringField(Constants.LOG_FIELD_IMPERSONATOR, impersonator); json.writeStringField(Constants.LOG_FIELD_IP_ADDRESS, ipAddress); json.writeStringField(Constants.LOG_FIELD_OPERATION, operation); json.writeStringField(Constants.LOG_FIELD_EVENT_TIME, eventTime); json.writeStringField(Constants.LOG_FIELD_OPERATION_TEXT, operationText); json.writeStringField(Constants.LOG_FIELD_ALLOWED, allowed); json.writeStringField(Constants.LOG_FIELD_DATABASE_NAME, databaseName); json.writeStringField(Constants.LOG_FIELD_TABLE_NAME, tableName); json.writeStringField(Constants.LOG_FIELD_COLUMN_NAME, columnName); json.writeStringField(Constants.LOG_FIELD_RESOURCE_PATH, resourcePath); json.writeStringField(Constants.LOG_FIELD_OBJECT_TYPE, objectType); json.writeEndObject(); json.flush(); } catch (IOException e) { // if there has error when creating the audit log in json, set the audit // log to empty. stringWriter = new StringWriter(); String msg = "Error creating audit log in json format: " + e.getMessage(); LOGGER.error(msg, e); } finally { try { if (json != null) { json.close(); } } catch (IOException e) { LOGGER.error("Error closing JsonGenerator", e); } } return stringWriter.toString(); } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getImpersonator() { return impersonator; } public void setImpersonator(String impersonator) { this.impersonator = impersonator; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; } public String getEventTime() { return eventTime; } public void setEventTime(String eventTime) { this.eventTime = eventTime; } public String getOperationText() { return operationText; } public void setOperationText(String operationText) { this.operationText = operationText; } public String getAllowed() { return allowed; } public void setAllowed(String allowed) { this.allowed = allowed; } public String getDatabaseName() { return databaseName; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getResourcePath() { return resourcePath; } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } public String getObjectType() { return objectType; } public void setObjectType(String objectType) { this.objectType = objectType; } /** * For use in tests * * @param json * incoming JSON to parse * @return a node tree * @throws IOException * on any parsing problems */ public static ContainerNode parse(String json) throws IOException { ObjectMapper mapper = new ObjectMapper(factory); JsonNode jsonNode = mapper.readTree(json); if (!(jsonNode instanceof ContainerNode)) { throw new IOException("Wrong JSON data: " + json); } return (ContainerNode) jsonNode; } }
28.987448
80
0.724452
7f545579d9532d197520892997e4568d67f62b6a
548
package xyz.flysium.photon.dao.entity; /** * * * @author zeno (Sven Augustus) * @version 1.0 */ public class Item { private Long id; private String title; public Item() { } public Item(Long id, String title) { this.id = id; this.title = title; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
14.051282
40
0.536496
10cd4ec36e9aa189f20a066950104712c51732d0
690
package br.com.safeguard.params; import java.io.Serializable; import br.com.safeguard.interfaces.BaseParam; /** * * Classe pojo usada para servir de bind para validação de paramentros * * @author Gilmar Carlos * */ public class Param implements Serializable{ private static final long serialVersionUID = 1L; private BaseParam type; private String value; public Param(BaseParam type, String value) { this.type = type; this.value = value; } public BaseParam getType() { return type; } public void setType(BaseParam type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
17.692308
70
0.710145
a3762a94f428706dbccadf60435201cab727c941
983
package com.github.athingx.athing.aliyun.config.thing.impl.domain; import com.github.athingx.athing.aliyun.config.thing.Scope; import com.google.gson.annotations.SerializedName; /** * 配置拉取 */ public class Pull { @SerializedName("id") private final String token; @SerializedName("version") private final String version; @SerializedName("method") private final String method; @SerializedName("params") private final Param param; public Pull(String token) { this.token = token; this.version = "1.0"; this.method = "thing.config.get"; this.param = new Param(Scope.PRODUCT.name(), "file"); } private static class Param { @SerializedName("configScope") private final String scope; @SerializedName("getType") private final String type; private Param(String scope, String type) { this.scope = scope; this.type = type; } } }
21.369565
66
0.632757
2cc3e3658068b25446ae936f4fae6af5ff07ee33
3,576
package org.atlasapi.output.annotation; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; import com.metabroadcast.common.ids.NumberToShortStringCodec; import com.metabroadcast.common.stream.MoreCollectors; import org.atlasapi.channel.ResolvedChannel; import org.atlasapi.content.Broadcast; import org.atlasapi.content.Content; import org.atlasapi.content.Item; import org.atlasapi.content.ResolvedBroadcast; import org.atlasapi.entity.Id; import org.atlasapi.output.FieldWriter; import org.atlasapi.output.OutputContext; import org.atlasapi.output.ResolvedChannelResolver; import org.atlasapi.output.writers.BroadcastWriter; import org.joda.time.DateTime; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class FirstBroadcastAnnotation extends OutputAnnotation<Content> { private final BroadcastWriter broadcastWriter; private final ResolvedChannelResolver resolvedChannelResolver; private FirstBroadcastAnnotation( BroadcastWriter broadcastWriter, ResolvedChannelResolver resolvedChannelResolver ) { this.broadcastWriter = broadcastWriter; this.resolvedChannelResolver = resolvedChannelResolver; } public static FirstBroadcastAnnotation create( NumberToShortStringCodec codec, ResolvedChannelResolver resolvedChannelResolver ) { return new FirstBroadcastAnnotation( BroadcastWriter.create( "first_broadcasts", "broadcast", codec ), resolvedChannelResolver ); } @Override public void write(Content entity, FieldWriter writer, OutputContext ctxt) throws IOException { if (entity instanceof Item) { writeBroadcasts(writer, (Item) entity, ctxt); } } private void writeBroadcasts(FieldWriter writer, Item item, OutputContext ctxt) throws IOException { List<Broadcast> broadcasts = item.getBroadcasts().stream() .filter(Broadcast::isActivelyPublished) .collect(Collectors.toList()); List<Broadcast> firstBroadcasts = ImmutableList.copyOf(firstBroadcasts(broadcasts)); Map<Id, ResolvedChannel> channelMap = resolvedChannelResolver.resolveChannelMap(firstBroadcasts); List<ResolvedBroadcast> resolvedBroadcasts = firstBroadcasts.stream() .map(broadcast -> ResolvedBroadcast.create(broadcast, channelMap.get(broadcast.getChannelId()))) .collect(MoreCollectors.toImmutableList()); writer.writeList( broadcastWriter, resolvedBroadcasts, ctxt ); } private Iterable<Broadcast> firstBroadcasts(Iterable<Broadcast> broadcasts) { DateTime earliest = null; Builder<Broadcast> filteredBroadcasts = ImmutableSet.builder(); for (Broadcast broadcast : broadcasts) { DateTime transmissionTime = broadcast.getTransmissionTime(); if (earliest == null || transmissionTime.isBefore(earliest)) { earliest = transmissionTime; filteredBroadcasts = ImmutableSet.<Broadcast>builder().add(broadcast); } else if (transmissionTime.isEqual(earliest)) { filteredBroadcasts.add(broadcast); } } return filteredBroadcasts.build(); } }
36.865979
112
0.692673
ce0510e833f008eeeee191b5bae0713c7eb0adbf
1,575
package org.aries.launcher; import org.aries.Assert; import org.aries.launcher.JavaApplicationLauncher; import org.aries.launcher.JavaProgram; import org.aries.util.ObjectUtil; import org.aries.util.test.AbstractMultiThreadedIT; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; /** * Generated by Nam. * */ @RunWith(MockitoJUnitRunner.class) public class JavaApplicationLauncherIT extends AbstractMultiThreadedIT { private JavaApplicationLauncher fixture; @Before public void setUp() throws Exception { super.setUp(); fixture = createFixture(); ObjectUtil.writeObjectToTempFile("", "test"); } @After public void tearDown() throws Exception { fixture = null; super.tearDown(); } protected JavaApplicationLauncher createFixture() throws Exception { fixture = new JavaApplicationLauncher(createProgramForTest()); return fixture; } protected JavaProgram createProgramForTest() { JavaProgram program = new JavaProgram(); program.setName("test_program"); program.setMainClass(getClass().getCanonicalName()); return program; } public static void main(String[] args) throws Exception { System.out.println("Executing within process..."); ObjectUtil.writeObjectToTempFile("DONE", "test"); } @Test public void testExecution() throws Exception { fixture.initialize(); fixture.start(); fixture.join(); String output = ObjectUtil.readObjectFromTempFile("test"); Assert.equals(output, "DONE", "Unexpected output"); } }
24.230769
72
0.76127
826b3d97cb931c2afa3d7aa9c3e62984164b0427
623
package fr.houseofcode.dap.server.gal; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; //TODO gal by Djer |Audit Code| (re)-active PMD et Checkstyle. Commentaire Javadoc (de classe) manquant. /** * * @author Alex */ @RestController public class HelloController { /** * * @return */ @RequestMapping("/") //TODO gal by Djer |Audit Code| (re)-active PMD et Checkstyle. Commentaire Javadoc (de méthode) manquant. public String index() { return "Bienvenue sur Spring Boot!"; } }
27.086957
110
0.667737
e86e0f85eba9b0e309fdca30b78e2f464b85a78b
64
package com.example.libnavcompiler; public class MyClass { }
16
36
0.765625
cb1b7729f7268851b768891791f9ec2a259f7ec9
553
/* * Copyright (c) 2020-2021 Pcap Project * SPDX-License-Identifier: MIT OR Apache-2.0 */ package pcap.spi; import java.nio.channels.SelectionKey; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) class SelectionTest { @Test void readWrite() { Assertions.assertEquals(SelectionKey.OP_READ, Selection.OPERATION_READ); Assertions.assertEquals(SelectionKey.OP_WRITE, Selection.OPERATION_WRITE); } }
25.136364
78
0.777577
eeed36128d8defae748e9186751fde563a34150e
3,957
package open.hui.ren.githubclientdemo.main.tabs.overview; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import com.google.android.agera.MutableRepository; import com.google.android.agera.Result; import java.util.ArrayList; import javax.inject.Inject; import open.hui.ren.githubclientdemo.ConstConfig; import open.hui.ren.githubclientdemo.MyApplication; import open.hui.ren.githubclientdemo.PreferenceService; import open.hui.ren.githubclientdemo.entities.Repo; import open.hui.ren.githubclientdemo.entities.UserInfo; import open.hui.ren.githubclientdemo.params.OverViewParams; import open.hui.ren.githubclientdemo.utils.ACache; import retrofit2.Retrofit; import tom.hui.ren.core.BasePresenter; import tom.hui.ren.core.BaseSupplier; /** * @author renhui * @date 16-10-25 * @desc OverView模块的业务模型,数据的获取、事件的推送、以及有关于数据存储的业务都由这里进行封装 */ public class OverViewSupplier extends BaseSupplier<OverViewParams> { @Inject ACache mACache; @Inject Retrofit mRetrofit; @Inject PreferenceService mPreferenceService; private MutableRepository<OverViewParams> mRepository;//上游数据Repository,主要负责参数输入 private Context mContext; public ArrayList<UserInfo> mFollowers; public ArrayList<UserInfo> mFollowings; public ArrayList<Repo> mStarred; public ArrayList<Repo> mRepos; public OverViewSupplier(BasePresenter presenter, MutableRepository repository) { super(presenter, repository); mPresenter = presenter; mRepository = repository; mContext = mPresenter.getView() .getCtx(); MyApplication.ComponentHolder.getCommonComponent() .inject(this); } @Override public Result<OverViewParams> loadData() { OverViewParams params = mRepository.get(); if (params == null) { return Result.failure(); } else if (TextUtils.isEmpty(params.tabName) || TextUtils.isEmpty(params.index)) { return Result.failure(new Throwable("params username is empty")); } String tab = params.tabName; if (tab.equals("followers")) { return Result.success(new OverViewParams("followers", "1")); } else if (tab.equals("followings")) { return Result.success(new OverViewParams("followings", "2")); } else if (tab.equals("starred")) { return Result.success(new OverViewParams("starred", "3")); } else if (tab.equals("repos")) { return Result.success(new OverViewParams("repos", "4")); } else if (tab.equals("events")) { return Result.success(new OverViewParams("events", "9")); } return Result.failure(); } @NonNull @Override public Result<OverViewParams> get() { return loadData(); } public ArrayList<UserInfo> getFollowers() { Object object = mACache.getAsObject(ConstConfig.S_FOLLOWERS); if (object == null) { return new ArrayList<>(); } else { return (ArrayList<UserInfo>) object; } } public ArrayList<UserInfo> getFollowings() { Object object = mACache.getAsObject(ConstConfig.S_FOLLOWINGS); if (object == null) { return new ArrayList<>(); } else { return (ArrayList<UserInfo>) object; } } public ArrayList<Repo> getStarred() { Object object = mACache.getAsObject(ConstConfig.S_STARRED); if (object == null) { return new ArrayList<>(); } else { return (ArrayList<Repo>) object; } } public ArrayList<Repo> getRepos() { Object object = mACache.getAsObject(ConstConfig.S_REPOES); if (object == null) { return new ArrayList<>(); } else { return (ArrayList<Repo>) object; } } }
31.91129
90
0.643164
d83c03b909b2202f2ce4244be423c76621161682
1,282
package com.dandy.glengine; import android.content.Context; import com.dandy.helper.android.LogHelper; import java.util.ArrayList; import java.util.List; public abstract class Group extends Actor { private static final String TAG = "Group"; public Group(Context context) { super(context); } protected List<Actor> mChildren = new ArrayList<Actor>(); /** * <pre> * Add the actors into this group. * 添加actors到组里来 * </pre> * * @param actors actors to add as children */ public void addChild(Actor... actors) { synchronized (this) { for (Actor child : actors) { if (child == null) { continue; } // Avoid adding duplicated child if (mChildren.contains(child)) { LogHelper.d(TAG, "The actor is already in the group"); continue; } mChildren.add(child); onChildAdded(child); child.setParent(this); LogHelper.d(TAG, LogHelper.getThreadName() + "mContext=" + mContext); } } } /** * @param child */ protected abstract void onChildAdded(Actor child); }
24.653846
85
0.536661
ab458b09de0d3bbdb70511a1504eb559958432a9
1,679
package com.skytala.eCommerce.domain.product.relations.prodCatalog.command.invFacility; import org.apache.ofbiz.entity.Delegator; import org.apache.ofbiz.entity.DelegatorFactory; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import com.skytala.eCommerce.domain.product.relations.prodCatalog.event.invFacility.ProdCatalogInvFacilityAdded; import com.skytala.eCommerce.domain.product.relations.prodCatalog.mapper.invFacility.ProdCatalogInvFacilityMapper; import com.skytala.eCommerce.domain.product.relations.prodCatalog.model.invFacility.ProdCatalogInvFacility; import com.skytala.eCommerce.framework.pubsub.Broker; import com.skytala.eCommerce.framework.pubsub.Command; import com.skytala.eCommerce.framework.pubsub.Event; import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit; public class AddProdCatalogInvFacility extends Command { private ProdCatalogInvFacility elementToBeAdded; public AddProdCatalogInvFacility(ProdCatalogInvFacility elementToBeAdded){ this.elementToBeAdded = elementToBeAdded; } @Override public Event execute(){ Delegator delegator = DelegatorFactory.getDelegator("default"); ProdCatalogInvFacility addedElement = null; boolean success = false; try { GenericValue newValue = delegator.makeValue("ProdCatalogInvFacility", elementToBeAdded.mapAttributeField()); addedElement = ProdCatalogInvFacilityMapper.map(delegator.create(newValue)); success = true; } catch(GenericEntityException e) { e.printStackTrace(); addedElement = null; } Event resultingEvent = new ProdCatalogInvFacilityAdded(addedElement, success); Broker.instance().publish(resultingEvent); return resultingEvent; } }
39.046512
114
0.848124
6191c8a110d5d8dc78ef37b4ed144ac58eacc094
2,618
package com.packtpub.wflydevelopment.chapter5.controller; import com.packtpub.wflydevelopment.chapter5.control.TicketService; import com.packtpub.wflydevelopment.chapter5.entity.SeatPosition; import com.packtpub.wflydevelopment.chapter5.entity.SeatType; import javax.annotation.PostConstruct; import javax.enterprise.inject.Model; import javax.enterprise.inject.Produces; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import java.util.Arrays; import java.util.List; @Model public class TheatreSetupService { @Inject private FacesContext facesContext; @Inject private TicketService ticketService; @Inject private List<SeatType> seatTypes; @Produces @Named private SeatType newSeatType; @PostConstruct public void initNewSeatType() { newSeatType = new SeatType(); } public String createTheatre() { ticketService.createTheatre(seatTypes); return "book"; } public String restart() { ticketService.doCleanUp(); return "/index"; } public void addNewSeats() throws Exception { try { ticketService.createSeatType(newSeatType); final FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Done!", "Seats Added"); facesContext.addMessage(null, m); initNewSeatType(); } catch (Exception e) { final String errorMessage = getRootErrorMessage(e); FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Error while saving data"); facesContext.addMessage(null, m); } } private String getRootErrorMessage(Exception e) { // Default to general error message that registration failed. String errorMessage = "Registration failed. See server log for more information"; if (e == null) { // This shouldn't happen, but return the default messages return errorMessage; } // Start with the exception and recurse to find the root cause Throwable t = e; while (t != null) { // Get the message from the Throwable class instance errorMessage = t.getLocalizedMessage(); t = t.getCause(); } // This is the root cause message return errorMessage; } public List<SeatPosition> getPositions() { return Arrays.asList(SeatPosition.values()); } }
30.44186
117
0.650879
3e1e497bcb30bec3335ee49019c8cd615e25d31c
10,371
/** * Copyright (c) 2019, Sinlmao ([email protected]). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.sinlmao.commons.network.http; import cn.sinlmao.commons.network.bean.ImResponseCookie; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * <b>HTTP Response类</b> * <p> * 该类为HTTP请求响应(Response)数据封装,所有与Response相关的数据均在该类封装提供。 * <br/><br/> * <b>HTTP Response class</b> * <p> * This class is HTTP response (Response) data encapsulation, and all data related to Response is provided in this class package. * * @author Sinlmao * @program Sinlmao Commons Network Utils * @description HTTP Response类 * @create 2019-08-01 11:11 */ public final class ImResponse { private int responseCode; private String responseMessage; private String stringContent; private byte[] bytesContent; private Map<String, List<String>> headers = new HashMap<String, List<String>>(); private String cookieStr; private Map<String, String> cookies = new HashMap<String, String>(); private Map<String, ImResponseCookie> cookiePropertys = new HashMap<String, ImResponseCookie>(); /////////////////////////////////////////////////////////////////////// /** * [内部] 设置Response状态码 * <p> * <font color="#666666">[Internal] Set the Response status code</font> * * @param responseCode Response状态码 <br/> <font color="#666666">Response status code</font> * @return ImResponse ImResponse响应实体对象 <br/> <font color="#666666">ImResponse response entity object</font> */ protected ImResponse setResponseCode(int responseCode) { this.responseCode = responseCode; return this; } /** * [内部] 设置Response状态消息 * <p> * <font color="#666666">[Internal] Set the Response status message</font> * * @param responseMessage Response状态消息 <br/> <font color="#666666">Response status message</font> * @return ImResponse ImResponse响应实体对象 <br/> <font color="#666666">ImResponse response entity object</font> */ protected ImResponse setResponseMessage(String responseMessage) { this.responseMessage = responseMessage; return this; } /** * [内部] 设置Response应答String消息 * <p> * <font color="#666666">[Internal] Set Response Reply String Message</font> * * @param stringContent Response应答String消息 <br/> <font color="#666666">Response response String message</font> * @return ImResponse ImResponse响应实体对象 <br/> <font color="#666666">ImResponse response entity object</font> */ protected ImResponse setStringContent(String stringContent) { this.stringContent = stringContent; return this; } /** * [内部] 设置Response应答bytes消息 * <p> * <font color="#666666">[Internal] Set Response Reply bytes message</font> * * @param bytesContent Response应答bytes消息 <br/> <font color="#666666">Response response bytes message</font> * @return ImResponse ImResponse响应实体对象 <br/> <font color="#666666">ImResponse response entity object</font> */ protected ImResponse setBytesContent(byte[] bytesContent) { this.bytesContent = bytesContent; return this; } /** * [内部] 添加Cookie完整数据 * <p> * <font color="#666666">[Internal] Add full data for cookies</font> * * @param data Cookie完整数据 <br/> <font color="#666666">Cookie full data</font> * @return ImResponse ImResponse响应实体对象 <br/> <font color="#666666">ImResponse response entity object</font> */ protected ImResponse setFullCookie(String data) { cookieStr = data; return this; } /** * [内部] 添加Cookie数据 * <p> * <font color="#666666">[Internal] Add cookie data</font> * * @param name Cookie键 <br/> <font color="#666666">Cookie key</font> * @param data Cookie值 <br/> <font color="#666666">Cookie value</font> * @return ImResponse ImResponse响应实体对象 <br/> ImResponse response entity object</font> */ protected ImResponse addCookie(String name, String data) { cookies.put(name, data); return this; } /** * [内部] 添加Cookies属性数据 * <p> * <font color="#666666">[Internal] Add cookie property data</font> * * @param imResponseCookie Cookie键 <br/> <font color="#666666">Cookie property data</font> * @return ImResponse ImResponse响应实体对象 <br/> ImResponse response entity object</font> * @since 1.4.1 */ protected ImResponse addCookieProperty(ImResponseCookie imResponseCookie) { cookiePropertys.put(imResponseCookie.getName(), imResponseCookie); return this; } /** * [内部] 添加Header完整数据 * <p> * <font color="#666666">[Internal] Add Header full data</font> * * @param headers Header完整数据 <br/> <font color="#666666">Header full data</font> * @return ImResponse ImResponse响应实体对象 <br/> <font color="#666666">ImResponse response entity object</font> */ protected ImResponse setFullHeaders(Map<String, List<String>> headers) { this.headers = headers; return this; } /////////////////////////////////////////////////////////////////////// /** * 获得Response状态码 * <p> * <font color="#666666">Get the Response status code</font> * * @return Response状态码 <br/> <font color="#666666">Response status code</font> */ public int getResponseCode() { return responseCode; } /** * 获得Response状态消息 * <p> * <font color="#666666">Get the Response status message</font> * * @return Response状态消息 <br/> <font color="#666666">Response status message</font> */ public String getResponseMessage() { return responseMessage; } /** * 获得Response应答String消息 * <p> * <font color="#666666">Get the Response response String message</font> * * @return Response应答String消息 <br/> <font color="#666666">Response response String message</font> */ public String getStringContent() { return stringContent; } /** * 获得Response应答Bytes消息 * <p> * <font color="#666666">Get the Response response bytes message</font> * * @return Response应答bytes消息 <br/> <font color="#666666">Response response bytes message</font> */ public byte[] getBytesContent() { return bytesContent; } /** * 使用传入参数Response应答Bytes消息 * <p> * 必须确定传入的bytes数组参数是空的,否则会被覆盖 * <p> * <font color="#666666">Reply to Bytes message with incoming parameter Response</font> * <p> * <font color="#666666">Must determine that the incoming bytes array parameter is empty, otherwise it will be overwritten</font> * * @param bytesContent 空的Response应答Bytes接收对象 <br/> <font color="#666666">Empty Response Answers Bytes Receive Object</font> */ public void get(byte[] bytesContent) { // this.bytesContent = bytesContent; bytesContent = this.bytesContent; } /////////////////////////////////////////////////////////////////////// /** * 获得Cookie数据完整字符 * <p> * <font color="#666666">Get the full character of the cookie data</font> * * @return Cookie数据完整字符 <br/> <font color="#666666">Full character of the cookie data</font> */ public String getCookieStr() { return this.cookieStr; } /** * 根据Cookie键获取对象值 * <p> * <font color="#666666">Get the object value according to the Cookie key</font> * * @param name Cookie键 <br/> <font color="#666666">Cookie key</font> * @return Cookie值 <br/> <font color="#666666">Cookie value</font> */ public String getCookieData(String name) { return cookies.get(name); } /** * 根据Cookie键获取对象属性 * <p> * <font color="#666666">Get the object property according to the Cookie key</font> * * @param name Cookie键 <br/> <font color="#666666">Cookie key</font> * @return Cookie值 <br/> <font color="#666666">Cookie property</font> */ public ImResponseCookie getCookieProperty(String name) { return cookiePropertys.get(name); } /** * 获取Cookie的所有键 * <p> * <font color="#666666">Get all the keys of the cookie</font> * * @return Cookie的所有键 <br/> <font color="#666666">All the keys of the cookie</font> */ public Set<String> getCookieNames() { return cookies.keySet(); } /** * 获取Cookie长度 * <p> * <font color="#666666">Get the size of the cookie</font> * * @return Cookie长度 <br/> <font color="#666666">Cookie size</font> */ public int getCookieSize() { return cookies.size(); } /////////////////////////////////////////////////////////////////////// /** * 根据Header键获取对象值 * <p> * <font color="#666666">Get the object value according to the Header key</font> * * @param name Header键 <br/> <font color="#666666">Header key</font> * @return Header值 <br/> <font color="#666666">Header value</font> */ public List<String> getHeaderData(String name) { return headers.get(name); } /** * 获取Header的所有键 * <p> * <font color="#666666">Get all the keys of the header</font> * * @return Header的所有键 <br/> <font color="#666666">All the keys of the header</font> */ public Set<String> getHeaderNames() { return headers.keySet(); } /** * 获取Header长度 * <p> * <font color="#666666">Get the size of the header</font> * * @return Header长度 <br/> <font color="#666666">Header size</font> */ public int getHeaderSize() { return headers.size(); } /////////////////////////////////////////////////////////////////////// /** * 禁止外部实例化 */ protected ImResponse() { } }
31.910769
133
0.608717
12f5e5bd163535ac26f474e66b6722a11a6fb8c4
2,145
package th.watsize.imageviewer; import java.io.File; import th.watsize.filebrowser.FileUtils; import th.watsize.filebrowser.R; import android.app.Activity; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; public class ExpandImage extends Activity { private static final int TARGET_HEIGHT = 800; private static final int TARGET_WIDTH = 480; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.expandimage); TouchImageView tiv = (TouchImageView) findViewById(R.id.touchimageview); String file = this.getIntent().getStringExtra("fileURI"); Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file, options); if (options.outHeight != -1 && options.outWidth != -1) { FileUtils.printDebug("Image is valid - " + file.toString()); // Only scale if we need to Boolean scaleByHeight = !(Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH)); // Load, scaling to smallest power of 2 that'll get it <= // desired // dimensions double sampleSize = scaleByHeight ? options.outHeight / TARGET_HEIGHT : options.outWidth / TARGET_WIDTH; options.inSampleSize = (int) Math.pow(2d, Math.floor(Math .log(sampleSize) / Math.log(2d))); // Do the actual decoding options.inJustDecodeBounds = false; Bitmap img = BitmapFactory.decodeFile(file, options); if (img == null){ FileUtils.printDebug(" ExpandImage: img is null"); } tiv.setImage(img, tiv.getWidth(), tiv.getHeight()); tiv.setOnClickListener(new OnClickListener() { public void onClick(View v) { ExpandImage.this.finish(); } }); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); FileUtils.printDebug("onConfigurationChanged()"); } }
27.5
74
0.731002
42a96c3c85fc0c4c01fecf7c2ddf8e16821b3bcd
7,833
/*************************************************************************** * Copyright 2020 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.tools.trace.analysis; /** * Externalized Strings from {@link TraceAnalysisTool}. * * @author Robert von Massow, Andre van Hoorn * * @since 1.2 * @deprecated 1.15 replaced in new toot setup */ @Deprecated public final class StringConstants { /** Command for the input directories containing monitoring records. */ public static final String CMD_OPT_NAME_INPUTDIRS = "inputdirs"; /** Command for the output directories. */ public static final String CMD_OPT_NAME_OUTPUTDIR = "outputdir"; public static final String CMD_OPT_NAME_OUTPUTFNPREFIX = "output-filename-prefix"; public static final String CMD_OPT_NAME_SELECTTRACES = "select-traces"; public static final String CMD_OPT_NAME_FILTERTRACES = "filter-traces"; /** Command whether to use short labels or not. */ public static final String CMD_OPT_NAME_SHORTLABELS = "short-labels"; public static final String CMD_OPT_NAME_IGNORE_ASSUMED = "ignore-assumed-calls"; /** Command whether to include self loops or not. */ public static final String CMD_OPT_NAME_INCLUDESELFLOOPS = "include-self-loops"; /** Command whether to ignore invalid traces or not. */ public static final String CMD_OPT_NAME_IGNOREINVALIDTRACES = "ignore-invalid-traces"; /** Command whether to repair traces with missing AfterEvents (e.g. because of software crash) or not. */ public static final String CMD_OPT_NAME_REPAIR_EVENT_BASED_TRACES = "repair-event-based-traces"; /** Command whether to plot deployment sequence diagrams or not. */ public static final String CMD_OPT_NAME_TASK_PLOTALLOCATIONSEQDS = "plot-Deployment-Sequence-Diagrams"; /** Command whether to plot assembly sequence diagrams or not. */ public static final String CMD_OPT_NAME_TASK_PLOTASSEMBLYSEQDS = "plot-Assembly-Sequence-Diagrams"; /** Command whether to plot deployment component dependency graphs or not. */ public static final String CMD_OPT_NAME_TASK_PLOTALLOCATIONCOMPONENTDEPG = "plot-Deployment-Component-Dependency-Graph"; /** Command whether to plot assembly component dependency graphs or not. */ public static final String CMD_OPT_NAME_TASK_PLOTASSEMBLYCOMPONENTDEPG = "plot-Assembly-Component-Dependency-Graph"; /** Command whether to plot container dependency graphs or not. */ public static final String CMD_OPT_NAME_TASK_PLOTCONTAINERDEPG = "plot-Container-Dependency-Graph"; /** Command whether to plot deployment operation dependency graphs or not. */ public static final String CMD_OPT_NAME_TASK_PLOTALLOCATIONOPERATIONDEPG = "plot-Deployment-Operation-Dependency-Graph"; /** Command whether to plot assembly operation dependency graphs or not. */ public static final String CMD_OPT_NAME_TASK_PLOTASSEMBLYOPERATIONDEPG = "plot-Assembly-Operation-Dependency-Graph"; /** Command whether to plot aggregated deployment call trees or not. */ public static final String CMD_OPT_NAME_TASK_PLOTAGGREGATEDALLOCATIONCALLTREE = "plot-Aggregated-Deployment-Call-Tree"; /** Command whether to plot aggregated assembly call trees or not. */ public static final String CMD_OPT_NAME_TASK_PLOTAGGREGATEDASSEMBLYCALLTREE = "plot-Aggregated-Assembly-Call-Tree"; /** Command whether to plot call trees or not. */ public static final String CMD_OPT_NAME_TASK_PLOTCALLTREES = "plot-Call-Trees"; /** Command whether to print message traces or not. */ public static final String CMD_OPT_NAME_TASK_PRINTMSGTRACES = "print-Message-Traces"; /** Command whether to print execution traces or not. */ public static final String CMD_OPT_NAME_TASK_PRINTEXECTRACES = "print-Execution-Traces"; /** Command whether to print the system model or not. */ public static final String CMD_OPT_NAME_TASK_PRINTSYSTEMMODEL = "print-System-Model"; /** Command whether to print invalid execution traces or not. */ public static final String CMD_OPT_NAME_TASK_PRINTINVALIDEXECTRACES = "print-invalid-Execution-Traces"; public static final String CMD_OPT_NAME_TASK_ALLOCATIONEQUIVCLASSREPORT = "print-Deployment-Equivalence-Classes"; public static final String CMD_OPT_NAME_TASK_ASSEMBLYEQUIVCLASSREPORT = "print-Assembly-Equivalence-Classes"; public static final String CMD_OPT_NAME_MAXTRACEDURATION = "max-trace-duration"; public static final String CMD_OPT_NAME_IGNOREEXECUTIONSBEFOREDATE = "ignore-executions-before-date"; public static final String CMD_OPT_NAME_IGNOREEXECUTIONSAFTERDATE = "ignore-executions-after-date"; /** The prefix for the call tree files. */ public static final String CALL_TREE_FN_PREFIX = "callTree"; /** The name prefix for the message traces files. */ public static final String MESSAGE_TRACES_FN_PREFIX = "messageTraces"; /** The name prefix for the execution traces files. */ public static final String EXECUTION_TRACES_FN_PREFIX = "executionTraces"; /** The name prefix for the invalid traces files. */ public static final String INVALID_TRACES_FN_PREFIX = "invalidTraceArtifacts"; public static final String TRACE_ALLOCATION_EQUIV_CLASSES_FN_PREFIX = "traceDeploymentEquivClasses"; public static final String TRACE_ASSEMBLY_EQUIV_CLASSES_FN_PREFIX = "traceAssemblyEquivClasses"; /** The name of the component for the execution trace reconstruction. */ public static final String EXEC_TRACE_RECONSTR_COMPONENT_NAME = "Execution record transformation"; /** The name of the component for the trace reconstruction of execution records. */ public static final String TRACERECONSTR_COMPONENT_NAME = "Trace reconstruction (execution records -> execution traces)"; /** The name of the component for the trace equivalence class filtering (deployment mode). */ public static final String TRACEALLOCATIONEQUIVCLASS_COMPONENT_NAME = "Trace equivalence class filter (deployment mode)"; /** The name of the component for the trace equivalence class filtering (assembly mode). */ public static final String TRACEASSEMBLYEQUIVCLASS_COMPONENT_NAME = "Trace equivalence class filter (assembly mode)"; /** The name of the component for the trace reconstruction of trace event records. */ public static final String EVENTRECORDTRACERECONSTR_COMPONENT_NAME = "Trace reconstruction (trace event records -> event record traces)"; /** The name of the component for the trace reconstruction of event record traces. */ public static final String EXECTRACESFROMEVENTTRACES_COMPONENT_NAME = "Trace reconstruction (event record traces -> execution traces)"; public static final String DECORATORS_OPTION_NAME = "responseTimes-ns | responseTimes-us | responseTimes-ms | responseTimes-s> " + "<responseTimeColoring threshold(ms)"; public static final char DECORATOR_SEPARATOR = ','; public static final String RESPONSE_TIME_COLORING_DECORATOR_FLAG = "responseTimeColoring"; public static final String CMD_OPT_NAME_TRACE_COLORING = "traceColoring"; public static final String COLORING_FILE_OPTION_NAME = "color map file"; public static final String CMD_OPT_NAME_ADD_DESCRIPTIONS = "addDescriptions"; public static final String DESCRIPTIONS_FILE_OPTION_NAME = "descriptions file"; /** * Private constructor to avoid instantiation. */ private StringConstants() {} }
65.275
138
0.781182
bd1ead81bec16d30508dd7dbd5b8c7b07502cad2
3,543
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8201793 * @summary Test Reference::clone to throw CloneNotSupportedException */ import java.lang.ref.*; public class ReferenceClone { private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue<>(); public static void main(String... args) { ReferenceClone refClone = new ReferenceClone(); refClone.test(); } public void test() { // test Reference::clone that throws CNSE Object o = new Object(); assertCloneNotSupported(new SoftRef(o)); assertCloneNotSupported(new WeakRef(o)); assertCloneNotSupported(new PhantomRef(o)); // Reference subclass may override the clone method CloneableReference ref = new CloneableReference(o); try { ref.clone(); } catch (CloneNotSupportedException e) {} } private void assertCloneNotSupported(CloneableRef ref) { try { ref.clone(); throw new RuntimeException("Reference::clone should throw CloneNotSupportedException"); } catch (CloneNotSupportedException e) {} } // override clone to be public that throws CNSE interface CloneableRef extends Cloneable { public Object clone() throws CloneNotSupportedException; } class SoftRef extends SoftReference<Object> implements CloneableRef { public SoftRef(Object referent) { super(referent, QUEUE); } public Object clone() throws CloneNotSupportedException { return super.clone(); } } class WeakRef extends WeakReference<Object> implements CloneableRef { public WeakRef(Object referent) { super(referent, QUEUE); } public Object clone() throws CloneNotSupportedException { return super.clone(); } } class PhantomRef extends PhantomReference<Object> implements CloneableRef { public PhantomRef(Object referent) { super(referent, QUEUE); } public Object clone() throws CloneNotSupportedException { return super.clone(); } } // override clone to return a new instance class CloneableReference extends WeakReference<Object> implements Cloneable { public CloneableReference(Object referent) { super(referent, QUEUE); } public Object clone() throws CloneNotSupportedException { return new CloneableReference(this.get()); } } }
33.742857
99
0.673441
af9a6a647569f616ff154426914a54cefa2aa4ba
2,929
/* * Copyright (C) 2014 Carlos González. * All rights reserved. * * The software in this package is published under the terms of the MIT * license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on Jul 17, 2014 by Carlos González */ package com.github.chuckbuckethead.cypher.keys; import java.io.UnsupportedEncodingException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import com.thoughtworks.xstream.core.util.Base64Encoder; /** * Abstract implementation of the CryptoKey interface. This class defines * the generic behavior of a cryptography key. * * @author Carlos González */ public abstract class AbstractCryptoKey implements CryptoKey { private Base64Encoder encoder; /** * */ protected AbstractCryptoKey() { } /* (non-Javadoc) * @see com.github.chuckbuckethead.cypher.keys.CryptoKey#encrypt(java.lang.String) */ public String encrypt(String str) { String encryptedStr = null; try { byte[] utf8 = str.getBytes("UTF-8"); encryptedStr = encryptBytes(utf8); } catch(UnsupportedEncodingException e) { /* ignore */ } return encryptedStr; } /* (non-Javadoc) * @see com.github.chuckbuckethead.cypher.keys.CryptoKey#encryptBytes(byte[]) */ public synchronized String encryptBytes(byte[] bytes) { String encryptedStr = null; try { //Encrypt byte[] enc = getEncryptCipher().doFinal(bytes); //Encode bytes to base64 to get a string encryptedStr = getEncoder().encode(enc); } catch(BadPaddingException e) { /* ignore */ } catch(IllegalBlockSizeException e) { /* ignore */ } return encryptedStr; } /* (non-Javadoc) * @see com.github.chuckbuckethead.cypher.keys.CryptoKey#decrypt(java.lang.String) */ public String decrypt(String base64Str) { String decryptedStr = null; try { byte[] dec = decryptBytes(base64Str); if(dec != null) { //Decode using UTF-8 decryptedStr = new String(dec, "UTF-8"); } } catch(UnsupportedEncodingException e) {} return decryptedStr; } /* (non-Javadoc) * @see com.github.chuckbuckethead.cypher.keys.CryptoKey#decryptBytes(java.lang.String) */ public synchronized byte[] decryptBytes(String base64Str) { byte[] bytes = null; try { byte[] dec = getEncoder().decode(base64Str); //Decrypt bytes = getDecryptCipher().doFinal(dec); } catch (IllegalBlockSizeException e) {} catch (BadPaddingException e) { } return bytes; } protected Base64Encoder getEncoder() { if(encoder == null) { encoder = new Base64Encoder(); } return encoder; } /** * Return the <code>Cipher</code> to use to encrypt data. */ protected abstract Cipher getEncryptCipher(); /** * Return the <code>Cipher</code> to use to decrypt data. */ protected abstract Cipher getDecryptCipher(); }
22.358779
88
0.692386
e992a1f1d9476261e3e607e8ba4eb2ea1370f96a
1,886
package com.web.produce.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.hibernate.annotations.DynamicUpdate; import com.app.base.entity.BaseEntity; import io.swagger.annotations.ApiModelProperty; /** * 补卡处理 */ @Entity(name = "ClassType") @Table(name= ClassType.TABLE_NAME) @DynamicUpdate public class ClassType extends BaseEntity{ private static final long serialVersionUID = -5951531333314901264L; public static final String TABLE_NAME = "MES_BASE_CLASS_TYPE"; /** * 班次编码 */ @ApiModelProperty(name="classNo",value="班次编码") @Column(length = 20) protected String classNo; /** * 班次名称 */ @ApiModelProperty(name="className",value="班次名称") @Column(length = 20) protected String className; /** * 上班时间 */ @ApiModelProperty(name="fcard1",value="上班时间") @Column(length = 10) protected String fcard1; /** * 下班时间 */ @ApiModelProperty(name="fcard2",value="下班时间") @Column(length = 10) protected String fcard2; public String getClassNo() { return classNo; } public void setClassNo(String classNo) { this.classNo = classNo; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getFcard1() { return fcard1; } public void setFcard1(String fcard1) { this.fcard1 = fcard1; } public String getFcard2() { return fcard2; } public void setFcard2(String fcard2) { this.fcard2 = fcard2; } @Override public String toString() { final StringBuffer sb = new StringBuffer(); sb.append("班次编码:").append(this.classNo); sb.append(",班次名称:").append(this.className); sb.append(",上班时间:").append(this.fcard1); sb.append(",下班时间:").append(this.fcard2); return sb.toString(); } }
20.06383
68
0.677625
fe5b21bca2c9f2a27f771bafae5d4cc8df4a940c
5,113
/** * Original iOS version by Jens Alfke, ported to Android by Marty Schoch * Copyright (c) 2012 Couchbase, Inc. All rights reserved. * * Modifications for this distribution by Cloudant, Inc., Copyright (c) 2013 Cloudant, 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.cloudant.sync.datastore; import com.cloudant.sync.util.Misc; import java.util.HashSet; import java.util.Set; class DatastoreConstants { public static final Set<String> KNOWN_SPECIAL_KEYS; static { KNOWN_SPECIAL_KEYS = new HashSet<String>(); KNOWN_SPECIAL_KEYS.add("_id"); KNOWN_SPECIAL_KEYS.add("_rev"); KNOWN_SPECIAL_KEYS.add("_attachments"); KNOWN_SPECIAL_KEYS.add("_deleted"); KNOWN_SPECIAL_KEYS.add("_revisions"); KNOWN_SPECIAL_KEYS.add("_revs_info"); KNOWN_SPECIAL_KEYS.add("_conflicts"); KNOWN_SPECIAL_KEYS.add("_deleted_conflicts"); } // First-time initialization: // (Note: Declaring revs.sequence as AUTOINCREMENT means the values will always be // monotonically increasing, never reused. See <http://www.sqlite4java.org/autoinc.html>) public static final String[] SCHEMA_VERSION_3 = { " CREATE TABLE docs ( " + " doc_id INTEGER PRIMARY KEY, " + " docid TEXT UNIQUE NOT NULL); ", " CREATE INDEX docs_docid ON docs(docid); ", " CREATE TABLE revs ( " + " sequence INTEGER PRIMARY KEY AUTOINCREMENT, " + " doc_id INTEGER NOT NULL REFERENCES docs(doc_id) ON DELETE CASCADE, " + " parent INTEGER REFERENCES revs(sequence) ON DELETE SET NULL, " + " current BOOLEAN, " + " deleted BOOLEAN DEFAULT 0, " + " available BOOLEAN DEFAULT 1, " + " revid TEXT NOT NULL, " + " json BLOB); ", " CREATE INDEX revs_by_id ON revs(revid, doc_id); ", " CREATE INDEX revs_current ON revs(doc_id, current); ", " CREATE INDEX revs_parent ON revs(parent); ", " CREATE TABLE localdocs ( " + " docid TEXT UNIQUE NOT NULL, " + " revid TEXT NOT NULL, " + " json BLOB); ", " CREATE INDEX localdocs_by_docid ON localdocs(docid); ", " CREATE TABLE views ( " + " view_id INTEGER PRIMARY KEY, " + " name TEXT UNIQUE NOT NULL," + " version TEXT, " + " lastsequence INTEGER DEFAULT 0); ", " CREATE INDEX views_by_name ON views(name); ", " CREATE TABLE maps ( " + " view_id INTEGER NOT NULL REFERENCES views(view_id) ON DELETE CASCADE, " + " sequence INTEGER NOT NULL REFERENCES revs(sequence) ON DELETE CASCADE, " + " key TEXT NOT NULL, " + " collation_key BLOB NOT NULL, " + " value TEXT); ", " CREATE INDEX maps_keys on maps(view_id, collation_key); ", " CREATE TABLE attachments ( " + " sequence INTEGER NOT NULL REFERENCES revs(sequence) ON DELETE CASCADE, " + " filename TEXT NOT NULL, " + " key BLOB NOT NULL, " + " type TEXT, " + " length INTEGER NOT NULL, " + " revpos INTEGER DEFAULT 0); ", " CREATE INDEX attachments_by_sequence on attachments(sequence, filename); ", " CREATE TABLE replicators ( " + " remote TEXT NOT NULL, " + " startPush BOOLEAN, " + " last_sequence TEXT, " + " UNIQUE (remote, startPush)); " }; private static final String[] SCHEMA_VERSION_4 = { "CREATE TABLE info ( " + " key TEXT PRIMARY KEY, " + " value TEXT); ", "INSERT INTO INFO (key, value) VALUES ('privateUUID', '%s'); ", "INSERT INTO INFO (key, value) VALUES ('publicUUID', '%s'); " }; /** * Returns SCHEMA_VERSION_4 with new UUIDs * * @return SCHEMA_VERSION_4 with new UUIDs */ public static String[] getSCHEMA_VERSION_4() { String[] result = new String[SCHEMA_VERSION_4.length]; result[0] = SCHEMA_VERSION_4[0]; result[1] = String.format(SCHEMA_VERSION_4[1], Misc.createUUID()) ; result[2] = String.format(SCHEMA_VERSION_4[2], Misc.createUUID()) ; return result; } }
45.247788
95
0.569724
2b304f9740a04c9e8e516a2f693dfbcd0f7cff3d
2,877
package io.lacuna.bifurcan; import io.lacuna.bifurcan.durable.Bytes; import io.lacuna.bifurcan.durable.codecs.Core; import java.nio.ByteBuffer; import java.nio.file.Path; import java.util.function.Function; import static io.lacuna.bifurcan.durable.codecs.Core.decodeCollection; public interface IDurableCollection { interface Fingerprint extends Comparable<Fingerprint> { String ALGORITHM = "SHA-512"; int HASH_BYTES = 32; byte[] binary(); default String toHexString() { return Bytes.toHexString(ByteBuffer.wrap(binary())); } default int compareTo(Fingerprint o) { return Bytes.compareBuffers( ByteBuffer.wrap(binary()), ByteBuffer.wrap(o.binary()) ); } } /** * */ interface Root { void close(); Path path(); DurableInput.Pool bytes(); Fingerprint fingerprint(); DurableInput cached(DurableInput in); IMap<Fingerprint, Fingerprint> redirects(); ISet<Fingerprint> dependencies(); default DirectedAcyclicGraph<Fingerprint, Void> dependencyGraph() { Function<Root, Iterable<Root>> deps = r -> () -> r.dependencies().stream().map(r::open).iterator(); DirectedAcyclicGraph<Fingerprint, Void> result = new DirectedAcyclicGraph<Fingerprint, Void>().linear(); for (Root r : Graphs.bfsVertices(this, deps)) { deps.apply(r).forEach(d -> result.link(r.fingerprint(), d.fingerprint())); } return result.forked(); } Root open(Fingerprint dependency); default <T extends IDurableCollection> T decode(IDurableEncoding encoding) { return (T) decodeCollection(encoding, this, bytes()); } } IDurableEncoding encoding(); DurableInput.Pool bytes(); Root root(); interface Rebase { IDurableEncoding encoding(); Fingerprint original(); Fingerprint updated(); ISortedMap<Long, Long> updatedIndices(); Root root(); <T extends IDurableCollection> T apply(T collection); } default Rebase compact(ISet<Fingerprint> compactSet) { Fingerprint fingerprint = root().fingerprint(); DirectedAcyclicGraph<Fingerprint, Void> compactGraph = root().dependencyGraph().select(compactSet); ISet<Fingerprint> unexpectedRoots = compactGraph.top().remove(fingerprint); if (unexpectedRoots.size() > 0) { throw new IllegalArgumentException("unexpected roots in `compactSet`: " + unexpectedRoots); } ISet<Fingerprint> reachable = Set.from(Graphs.bfsVertices(fingerprint, compactGraph::out)); if (reachable.size() < compactSet.size()) { throw new IllegalArgumentException("disconnected elements in `compactSet`: " + compactSet.difference(reachable)); } if (compactSet.size() < 2) { throw new IllegalArgumentException("there must be at least two elements in `compactSet`"); } return Core.compact(compactSet, this); } }
26.88785
119
0.688564
0b4c7c66100f059bca1b4f109c9515237c57947e
2,414
package org.springframework.beans.factory.config; import java.util.LinkedHashSet; import java.util.Set; import org.springframework.beans.BeanUtils; import org.springframework.beans.TypeConverter; import org.springframework.core.ResolvableType; import org.springframework.lang.Nullable; /** * Simple factory for shared Set instances. Allows for central setup * of Sets via the "set" element in XML bean definitions. * @since 09.12.2003 * @see ListFactoryBean * @see MapFactoryBean */ public class SetFactoryBean extends AbstractFactoryBean<Set<Object>> { @Nullable private Set<?> sourceSet; @SuppressWarnings("rawtypes") @Nullable private Class<? extends Set> targetSetClass; /** * Set the source Set, typically populated via XML "set" elements. */ public void setSourceSet(Set<?> sourceSet) { this.sourceSet = sourceSet; } /** * Set the class to use for the target Set. Can be populated with a fully * qualified class name when defined in a Spring application context. * Default is a linked HashSet, keeping the registration order. * @see java.util.LinkedHashSet */ @SuppressWarnings("rawtypes") public void setTargetSetClass(@Nullable Class<? extends Set> targetSetClass) { if (targetSetClass == null) { throw new IllegalArgumentException("'targetSetClass' must not be null"); } if (!Set.class.isAssignableFrom(targetSetClass)) { throw new IllegalArgumentException("'targetSetClass' must implement [java.util.Set]"); } this.targetSetClass = targetSetClass; } @Override @SuppressWarnings("rawtypes") public Class<Set> getObjectType() { return Set.class; } @Override @SuppressWarnings("unchecked") protected Set<Object> createInstance() { if (this.sourceSet == null) throw new IllegalArgumentException("'sourceSet' is required"); Set<Object> result; if (this.targetSetClass != null) { result = BeanUtils.instantiateClass(this.targetSetClass); }else { result = new LinkedHashSet<>(this.sourceSet.size()); } Class<?> valueType = null; if (this.targetSetClass != null) { valueType = ResolvableType.forClass(this.targetSetClass).asCollection().resolveGeneric(); } if (valueType != null) { TypeConverter converter = getBeanTypeConverter(); for (Object elem : this.sourceSet) { result.add(converter.convertIfNecessary(elem, valueType)); } }else { result.addAll(this.sourceSet); } return result; } }
28.069767
92
0.73488
e71e9b793cfa3a308339b4f9e22a3540bc09f3e3
2,104
package com.lindronics.flirapp.activities; import android.os.Bundle; import android.view.View; import android.widget.ToggleButton; import com.lindronics.flirapp.R; import com.lindronics.flirapp.camera.FrameDataHolder; import com.lindronics.flirapp.camera.ImageWriter; public class CameraActivity extends AbstractCameraActivity { private static final String TAG = "CameraActivity"; private ToggleButton cameraButton; private ImageWriter imageWriter = null; /** * Executed when activity is created. * Get camera identity from intent and connect to camera. */ @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_camera); super.onCreate(savedInstanceState); cameraButton = findViewById(R.id.camera_button); } @Override public void receiveImages(FrameDataHolder images) { super.receiveImages(images); runInBackground(() -> { if (imageWriter != null) { imageWriter.saveImages(images); } }); } /** * Event listener for starting or stopping camera capture/recording * * @param view Toggle button */ public void toggleCapture(View view) { ToggleButton button = (ToggleButton) view; if (button.isChecked()) { startCapture(); } else { endCapture(); } } /** * Start capturing/recording data */ private void startCapture() { cameraButton.setBackground(getDrawable(R.drawable.ic_camera_capture_recording)); imageWriter = new ImageWriter(this); } /** * Finish capturing/recording data */ private void endCapture() { cameraButton.setBackground(getDrawable(R.drawable.ic_camera_capture_ready)); imageWriter = null; } /** * End capture when disconnected */ @Override void onDisconnected() { endCapture(); } @Override public void toggleTransformation(View view) { super.toggleTransformation(view); } }
24.465116
88
0.646388
88475ca3dc163a18cdbb542e282971cb20e4003f
1,558
/* * Copyright (C) 2019 xuexiangjys([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.libenli.easygym; import android.app.Application; import android.content.Context; import androidx.multidex.MultiDex; import com.libenli.easygym.utils.sdkinit.UMengInit; import com.libenli.easygym.utils.sdkinit.XBasicLibInit; /** * @author xuexiang * @since 2018/11/7 下午1:12 */ public class MyApp extends Application { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); //解决4.x运行崩溃的问题 MultiDex.install(this); } @Override public void onCreate() { super.onCreate(); initLibs(); } /** * 初始化基础库 */ private void initLibs() { XBasicLibInit.init(this); //运营统计数据运行时不初始化 if (!MyApp.isDebug()) { UMengInit.init(this); } } /** * @return 当前app是否是调试开发模式 */ public static boolean isDebug() { return BuildConfig.DEBUG; } }
22.57971
75
0.66303
bb06713b17cdc7fb42907dacf6ad81d7623bc835
1,787
// Copyright 2020 The KeepTry Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package greedy; import java.util.Arrays; /** * <pre> * You have an initial power P, an initial score of 0 points, and a bag of tokens. * * Each token can be used at most once, has a value token[i], and has potentially two ways to use it. * * If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point. * If we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point. * Return the largest number of points we can have after playing any number of tokens. */ public class Leetcode948BagofTokens { /** why it is greedy. Buy at the cheapest and sell at the most expensive. */ public int bagOfTokensScore(int[] tokens, int P) { if (tokens == null || tokens.length == 0) { return 0; } int res = 0, s = 0, l = 0, r = tokens.length - 1; Arrays.sort(tokens); // need not reassign while (l <= r) { while (l <= r && P >= tokens[l]) { // check l<=r firstly P -= tokens[l++]; s++; res = Math.max(res, s); // ever max } if (s == 0 || l > r) break; P += tokens[r--]; s--; } return res; } }
34.365385
113
0.650811
165a5c47cbbbc9c3d498467091d15c5613abe33e
3,121
/* * Solo - A small and beautiful blogging system written in Java. * Copyright (c) 2010-2018, b3log.org & hacpai.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.b3log.solo.service; import org.b3log.latke.ioc.Inject; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.repository.RepositoryException; import org.b3log.latke.service.ServiceException; import org.b3log.latke.service.annotation.Service; import org.b3log.solo.model.Option; import org.b3log.solo.repository.OptionRepository; import org.json.JSONObject; /** * Preference query service. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.1.0.4, Sep 17, 2018 * @since 0.4.0 */ @Service public class PreferenceQueryService { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(PreferenceQueryService.class); /** * Option repository. */ @Inject private OptionRepository optionRepository; /** * Optiona query service. */ @Inject private OptionQueryService optionQueryService; /** * Gets the reply notification template. * * @return reply notification template, returns {@code null} if not found * @throws ServiceException service exception */ public JSONObject getReplyNotificationTemplate() throws ServiceException { try { final JSONObject ret = new JSONObject(); final JSONObject preference = getPreference(); ret.put("subject", preference.optString(Option.ID_C_REPLY_NOTI_TPL_SUBJECT)); ret.put("body", preference.optString(Option.ID_C_REPLY_NOTI_TPL_BODY)); return ret; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Updates reply notification template failed", e); throw new ServiceException(e); } } /** * Gets the user preference. * * @return user preference, returns {@code null} if not found * @throws ServiceException if repository exception */ public JSONObject getPreference() throws ServiceException { try { final JSONObject checkInit = optionRepository.get(Option.ID_C_ADMIN_EMAIL); if (null == checkInit) { return null; } return optionQueryService.getOptions(Option.CATEGORY_C_PREFERENCE); } catch (final RepositoryException e) { return null; } } }
32.175258
89
0.680551
22fc8a65ffe33e26f9a0d768cdf6cabcc7c33681
1,276
package speedith.core.lang.cop; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; import org.junit.Test; import speedith.core.lang.cop.Arrow; import speedith.core.lang.cop.Cardinality; import speedith.core.lang.cop.Comparator; public class ArrowTest { private Arrow one = new Arrow("A","B","solid"); private Arrow two = new Arrow("A","B","dashed"); private Arrow three = new Arrow("C","D","dashed"); private Arrow four = new Arrow("C","D","dashed"); @Test public void testSameSource() { assertTrue(Arrow.sameSource(one,two)); assertFalse(Arrow.sameSource(one,three)); } @Test public void testSameArrow() { assertTrue(Arrow.sameArrow(three,four)); assertFalse(Arrow.sameArrow(two,four)); } @Test public void testCompareTo() { int v1 = three.compareTo(four); int v2 = one.compareTo(two); assertEquals(v1,0); assertNotEquals(v2,0); } @Test public void testEqualsObject() { assertTrue(three.equals(four)); assertFalse(two.equals(four)); } @Test public void testCardinality() { //Cardinality cardinality = new Cardinality("=","1"); Cardinality cardinality = new Cardinality(Comparator.Eq, 1); one.setCardinality(cardinality); assertEquals(one.getCardinality(),cardinality); } }
20.253968
62
0.709248
63f9755c63d0c1a483c60d52b4c2c05af6eae832
671
package fun.gengzi.codecopy.business.redis.controller.skiplistnew; import org.junit.Test; public class SkipListTest { @Test public void fun01(){ SkipList<Integer> integerSkipList = new SkipList<>(); // head <-------> tail integerSkipList.put(1,1); integerSkipList.put(2,2); integerSkipList.put(6,6); integerSkipList.put(3,3); integerSkipList.put(4,4); integerSkipList.put(5,5); String string = integerSkipList.toString(); System.out.println(string); SkipListNode<Integer> search = integerSkipList.search(4); System.out.println(search.getValue()); } }
20.96875
66
0.627422
ac629ec0b10e5a52a9fcf14c523a86c63d32944e
308
package com.beibeiMajor.web.mapper.po; import lombok.Data; import java.io.Serializable; /** * @author lenovo */ @Data public class DoubleAccountPo implements Serializable { private static final long serialVersionUID = -63024680546901733L; private Long matchId; private String accountIds; }
18.117647
69
0.756494
d659b57fd95a929c519a4603a204f91619f3c138
3,686
/* * $Id$ * * Copyright (C) 2003-2013 JNode.org * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; If not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jnode.partitions.apm; import org.jnode.partitions.PartitionTableEntry; import org.jnode.partitions.ibm.IBMPartitionTable; import org.jnode.util.BigEndian; import org.jnode.util.NumberUtils; import java.nio.charset.Charset; /** * A APM partition table entry. * * @author Luke Quinane */ public class ApmPartitionTableEntry implements PartitionTableEntry { /** * The first 16KiB of the drive. */ private final byte[] first16KiB; /** * The offset to this partition table entry. */ private final int offset; /** * Creates a new entry. * * @param parent the parent table. * @param first16KiB the first 16,384 bytes of the disk. * @param offset the offset of this entry in the table. */ public ApmPartitionTableEntry(ApmPartitionTable parent, byte[] first16KiB, int offset) { this.first16KiB = first16KiB; this.offset = offset; } @Override public boolean isValid() { return first16KiB.length > offset + 128; } /** * @see org.jnode.partitions.PartitionTableEntry#getChildPartitionTable() */ @Override public IBMPartitionTable getChildPartitionTable() { throw new UnsupportedOperationException("No child partitions."); } /** * @see org.jnode.partitions.PartitionTableEntry#hasChildPartitionTable() */ @Override public boolean hasChildPartitionTable() { return false; } public long getStartOffset() { return BigEndian.getUInt32(first16KiB, offset + 0x8) * 0x200L; } public long getEndOffset() { return getStartOffset() + BigEndian.getUInt32(first16KiB, offset + 0xc) * 0x200L; } public String getName() { byte[] nameBytes = new byte[31]; System.arraycopy(first16KiB, offset + 0x10, nameBytes, 0, nameBytes.length); return new String(nameBytes, Charset.forName("ASCII")).replace("\u0000", ""); } public String getType() { byte[] nameBytes = new byte[31]; System.arraycopy(first16KiB, offset + 0x30, nameBytes, 0, nameBytes.length); return new String(nameBytes, Charset.forName("ASCII")).replace("\u0000", ""); } public String dump() { StringBuilder b = new StringBuilder(); for (int i = 0; i < 128; i++) { b.append(NumberUtils.hex(BigEndian.getUInt8(first16KiB, offset + i), 2)); b.append(' '); } return b.toString(); } @Override public String toString() { StringBuilder builder = new StringBuilder(32); builder.append('[').append(getName()).append(' '); builder.append("t:").append(getType()).append(' '); builder.append("s:").append(getStartOffset()).append(' '); builder.append("e:").append(getEndOffset()).append(']'); return builder.toString(); } }
30.97479
92
0.654639
65c9a7f8554e4171ce6ed0e59807ca9c39518c18
1,653
package pl.oaza.warszawa.dor.rekolekcje.api.security.users; import java.sql.Date; import java.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/users") class UserRegistrationEndpoint { private static final Logger LOGGER = LoggerFactory.getLogger(UserRegistrationEndpoint.class); private UserRepository userRepository; private PasswordEncoder passwordEncoder; public UserRegistrationEndpoint(UserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } @PostMapping("/sign-up") public String signUp(@RequestBody User user) { if (userRepository.findByUsername(user.getUsername()) != null) { return "User already exists with this username: " + user.getUsername(); } //TODO: create real user instead of a mock one user.setPassword(passwordEncoder.encode(user.getPassword())); user.setEmail("email"); user.setFirstname("first name"); user.setLastname("last name"); user.setEnabled(true); user.setLastPasswordResetDate(Date.valueOf(LocalDate.now().minusDays(1))); userRepository.save(user); LOGGER.info("Sign up successful for {}", user); return "Sign up successful. " + user; } }
37.568182
95
0.757411