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
e46ea8fa075d766f535b450058e897ca9d654061
767
package com.achilles.model; public class MatchRegistrationAdversary { private int id; private int playerId; private int roundId; private int adversaryId; private String platId; public String getPlatId() { return platId; } public void setPlatId(String platId) { this.platId = platId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPlayerId() { return playerId; } public void setPlayerId(int playerId) { this.playerId = playerId; } public int getRoundId() { return roundId; } public void setRoundId(int roundId) { this.roundId = roundId; } public int getAdversaryId() { return adversaryId; } public void setAdversaryId(int adversaryId) { this.adversaryId = adversaryId; } }
18.707317
46
0.713168
2a8e4613ef6e9f0a6d9c5f1442dbb6012ac02627
1,368
package com.jraph.svg; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.jraph.svg.utils.Vector2; public class Svg extends Element { private Vector2<Integer> dimension; private List<Element> elements; public Svg(Vector2<Integer> theSize) { super("svg"); dimension = new Vector2<>(theSize); elements = new ArrayList<>(); } public void addElement(Element theElement) { elements.add(theElement); } public void addAllElements(List<Element> list) { elements.addAll(list); } @Override protected void initParameters() { addParameter(new Parameter<String>(Attribute.XMLNS, "http://www.w3.org/2000/svg")); addParameter(new Parameter<Integer>(Attribute.WIDTH, dimension.getX())); addParameter(new Parameter<Integer>(Attribute.HEIGHT, dimension.getY())); StringBuilder aBuilder = new StringBuilder(); for (Element anElement : elements) { aBuilder.append(anElement.toSvg()).append("\n"); } setContent(aBuilder.toString()); } public void save(String theFileName) { File aFile = new File(theFileName); try { FileWriter aFileWriter = new FileWriter(aFile); aFileWriter.append(toSvg()); aFileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
25.811321
86
0.689327
b09e13d62d9aca8e1431115f865a8dbf8911d5d1
5,017
package org.sheepy.lily.vulkan.process.graphic.pipeline; import org.joml.Vector2ic; import org.lwjgl.vulkan.VkGraphicsPipelineCreateInfo; import org.sheepy.lily.vulkan.core.pipeline.VkPipeline; import org.sheepy.lily.vulkan.core.pipeline.VkPipelineLayout; import org.sheepy.lily.vulkan.core.pipeline.VkShaderStage; import org.sheepy.lily.vulkan.core.util.Logger; import org.sheepy.lily.vulkan.process.graphic.pipeline.builder.*; import org.sheepy.lily.vulkan.process.graphic.renderpass.RenderPassAllocation; import org.sheepy.lily.vulkan.process.pipeline.builder.ShaderStageBuilder; import org.sheepy.lily.vulkan.process.process.ProcessContext; import org.sheepy.vulkan.model.graphicpipeline.*; import java.nio.ByteBuffer; import java.util.List; import static org.lwjgl.vulkan.VK10.*; public final class VkGraphicsPipeline extends VkPipeline { private static final String FAILED_TO_CREATE_GRAPHICS_PIPELINE = "Failed to create graphics pipeline"; private final ShaderStageBuilder shaderStageBuilder; private final InputAssemblyBuilder inputAssemblyBuilder; private final ViewportStateBuilder viewportStateBuilder; private final RasterizerBuilder rasterizerBuilder; private final DepthStencilBuilder depthStencilBuidler; private final MultisampleBuilder multisampleBuilder; private final ColorBlendBuilder colorBlendBuilder; private final DynamicStateBuilder dynamicStateBuilder; private final VkPipelineLayout pipelineLayout; private final ColorBlend colorBlend; private final Rasterizer rasterizer; private final InputAssembly inputAssembly; private final ViewportState viewportState; private final DynamicState dynamicState; private final DepthStencilState depthStencilState; private final VkInputStateDescriptor vertexDescriptor; private final List<VkShaderStage> shaderStages; private final ByteBuffer specializationData; private final int subpass; private long pipelinePtr = 0; public VkGraphicsPipeline(VkPipelineLayout pipelineLayout, ColorBlend colorBlend, Rasterizer rasterizer, InputAssembly inputAssembly, ViewportState viewportState, DynamicState dynamicState, DepthStencilState depthStencilState, VkInputStateDescriptor vertexBufferDescriptor, List<VkShaderStage> shaderStages, ByteBuffer specializationData, int subpass) { super(VK_PIPELINE_BIND_POINT_GRAPHICS); this.pipelineLayout = pipelineLayout; this.colorBlend = colorBlend; this.rasterizer = rasterizer; this.inputAssembly = inputAssembly; this.viewportState = viewportState; this.dynamicState = dynamicState; this.depthStencilState = depthStencilState; this.vertexDescriptor = vertexBufferDescriptor; this.shaderStages = shaderStages; this.specializationData = specializationData; this.subpass = subpass; shaderStageBuilder = new ShaderStageBuilder(); inputAssemblyBuilder = new InputAssemblyBuilder(); viewportStateBuilder = new ViewportStateBuilder(); rasterizerBuilder = new RasterizerBuilder(); depthStencilBuidler = new DepthStencilBuilder(); multisampleBuilder = new MultisampleBuilder(); colorBlendBuilder = new ColorBlendBuilder(); dynamicStateBuilder = new DynamicStateBuilder(); } public void allocate(ProcessContext context, Vector2ic extent, RenderPassAllocation renderPassAllocation) { final var device = context.getVkDevice(); final var stack = context.stack(); // Create Pipeline // ----------------------- final var info = VkGraphicsPipelineCreateInfo.callocStack(1, stack); info.sType(VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO); info.pStages(shaderStageBuilder.allocShaderStageInfo(stack, shaderStages, specializationData)); info.pVertexInputState(vertexDescriptor.allocCreateInfo(stack)); info.pInputAssemblyState(inputAssemblyBuilder.allocCreateInfo(stack, inputAssembly)); info.pViewportState(viewportStateBuilder.allocCreateInfo(stack, extent, viewportState)); info.pRasterizationState(rasterizerBuilder.allocCreateInfo(stack, rasterizer)); info.pMultisampleState(multisampleBuilder.allocCreateInfo(stack)); if (depthStencilState != null) info.pDepthStencilState(depthStencilBuidler.allocCreateInfo(stack, depthStencilState)); info.pColorBlendState(colorBlendBuilder.allocCreateInfo(stack, colorBlend)); if (dynamicState != null) info.pDynamicState(dynamicStateBuilder.allocCreateInfo(stack, dynamicState)); info.layout(pipelineLayout.getPtr()); info.renderPass(renderPassAllocation.getPtr()); info.subpass(subpass); info.basePipelineHandle(VK_NULL_HANDLE); info.basePipelineIndex(-1); final long[] aId = new long[1]; Logger.check(vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, info, null, aId), FAILED_TO_CREATE_GRAPHICS_PIPELINE); pipelinePtr = aId[0]; } public void free(ProcessContext context) { final var device = context.getVkDevice(); vkDestroyPipeline(device, pipelinePtr, null); pipelinePtr = 0; } @Override public long getPipelinePtr() { return pipelinePtr; } }
39.195313
106
0.805063
c875678a3324f146a284dffa95fd6dc8e0bc1643
1,049
package org.jooby.issues; import org.jooby.Route; import org.jooby.mvc.GET; import org.jooby.mvc.Path; import org.jooby.test.ServerFeature; import org.junit.Test; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Arrays; public class Issue1208 extends ServerFeature { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Role { String[] value() default ""; } @Path("/1208") public static class Controller1208 { @GET @Role("first") public String first(Route route) { return Arrays.toString((String[]) route.attr("role")); } @GET @Role("second") public String second(Route route) { return Arrays.toString((String[]) route.attr("role")); } } { use(Controller1208.class); } @Test public void shouldNotFailOnEmptyAttribute() throws Exception { request() .get("/1208") .expect("[first]"); } }
20.98
64
0.686368
7196a73364e7f9b7c3178c45ccf0243a81e4bad8
1,218
package mage.cards.a; import java.util.UUID; import mage.MageInt; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.combat.CantBeBlockedSourceEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.constants.Zone; /** * * @author LevelX2 */ public final class AgentOfHorizons extends CardImpl { public AgentOfHorizons(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{G}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.ROGUE); this.power = new MageInt(3); this.toughness = new MageInt(2); // {2}{U}: Agent of Horizons can't be blocked this turn. this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new CantBeBlockedSourceEffect(Duration.EndOfTurn), new ManaCostsImpl("{2}{U}"))); } private AgentOfHorizons(final AgentOfHorizons card) { super(card); } @Override public AgentOfHorizons copy() { return new AgentOfHorizons(this); } }
28.325581
150
0.721675
58b0aaf3b7ac09e5727992cb07015e5ab3046cec
1,361
package com.javarush.task.task22.task2203; /** * Между табуляциями * Метод getPartOfString должен возвращать подстроку между первой и второй табуляцией. * На некорректные данные бросить исключение TooShortStringException. * Класс TooShortStringException не менять. * * * Требования: * 1. Класс TooShortStringException должен быть потомком класса Exception. * 2. Метод getPartOfString должен принимать строку в качестве параметра. * 3. В случае, если строка, переданная в метод getPartOfString содержит менее 2 табуляций * должно возникнуть исключение TooShortStringException. * 4. Метод getPartOfString должен возвращать подстроку между первой и второй табуляцией. */ public class Solution { public static void main(String[] args) throws TooShortStringException { System.out.println(getPartOfString("\tJavaRush - лучший сервис \tобучения Java\t.")); } public static String getPartOfString(String string) throws TooShortStringException { try { int first = string.indexOf("\t") + 1; int second = string.indexOf("\t", first); return string.substring(first, second); } catch (StringIndexOutOfBoundsException | NullPointerException e) { throw new TooShortStringException(); } } public static class TooShortStringException extends Exception { } }
37.805556
93
0.731815
d0149206fb7f7c65681cbff3f5b411c07ad0a2d8
1,577
package pm.n2.parachute; import fi.dy.masa.malilib.event.RenderEventHandler; import pm.n2.parachute.events.InputHandler; import pm.n2.parachute.events.KeyCallbacks; import pm.n2.parachute.events.RenderHandler; import pm.n2.parachute.events.WorldLoadListener; import fi.dy.masa.malilib.config.ConfigManager; import fi.dy.masa.malilib.event.InputEventHandler; import fi.dy.masa.malilib.event.WorldLoadHandler; import fi.dy.masa.malilib.interfaces.IInitializationHandler; import net.minecraft.client.MinecraftClient; // stolen from blanket/tweakeroo lol public class InitHandler implements IInitializationHandler { @Override public void registerModHandlers() { ConfigManager.getInstance().registerConfigHandler(Parachute.MOD_ID, new ParachuteConfig()); RenderHandler renderer = RenderHandler.getInstance(); RenderEventHandler.getInstance().registerGameOverlayRenderer(renderer); RenderEventHandler.getInstance().registerWorldLastRenderer(renderer); InputEventHandler.getKeybindManager().registerKeybindProvider(InputHandler.getInstance()); InputEventHandler.getInputManager().registerKeyboardInputHandler(InputHandler.getInstance()); InputEventHandler.getInputManager().registerMouseInputHandler(InputHandler.getInstance()); WorldLoadListener listener = new WorldLoadListener(); WorldLoadHandler.getInstance().registerWorldLoadPreHandler(listener); WorldLoadHandler.getInstance().registerWorldLoadPostHandler(listener); KeyCallbacks.init(MinecraftClient.getInstance()); } }
45.057143
101
0.798351
e85cc329f8fb695ed85a3863dacf8560491bad05
3,425
package foundation.omni; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; /** * Numeric Value of Indivisible Omni Token * An indivisible token is an integer number of tokens that can't be subdivided to * less than one token. */ public final class OmniIndivisibleValue extends OmniValue { public static final long MIN_VALUE = 0; // Minimum value of 1 in transactions? public static final long MAX_VALUE = 9223372036854775807L; public static final BigInteger MIN_BIGINT = BigInteger.valueOf(MIN_VALUE); public static final BigInteger MAX_BIGINT = BigInteger.valueOf(MAX_VALUE); public static final OmniIndivisibleValue MIN = OmniIndivisibleValue.of(MIN_VALUE); public static final OmniIndivisibleValue MAX = OmniIndivisibleValue.of(MAX_VALUE); public static OmniIndivisibleValue of(BigInteger amount) { checkWilletValue(amount); return new OmniIndivisibleValue(amount.intValue()); } /** * Create OmniDivisibleValue of the specified amount * @param amount Number of Omni tokens * @return OmniDivisibleValue representing amount tokens */ public static OmniIndivisibleValue of(long amount) { return new OmniIndivisibleValue(amount); } /** * Create OmniIndivisibleValue from willets/internal/wire format * * @param willets number of willets * @return OmniIndivisibleValue equal to number of willets */ public static OmniIndivisibleValue ofWillets(long willets) { return OmniIndivisibleValue.of(willets); } /** * <p>Make sure a BigInteger value is a valid value for OmniIndivisibleValue</p> * * @param candidate value to check * @throws ArithmeticException if less than minimum or greater than maximum allowed value */ public static void checkValue(BigInteger candidate) throws ArithmeticException { OmniValue.checkWilletValue(candidate); } /** * <p>Make sure a BigInteger value is a valid value for OmniIndivisibleValue</p> * * <p>Note: Since any positive long is valid, we just need to check that * it's not less than MIN_VALUE</p> * * @param candidate value to check. * @throws ArithmeticException if less than minimum allowed value */ public static void checkValue(long candidate) throws ArithmeticException { OmniValue.checkWilletValue(candidate); } private OmniIndivisibleValue(long willets) { super(willets); } @Override public Class<Long> getNumberType() { return Long.class; } @Override public OmniIndivisibleValue round(MathContext mathContext) { return OmniIndivisibleValue.of(asBigDecimal().round(mathContext).longValue()); } @Override public Long numberValue() { return willets; } public BigDecimal bigDecimalValue() { return asBigDecimal(); } private BigDecimal asBigDecimal() { return new BigDecimal(willets); } @Override public PropertyType getPropertyType() { return PropertyType.INDIVISIBLE; } public OmniIndivisibleValue plus(OmniIndivisibleValue right) { return OmniIndivisibleValue.of(this.willets + right.willets); } public OmniIndivisibleValue minus(OmniIndivisibleValue right) { return OmniIndivisibleValue.of(this.willets - right.willets); } }
31.422018
93
0.70365
3bd4582f85610321d610c0dd804f61a39137af01
341
package dtos; import lombok.Data; import java.math.BigDecimal; import java.util.Date; import java.util.List; @Data public class OrderDto { private Long id; private BigDecimal final_price; private Date created_at; private List<OrderItemDto> items; private PaymentMethodDto payObj; private UserAddressDto addrObj; }
18.944444
37
0.753666
61fac24bc2eab4bc3be4dbf81b68a1b72ff89475
599
package innerclasses; /** * @author XuYanXin * @program aibook-parent * @description * @date 2020/2/13 2:13 下午 */ public class Parcel7b { // 对应匿名内部类,这里单独定义了一个有名字的类 class MyContents implements Contents { private int i = 11; @Override public int value() { return i; } } public Contents contents() { return new MyContents(); } public static void main(String[] args) { Parcel7b parcel7b = new Parcel7b(); Contents contents = parcel7b.contents(); System.out.println(contents.value()); } }
19.322581
48
0.589316
22e0c069c7fd59af378f7cb63e6c28758110c378
3,882
/* * Create by Jacob G(GuanDeLiang) on 2020. * Copyright (c) 2020 . All rights reserved. * Last modified 20-2-1 下午2:24 * */ package com.jacob.material.example.backdrop; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.drawable.Animatable; import android.graphics.drawable.AnimatedVectorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.view.Window; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.OnLifecycleEvent; import androidx.vectordrawable.graphics.drawable.Animatable2Compat; import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat; import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback; import com.jacob.material.R; import com.jacob.material.databinding.BackdropCraneLaunchActivityBinding; public class BackdropCraneLaunchActivity extends AppCompatActivity implements LifecycleObserver{ private BackdropCraneLaunchActivityBinding binding; private Animatable logoAni; private boolean hasStartMainActivity; @Override protected void onCreate(Bundle savedInstanceState) { this.getLifecycle().addObserver(this); //启动Activity动画效果,也可以在在Style正设置 this.getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS); //配合目标Activity中的setEnterSharedElementCallback使用,否则会出现重影,毛边等现象 this.setExitSharedElementCallback(new MaterialContainerTransformSharedElementCallback()); //避免Shared Elements被遮盖 this.getWindow().setSharedElementsUseOverlay(false); super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.backdrop_crane_launch_activity); hasStartMainActivity = false; if (Build.VERSION.SDK_INT >= 24) { AnimatedVectorDrawable logoDrawable = (AnimatedVectorDrawable) getResources().getDrawable(R.drawable.crane_logo_ani, getTheme()); binding.logoImageView.setImageDrawable(logoDrawable); logoAni = ((Animatable)logoDrawable); AnimatedVectorDrawableCompat.registerAnimationCallback(logoDrawable, new AniVectorCallback()); }else{ AnimatedVectorDrawableCompat logoCompatDrawable = AnimatedVectorDrawableCompat.create(this, R.drawable.crane_logo_ani); binding.logoImageView.setImageDrawable(logoCompatDrawable); logoAni = ((Animatable)logoCompatDrawable); AnimatedVectorDrawableCompat.registerAnimationCallback(logoCompatDrawable, new AniVectorCallback()); } logoAni.start(); } private class AniVectorCallback extends Animatable2Compat.AnimationCallback{ public void onAnimationEnd(Drawable drawable) { hasStartMainActivity = true; Intent intent = new Intent(); intent.setClass(BackdropCraneLaunchActivity.this, BackdropCraneMainActivity.class); binding.logoImageView.setImageResource(R.drawable.crane_logo_no_background); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(BackdropCraneLaunchActivity.this, binding.logoImageView, "logoImageView"); startActivity(intent, options.toBundle()); //finishAfterTransition();//无法监听到share element 动画结束,只能通过Lifecycle控制 } } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void onResumeEvent() { //如果启动Main Activity到一半,被中断返回 if(hasStartMainActivity){ finish(); } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) public void onStopEvent() { //如果已经完全启动Main Activity if(hasStartMainActivity){ finish(); } } }
40.863158
157
0.752447
6dfaa9fb78143919b934eac9ebb2a0c7335cd5ab
3,471
/** * 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.hive.ql; import java.util.Map; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.plan.HiveOperation; /** * The class to store query level info such as queryId. Multiple queries can run * in the same session, so SessionState is to hold common session related info, and * each QueryState is to hold query related info. * */ public class QueryState { /** * current configuration. */ private final HiveConf queryConf; /** * type of the command. */ private HiveOperation commandType; public QueryState(HiveConf conf) { this(conf, null, false); } public QueryState(HiveConf conf, Map<String, String> confOverlay, boolean runAsync) { this.queryConf = createConf(conf, confOverlay, runAsync); } /** * If there are query specific settings to overlay, then create a copy of config * There are two cases we need to clone the session config that's being passed to hive driver * 1. Async query - * If the client changes a config setting, that shouldn't reflect in the execution already underway * 2. confOverlay - * The query specific settings should only be applied to the query config and not session * @return new configuration */ private HiveConf createConf(HiveConf conf, Map<String, String> confOverlay, boolean runAsync) { if ( (confOverlay != null && !confOverlay.isEmpty()) ) { conf = (conf == null ? new HiveConf() : new HiveConf(conf)); // apply overlay query specific settings, if any for (Map.Entry<String, String> confEntry : confOverlay.entrySet()) { try { conf.verifyAndSet(confEntry.getKey(), confEntry.getValue()); } catch (IllegalArgumentException e) { throw new RuntimeException("Error applying statement specific settings", e); } } } else if (runAsync) { conf = (conf == null ? new HiveConf() : new HiveConf(conf)); } if (conf == null) { conf = new HiveConf(); } conf.setVar(HiveConf.ConfVars.HIVEQUERYID, QueryPlan.makeQueryId()); return conf; } public String getQueryId() { return (queryConf.getVar(HiveConf.ConfVars.HIVEQUERYID)); } public String getQueryString() { return queryConf.getQueryString(); } public String getCommandType() { if (commandType == null) { return null; } return commandType.getOperationName(); } public HiveOperation getHiveOperation() { return commandType; } public void setCommandType(HiveOperation commandType) { this.commandType = commandType; } public HiveConf getConf() { return queryConf; } }
30.716814
104
0.694324
338da61da97900f183230a0a65c1886734286e8a
1,785
package com.ftninformatika.cris.repository; import com.ftninformatika.cris.model.InstitutionFounder; import com.ftninformatika.cris.model.projection.InstitutionFounderProjection; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; import java.util.List; @RepositoryRestResource(excerptProjection = InstitutionFounderProjection.class) public interface InstitutionFounderRepository extends PagingAndSortingRepository<InstitutionFounder, Long>{ //Bez Institution i Founder @RestResource(path = "search", rel = "search") List<InstitutionFounder> findByRescriptNumberContainingAllIgnoreCase( @Param("rescriptNumber") String rescriptNumber); //Sa Institution i Founder @RestResource(path = "search1", rel = "search1") List<InstitutionFounder> findByRescriptNumberContainingAndInstitutionIdAndFounderIdAllIgnoreCase( @Param("rescriptNumber") String rescriptNumber, @Param("institutionId") Long institutionId, @Param("founderId") Long founderId); //Sa Institution @RestResource(path = "search2", rel = "search2") List<InstitutionFounder> findByRescriptNumberContainingAndInstitutionIdAllIgnoreCase( @Param("rescriptNumber") String rescriptNumber, @Param("institutionId") Long institutionId); //Sa Founder @RestResource(path = "search3", rel = "search3") List<InstitutionFounder> findByRescriptNumberContainingAndFounderIdAllIgnoreCase( @Param("rescriptNumber") String rescriptNumber, @Param("founderId") Long founderId); }
45.769231
107
0.770308
14146a22702b59ecb6991f3d86a9e72a1c08bf37
3,956
package com.artschool.model.entity; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import javax.persistence.*; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; @Entity public class Date { private static final String RANGE_DELIMITER = " - "; private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy"); private static final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("kk:mm"); @Id @Column(name = "date_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private LocalDate startDate; private LocalDate endDate; private LocalTime startTime; private LocalTime endTime; @OneToOne(mappedBy = "date") private Course course; public Date() { } public Date(String dateRange, String startTime, String endTime) { parseDateRange(dateRange); parseTimeRange(startTime, endTime); } public Date(String dateRange, LocalTime startTime, LocalTime endTime) { parseDateRange(dateRange); this.startTime = startTime; this.endTime = endTime; } public Date(LocalDate startDate, LocalDate endDate, LocalTime startTime, LocalTime endTime) { this.startDate = startDate; this.endDate = endDate; this.startTime = startTime; this.endTime = endTime; } private void parseTimeRange(String startTime, String endTime) { this.startTime = LocalTime.parse(startTime, timeFormatter); this.endTime = LocalTime.parse(endTime, timeFormatter); } private void parseDateRange(String dateRange) { String[] dates = dateRange.split(RANGE_DELIMITER); this.startDate = LocalDate.parse(dates[0], dateFormatter); this.endDate = LocalDate.parse(dates[1], dateFormatter); } public long getId() { return id; } public String getFormattedStartDate() { return dateFormatter.format(startDate); } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public String getFormattedEndDate() { return dateFormatter.format(endDate); } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public LocalTime getStartTime() { return startTime; } public void setStartTime(LocalTime startTime) { this.startTime = startTime; } public LocalTime getEndTime() { return endTime; } public void setEndTime(LocalTime endTime) { this.endTime = endTime; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } @Override public String toString() { return "Date{" + "id=" + id + ", startDate=" + startDate + ", endDate=" + endDate + ", startTime=" + startTime + ", endTime=" + endTime + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Date)) return false; Date that = (Date) o; return new EqualsBuilder() .append(startDate, that.startDate) .append(endDate, that.endDate) .append(startTime, that.startTime) .append(endTime, that.endTime) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(startDate) .append(endDate) .append(startTime) .append(endTime) .toHashCode(); } }
25.856209
102
0.618554
5812c49d65bfc9dcb8584442823dae1dd486eb72
422
package org.zeroturnaround.exec.test; import java.io.PrintStream; class Loop { private static final long INTERVAL = 1000; private static final long COUNT = 10; public static void main(String[] args) throws Exception { PrintStream out = System.out; out.println("Started"); for (int i = 0; i < COUNT; i++) { out.println(i); Thread.sleep(INTERVAL); } out.println("Finished"); } }
20.095238
59
0.651659
251eda0ab03476168dae7f664d63e59c9c659ca3
256
package au.com.tyo.jesreader; import au.com.tyo.jesreader.ui.activity.ActivityMain; /** * Created by Eric Tang (eric.tang@tyo.com.au) on 27/11/17. */ public class ActivityApp extends ActivityMain { // the page class is defined in ActivityMain }
18.285714
59
0.726563
39cb24ad346c98e306283d29aad0c74b128bf3fb
445
/* Copyright (C) 2004 - 2006 Versant Inc. http://www.db4o.com */ package com.db4o.instrumentation.bloat; import EDU.purdue.cs.bloat.editor.*; import com.db4o.instrumentation.api.*; public class BloatRef { private final BloatReferenceProvider _provider; public BloatRef(BloatReferenceProvider provider) { _provider = provider; } protected TypeRef typeRef(Type type) { return _provider.forBloatType(type); } }
21.190476
65
0.719101
80e30619c1bec10ae7d246fd2c72b8fc5309f510
640
package minicraft.backend.map.block; import minicraft.backend.constants.Constant; public class DirtBlock extends BlockBackend{ private static final int blockID = Constant.BLOCK_DIRT; public DirtBlock(){ super("dirt"); } @Override public int getBlockid() { return blockID; } public static int getBlockidStatic() { return blockID; } @Override public void playDestorySound() { chunk.getMap().miniCraftApp.audioSounds[1].playInstance(); } @Override public void playPlaceSound() { chunk.getMap().miniCraftApp.audioSounds[1].playInstance(); } }
22.068966
66
0.660938
d2692af850ad170767b2c58bd8d349ea1691cef6
14,230
/* * 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 tut16.gammaRamp; import com.jogamp.newt.awt.NewtCanvasAWT; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.event.KeyListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.GL3; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLCapabilities; import com.jogamp.opengl.GLEventListener; import com.jogamp.opengl.GLProfile; import com.jogamp.opengl.util.FPSAnimator; import com.jogamp.opengl.util.GLBuffers; import com.jogamp.opengl.util.texture.TextureData; import com.jogamp.opengl.util.texture.TextureIO; import framework.GLSLProgramObject; import framework.glutil.MatrixStack; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import java.util.logging.Level; import java.util.logging.Logger; import framework.jglm.Vec3; */ /** * * @author gbarbieri *//* public class GammaRamp implements GLEventListener, KeyListener { */ /** * @param args the command line arguments *//* public static void main(String[] args) { final GammaRamp gammaRamp = new GammaRamp(); gammaRamp.initGL(); Frame frame = new Frame("Tutorial 14 - Material Texture"); frame.add(gammaRamp.newtCanvasAWT); frame.setSize(gammaRamp.window.getWidth(), gammaRamp.window.getHeight()); final FPSAnimator fPSAnimator = new FPSAnimator(gammaRamp.window, 30); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent windowEvent) { fPSAnimator.stop(); gammaRamp.window.destroy(); System.exit(0); } }); fPSAnimator.start(); frame.setVisible(true); } private GLWindow window; private NewtCanvasAWT newtCanvasAWT; private int[] programs; private int[] uniformBlockBuffers; private int[] objects; private int[] textures; private int[] samplerObj; private boolean[] useGammaCorrect = new boolean[]{false, false}; public GammaRamp() { } public void initGL() { GLProfile gLProfile = GLProfile.get(GLProfile.GL3); GLCapabilities gLCapabilities = new GLCapabilities(gLProfile); window = GLWindow.create(gLCapabilities); window.setSize(1024, 768); window.addGLEventListener(this); window.addKeyListener(this); // window.addMouseListener(this); */ /* * We combine NEWT GLWindow inside existing AWT application (the main JFrame) * by encapsulating the glWindow inside a NewtCanvasAWT canvas. *//* newtCanvasAWT = new NewtCanvasAWT(glWindow); } @Override public void init(GLAutoDrawable glad) { GL3 gl3 = glad.getGL().getGL3(); initializePrograms(gl3); initializeVertexData(gl3); loadTextures(gl3); //Setup our Uniform Buffers uniformBlockBuffers = new int[UniformBlockBinding.size.ordinal()]; gl3.glGenBuffers(1, uniformBlockBuffers, UniformBlockBinding.projection.ordinal()); gl3.glBindBuffer(GL3.GL_UNIFORM_BUFFER, uniformBlockBuffers[UniformBlockBinding.projection.ordinal()]); { gl3.glBufferData(GL3.GL_UNIFORM_BUFFER, 16 * 4, null, GL3.GL_DYNAMIC_DRAW); gl3.glBindBufferRange(GL3.GL_UNIFORM_BUFFER, UniformBlockBinding.projection.ordinal(), uniformBlockBuffers[UniformBlockBinding.projection.ordinal()], 0, 16 * 4); } gl3.glBindBuffer(GL3.GL_UNIFORM_BUFFER, 0); // int[] drawBuffer = new int[1]; // gl3.glGetIntegerv(GL3.GL_DRAW_BUFFER, drawBuffer, 0); // System.out.println("draw buffer " + (drawBuffer[0] == GL3.GL_BACK ? "BACK " : drawBuffer[0])); // int[] framebufferAttachmentParameter = new int[1]; // gl3.glGetFramebufferAttachmentParameteriv(GL3.GL_DRAW_FRAMEBUFFER, GL3.GL_FRONT_LEFT, // GL3.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, framebufferAttachmentParameter, 0); // System.out.println("bounded framebuffer " + (framebufferAttachmentParameter[0] // == GL3.GL_FRAMEBUFFER_DEFAULT ? " DEFAULT" : framebufferAttachmentParameter[0])); // gl3.glGetFramebufferAttachmentParameteriv(GL3.GL_DRAW_FRAMEBUFFER, GL3.GL_BACK_LEFT, // GL3.GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, framebufferAttachmentParameter, 0); // System.out.println("color encoding "); // switch (framebufferAttachmentParameter[0]) { // case GL3.GL_LINEAR: // System.out.print("LINEAR"); // break; // case GL3.GL_SRGB: // System.out.print("SRGB"); // break; // default: // System.out.print("" + framebufferAttachmentParameter[0]); // break; // } } private void initializePrograms(GL3 gl3) { programs = new int[Programs.size.ordinal()]; String filepath = "/tut16/gammaRamp/shaders/"; GLSLProgramObject noGammaProgram = new GLSLProgramObject(gl3, filepath, "screenCoords_VS.glsl", "textureNoGamma_FS.glsl"); programs[Programs.noGamma.ordinal()] = noGammaProgram.getProgramId(); GLSLProgramObject gammaProgram = new GLSLProgramObject(gl3, filepath, "screenCoords_VS.glsl", "textureGamma_FS.glsl"); programs[Programs.gamma.ordinal()] = gammaProgram.getProgramId(); int projectionUBI = gl3.glGetUniformBlockIndex(noGammaProgram.getProgramId(), "Projection"); gl3.glUniformBlockBinding(noGammaProgram.getProgramId(), projectionUBI, UniformBlockBinding.projection.ordinal()); int colorTextureUL = gl3.glGetUniformLocation(noGammaProgram.getProgramId(), "colorTexture"); gl3.glUseProgram(noGammaProgram.getProgramId()); { gl3.glUniform1i(colorTextureUL, TexUnit.gammaRamp.ordinal()); } gl3.glUseProgram(0); projectionUBI = gl3.glGetUniformBlockIndex(gammaProgram.getProgramId(), "Projection"); gl3.glUniformBlockBinding(gammaProgram.getProgramId(), projectionUBI, UniformBlockBinding.projection.ordinal()); colorTextureUL = gl3.glGetUniformLocation(gammaProgram.getProgramId(), "colorTexture"); gl3.glUseProgram(gammaProgram.getProgramId()); { gl3.glUniform1i(colorTextureUL, TexUnit.gammaRamp.ordinal()); } gl3.glUseProgram(0); } private void initializeVertexData(GL3 gl3) { short[] vertexData = new short[]{ 90, 80, 0, 0, 90, 16, 0, Short.MAX_VALUE, 410, 80, Short.MAX_VALUE, 0, 410, 16, Short.MAX_VALUE, Short.MAX_VALUE, 90, 176, 0, 0, 90, 112, 0, Short.MAX_VALUE, 410, 176, Short.MAX_VALUE, 0, 410, 112, Short.MAX_VALUE, Short.MAX_VALUE}; objects = new int[Objects.size.ordinal()]; gl3.glGenBuffers(1, objects, Objects.dataBuffer.ordinal()); gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, objects[Objects.dataBuffer.ordinal()]); { ShortBuffer shortBuffer = GLBuffers.newDirectShortBuffer(vertexData); gl3.glBufferData(GL3.GL_ARRAY_BUFFER, vertexData.length * GLBuffers.SIZEOF_SHORT, shortBuffer, GL3.GL_STATIC_DRAW); gl3.glGenVertexArrays(1, objects, Objects.vao.ordinal()); gl3.glBindVertexArray(objects[Objects.vao.ordinal()]); { int stride = 4 * GLBuffers.SIZEOF_SHORT; int offset = 0; gl3.glEnableVertexAttribArray(0); { gl3.glVertexAttribPointer(0, 2, GL3.GL_SHORT, false, stride, offset); } offset = 2 * GLBuffers.SIZEOF_SHORT; gl3.glEnableVertexAttribArray(5); { gl3.glVertexAttribPointer(5, 2, GL3.GL_SHORT, true, stride, offset); } } gl3.glBindVertexArray(0); } gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0); } private void loadTextures(GL3 gl3) { textures = new int[2]; gl3.glGenTextures(2, textures, 0); String filePath = "/tut16/gammaRamp/data/gamma_ramp.png"; URL url = getClass().getResource(filePath); File file = new File(url.getPath()); try { TextureData textureData = TextureIO.newTextureData(gl3.getGLProfile(), file, false, TextureIO.PNG); gl3.glBindTexture(GL3.GL_TEXTURE_2D, textures[Programs.noGamma.ordinal()]); { gl3.glTexImage2D(GL3.GL_TEXTURE_2D, 0, GL3.GL_RGB8, textureData.getWidth(), textureData.getHeight(), 0, textureData.getPixelFormat(), textureData.getPixelType(), textureData.getBuffer()); gl3.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_BASE_LEVEL, 0); gl3.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_MAX_LEVEL, 0); } gl3.glBindTexture(GL3.GL_TEXTURE_2D, textures[Programs.gamma.ordinal()]); { gl3.glTexImage2D(GL3.GL_TEXTURE_2D, 0, GL3.GL_SRGB8, textureData.getWidth(), textureData.getHeight(), 0, textureData.getPixelFormat(), textureData.getPixelType(), textureData.getBuffer()); gl3.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_BASE_LEVEL, 0); gl3.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_MAX_LEVEL, 0); } gl3.glBindTexture(GL3.GL_TEXTURE_2D, 0); // textureData = TextureIO.newTextureData(gl3.getGLProfile(), file, true, TextureIO.PNG); // // System.out.println("textureData.getMipmap() "+textureData.getMipmap()); // System.out.println("textureData.getMipmapData().length "+textureData.getMipmapData().length); // samplerObj = new int[1]; gl3.glGenSamplers(1, samplerObj, 0); gl3.glSamplerParameteri(samplerObj[0], GL3.GL_TEXTURE_WRAP_S, GL3.GL_CLAMP_TO_EDGE); gl3.glSamplerParameteri(samplerObj[0], GL3.GL_TEXTURE_WRAP_T, GL3.GL_CLAMP_TO_EDGE); gl3.glSamplerParameteri(samplerObj[0], GL3.GL_TEXTURE_MAG_FILTER, GL3.GL_NEAREST); gl3.glSamplerParameteri(samplerObj[0], GL3.GL_TEXTURE_MIN_FILTER, GL3.GL_NEAREST); } catch (IOException ex) { Logger.getLogger(GammaRamp.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void dispose(GLAutoDrawable glad) { } @Override public void display(GLAutoDrawable glad) { GL3 gl3 = glad.getGL().getGL3(); gl3.glClearColor(0f, .5f, .3f, 0f); gl3.glClear(GL3.GL_COLOR_BUFFER_BIT); gl3.glActiveTexture(GL3.GL_TEXTURE0 + TexUnit.gammaRamp.ordinal()); int texUnit = useGammaCorrect[0] ? Programs.gamma.ordinal() : Programs.noGamma.ordinal(); gl3.glBindTexture(GL3.GL_TEXTURE_2D, textures[texUnit]); { gl3.glBindSampler(textures[TexUnit.gammaRamp.ordinal()], samplerObj[0]); { gl3.glBindVertexArray(objects[Objects.vao.ordinal()]); { gl3.glUseProgram(programs[Programs.noGamma.ordinal()]); { gl3.glDrawArrays(GL3.GL_TRIANGLE_STRIP, 0, 4); } } } } texUnit = useGammaCorrect[1] ? Programs.gamma.ordinal() : Programs.noGamma.ordinal(); gl3.glBindTexture(GL3.GL_TEXTURE_2D, textures[texUnit]); { gl3.glUseProgram(programs[Programs.gamma.ordinal()]); { gl3.glDrawArrays(GL3.GL_TRIANGLE_STRIP, 4, 4); } gl3.glBindVertexArray(0); gl3.glUseProgram(0); } gl3.glBindTexture(GL3.GL_TEXTURE_2D, 0); gl3.glBindSampler(TexUnit.gammaRamp.ordinal(), 0); } @Override public void reshape(GLAutoDrawable glad, int x, int y, int w, int h) { GL3 gl3 = glad.getGL().getGL3(); MatrixStack persMatrix = new MatrixStack(); persMatrix.translate(new Vec3(-1f, 1f, 0f)); persMatrix.scale(new Vec3(2f / w, -2f / h, 1f)); gl3.glBindBuffer(GL3.GL_UNIFORM_BUFFER, uniformBlockBuffers[UniformBlockBinding.projection.ordinal()]); { FloatBuffer floatBuffer = GLBuffers.newDirectFloatBuffer(persMatrix.top().toFloatArray()); gl3.glBufferSubData(GL3.GL_UNIFORM_BUFFER, 0, 16 * 4, floatBuffer); } gl3.glBindBuffer(GL3.GL_UNIFORM_BUFFER, 0); gl3.glViewport(x, y, w, h); } @Override public void keyPressed(KeyEvent ke) { switch (ke.getKeyCode()) { case KeyEvent.VK_1: useGammaCorrect[0] = !useGammaCorrect[0]; if (useGammaCorrect[0]) { System.out.println("Top sRGB texture."); } else { System.out.println("Top linear texture."); } break; case KeyEvent.VK_2: useGammaCorrect[1] = !useGammaCorrect[1]; if (useGammaCorrect[1]) { System.out.println("Bottom sRGB texture."); } else { System.out.println("Bottom linear texture."); } break; } } @Override public void keyReleased(KeyEvent ke) { } public enum Objects { dataBuffer, vao, size } public enum UniformBlockBinding { projection, size } public enum TexUnit { gammaRamp, size } private enum Programs { noGamma, gamma, size } } */
34.455206
122
0.62045
36d837365f5c641c6917610364053ec4f24f8181
3,564
package com.skywatcher.extend; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Panorama { private final String TAG = "Panorama"; private static Angle FovX, FovY; // between 10 ~ 100 public static Angle getFovX() { return FovX; } public static void setFovX(Angle fovX) { FovX = fovX; } public static Angle getFovY() { return FovY; } public static void setFovY(Angle fovY) { FovY = fovY; } public static double getOverlap() { return Overlap; } public static void setOverlap(double overlap) { Overlap = overlap; } public static double getStepDelay() { return StepDelay; } public static void setStepDelay(double stepDelay) { StepDelay = stepDelay; } public static double getTriggerDelay() { return TriggerDelay; } public static void setTriggerDelay(double triggerDelay) { TriggerDelay = triggerDelay; } public static boolean isPortrait() { return Portrait; } public static void setPortrait(boolean portrait) { Portrait = portrait; } private static double Overlap; // should between 0.2 ~ 0.5 private static double StepDelay; // should between 1 ~ 20 sec private static double TriggerDelay; // should between 1 ~ 5 sec private static boolean Portrait; // FovX always bigger than FovY // MinAlt must smaller than MaxAlt // MinAlt -90 ~ 90 // MaxAlt -90 ~ 90 // MinAz -180 ~ 180 // MaxAz -180 ~ 180 public static List<CroodAxis1Axis2> GenerateShotPoint(Angle MinAz, Angle MaxAz, Angle MinAlt, Angle MaxAlt) { // Need to check the books double delta_y = 0, delta_x = 0; if (Portrait == false) { delta_x = FovX.getRad(); delta_y = FovY.getRad(); } else { delta_x = FovY.getRad(); delta_y = FovX.getRad(); } double max_alt_rad = MaxAlt.getRad(); double min_alt_rad = MinAlt.getRad(); double max_az_rad = MaxAz.getRad(); double min_az_rad = MinAz.getRad(); double ratio = 1 - Overlap; if(max_az_rad < min_az_rad) max_az_rad = max_az_rad + Angle.RAD360; List<CroodAxis1Axis2> list = new LinkedList<CroodAxis1Axis2>(); List<CroodAxis1Axis2> list2 = new LinkedList<CroodAxis1Axis2>(); int direction = 0; // az_position, alt_position is the center of camera for(double alt_position = min_alt_rad + delta_y * ratio / 2; ; alt_position += delta_y * ratio){ double alt_position_min = alt_position - delta_y / 2; double alt_position_max = alt_position + delta_y / 2; double delta_angle = 0; if(alt_position_min < 0 && alt_position_max < 0) delta_angle = - alt_position_max; if(alt_position_min < 0 && alt_position_max > 0) delta_angle = 0; if(alt_position_min > 0 && alt_position_max > 0) delta_angle = alt_position_min; double delta_x_with_alt_fixed = delta_x / Math.cos(delta_angle); list2.clear(); for(double az_position = min_az_rad + delta_x_with_alt_fixed * ratio / 2; ; az_position += delta_x_with_alt_fixed * ratio) { list2.add(new CroodAxis1Axis2(Angle.FromRad(az_position), Angle.FromRad(alt_position))); if(max_az_rad < az_position + delta_x_with_alt_fixed / 2) break; } if(direction % 2 == 0) { list.addAll(list2); } else { Collections.reverse(list2); list.addAll(list2); } direction ++; // if covered the max_alt_rad already if(max_alt_rad < alt_position_max) break; } return list; } }
25.826087
139
0.660213
d4b7608ba510a50e955847f6959921080b57c0b7
3,443
package com.joker17.small.tools; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import static org.junit.Assert.*; public class ConsoleTableTest { @Test public void test() { List<String> titleList = new ArrayList<>(16); int size = 101; for (int i = 0; i < size; i++) { titleList.add(String.valueOf(i)); } ConsoleTable table = ConsoleTable.of(titleList.toArray(new String[size])); table.leftMargin(3); table.rightMargin(3); for (int i = 0; i < 20; i++) { String[] contents = new String[size]; for (int j = 0; j < size; j++) { contents[j] = String.valueOf(i * j); } table.addRowElements(contents); } table.textAligns(ConsoleTable.TextAlign.CENTER).print(); table.textAligns(ConsoleTable.TextAlign.LEFT).print(); table.textAligns(ConsoleTable.TextAlign.RIGHT).print(); } @Test public void testSimple() { List<String> titleList = new ArrayList<>(16); int size = 10; for (int i = 0; i < size; i++) { titleList.add(String.format("%s%s", (char) (65 + i), (char) (65 + i))); } ConsoleTable table = ConsoleTable.of(titleList.toArray(new String[size])); table.leftMargin(3); table.rightMargin(3); for (int i = 0; i < 8; i++) { String[] contents = new String[size]; for (int j = 0; j < size; j++) { contents[j] = String.valueOf(i * j); } table.addRowElements(contents); } table.textAligns(ConsoleTable.TextAlign.CENTER).print(); table.textAligns(ConsoleTable.TextAlign.LEFT).print(); table.textAligns(ConsoleTable.TextAlign.RIGHT).print(); } @Test public void testChinese() { //测试输出中文 -- 控制台样式排版整齐字体需是等宽字体, e.g: 雅黑 幼圆等 List<String> titleList = Arrays.asList("数学", "语文", "英语", "历史", "地理", "思想政治", "总分"); int size = titleList.size(); ConsoleTable table = ConsoleTable.of(titleList.toArray(new String[size])); for (int i = 0; i < 20; i++) { String[] contents = new String[size]; int total = 0; for (int j = 0; j < size; j++) { if (j < 3) { int current = new Random().nextInt(100) + 50; total += current; contents[j] = String.valueOf(current); } else { if (j != size - 1) { int current = new Random().nextInt(50) + 50; total += current; contents[j] = String.valueOf(current); } else { contents[j] = String.valueOf(total); } } } table.addRowElements(contents); } table.textAligns(ConsoleTable.TextAlign.CENTER).print(); table.textAligns(ConsoleTable.TextAlign.LEFT).print(); table.textAligns(ConsoleTable.TextAlign.RIGHT).print(); //测试输出获取的字符串 System.out.println("<<<<<<<<<<<<---------------->>>>>>>>>>>>"); System.out.print(table.textAligns(ConsoleTable.TextAlign.CENTER).getAsString()); System.out.println("<<<<<<<<<<<<---------------->>>>>>>>>>>>"); } }
33.105769
91
0.51612
0bc45a6dc20cd6c24d278f7798f0b710a6b7b0f1
1,017
/* * Copyright 2017 StreamSets 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.streamsets.pipeline.stage.processor.hive; import com.streamsets.pipeline.api.base.BaseEnumChooserValues; import com.streamsets.pipeline.stage.lib.hive.typesupport.HiveType; public class PartitionColumnTypeChooserValues extends BaseEnumChooserValues<HiveType> { public PartitionColumnTypeChooserValues() { super( HiveType.INT, HiveType.BIGINT, HiveType.STRING ); } }
31.78125
87
0.749263
7e7f896f0040f8f6e518bed55be0a679965f7b4d
461
package com.xiao9; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration; @SpringBootApplication public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class); } }
30.733333
86
0.826464
691dfbaa1ff85ae58f47ae3e02bc28da3c4f872e
5,522
package com.steelypip.powerups.minx; import com.steelypip.powerups.exceptions.Alert; import com.steelypip.powerups.repeaters.PeekableCharRepeater; public class MinXParser< T extends MinX > { private int level = 0; final PeekableCharRepeater cucharin; private boolean pending_end_tag = false; private MinXBuilder< T > parent = null; private String tag_name = null; public MinXParser( PeekableCharRepeater rep, MinXBuilder< T > parent ) { this.parent = parent; this.cucharin = rep; } private char nextChar() { return this.cucharin.nextChar(); } private char peekChar() { return this.cucharin.peekChar(); } private void mustReadChar( final char ch_want ) { if ( this.cucharin.hasNextChar( ch_want ) ) { this.cucharin.skip(); } else { if ( this.cucharin.hasNext() ) { throw new Alert( "Unexpected character" ).culprit( "Wanted", "" + ch_want ).culprit( "Received", "" + this.cucharin.peekChar() ); } else { throw new Alert( "Unexpected end of stream" ); } } } private void eatWhiteSpace() { while ( this.cucharin.hasNext() ) { final char ch = this.cucharin.nextChar(); if ( ch == '#' && this.level == 0 ) { // EOL comment. while ( this.cucharin.hasNext() && this.cucharin.nextChar() != '\n' ) { } } else if ( ! Character.isWhitespace( ch ) ) { this.cucharin.putBackChar( ch ); return; } } } private static boolean is_name_char( final char ch ) { return Character.isLetterOrDigit( ch ) || ch == '-' || ch == '.'; } private String readName() { final StringBuilder name = new StringBuilder(); while ( this.cucharin.hasNext() ) { final char ch = this.cucharin.nextChar(); if ( is_name_char( ch ) ) { name.append( ch ); } else { this.cucharin.putBackChar( ch ); break; } } return name.toString(); } private String readAttributeValue() { final StringBuilder attr = new StringBuilder(); final char q = this.nextChar(); if ( q != '"' && q != '\'' ) throw new Alert( "Attribute value not quoted" ).culprit( "Character", q ); for (;;) { char ch = this.nextChar(); if ( ch == q ) break; if ( ch == '&' ) { final StringBuilder esc = new StringBuilder(); for (;;) { ch = this.nextChar(); if ( ch == ';' ) break; //std::cout << "char " << ch << endl; esc.append( ch ); if ( esc.length() > 4 ) { throw new Alert( "Malformed escape" ).culprit( "Sequence", esc ); } } if ( esc.length() >= 2 && esc.charAt( 0 ) == '#' ) { try { final int n = Integer.parseInt( esc.toString().substring( 1 ) ); attr.append( (char)n ); } catch ( NumberFormatException e ) { throw new Alert( e, "Unexpected numeric sequence after &#" ).culprit( "Sequence", esc ); } } else { final String e = esc.toString(); if ( "lt".equals( e ) ) { attr.append( '<' ); } else if ( "gt".equals( e ) ) { attr.append( '>' ); } else if ( "amp".equals( e ) ) { attr.append( '&' ); } else if ( "quot".equals( e ) ) { attr.append( '"' ); } else if ( "apos".equals( e ) ) { attr.append( '\'' ); } else { throw new Alert( "Unexpected escape sequence after &" ).culprit( "Sequence", esc ); } } } else { attr.append( ch ); } } return attr.toString(); } private void processAttributes() { // Process attributes for (;;) { this.eatWhiteSpace(); char c = peekChar(); if ( c == '/' || c == '>' ) break; final String key = this.readName(); this.eatWhiteSpace(); this.mustReadChar( '=' ); this.eatWhiteSpace(); final String value = this.readAttributeValue(); this.parent.put( key, value ); } } private void read() { if ( this.pending_end_tag ) { this.parent.endTag( this.tag_name ); this.pending_end_tag = false; this.level -= 1; return; } this.eatWhiteSpace(); if ( !this.cucharin.hasNext() ) { return; } this.mustReadChar( '<' ); char ch = this.nextChar(); if ( ch == '/' ) { final String end_tag = this.readName(); this.eatWhiteSpace(); this.mustReadChar( '>' ); this.parent.endTag( end_tag ); this.level -= 1; return; } else if ( ch == '!' ) { if ( '-' != nextChar() || '-' != nextChar() ) throw new Alert( "Invalid XML comment syntax" ); ch = nextChar(); for (;;) { char prev_ch = ch; ch = nextChar(); if ( prev_ch == '-' && ch == '-' ) break; } if ( '>' != this.nextChar() ) throw new Alert( "Invalid XML comment syntax" ); this.read(); return; } else if ( ch == '?' ) { for (;;) { char prev = ch; ch = this.nextChar(); if ( prev == '?' && ch == '>' ) break; } this.read(); return; } else { //cout << "Ungetting '" << ch << "'" << endl; this.cucharin.putBackChar( ch ); } this.tag_name = this.readName(); this.parent.startTag( this.tag_name ); this.processAttributes(); // Commenting out the original C++ callback. // this.parent.startTagClose( this.tag_name ); this.eatWhiteSpace(); ch = nextChar(); if ( ch == '/' ) { this.mustReadChar( '>' ); this.pending_end_tag = true; this.level += 1; //this->parent.endTag( name ); <- this code replaced return; } else if ( ch == '>' ) { this.level += 1; return; } else { throw new Alert( "Invalid continuation" ); } } public void readElement() { for (;;) { this.read(); if ( this.level == 0 ) break; } } } // namespace
24.762332
133
0.567005
f7c8ff66c011fb67c41aec13091e09197aea5c8a
579
package toolgood.textfilter.api.Datas.Images; public class ImageClassifyResult { /** * 返回码:0) 成功,1) 失败 */ public int code; /** * 返回码详情描述 */ public String message; /** * 请求标识 */ public String requestId; /** * 色情系数 */ public Float porn; /** * 血腥系数 */ public Float bloody; /** * 变态系数 */ public Float hentai; /** * 引诱系数 */ public Float lure; /** * 性感系数 */ public Float sexy; /** * 正常系数 */ public Float normal; }
11.816327
45
0.452504
c24eac188b4c1071b69b9432e9b067cea6c08462
647
package name.matco.hotspot.api.security.tokens; import java.time.Instant; import jakarta.validation.constraints.NotNull; public class RevokedToken { @NotNull private final String token; @NotNull private final Instant expirationDate; @NotNull private final long userFk; public RevokedToken(final String token, final Instant expirationDate, final long userFk) { this.token = token; this.expirationDate = expirationDate; this.userFk = userFk; } public final String getToken() { return token; } public final long getUserFk() { return userFk; } public final Instant getExpirationDate() { return expirationDate; } }
17.486486
91
0.75425
fa27e72316d8f9195a16987988a9e3a96267d6a7
7,883
package com.maq.xprize.kitkitlauncher.english; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.PixelFormat; import android.graphics.Point; import android.os.Build; import android.os.Environment; import android.preference.PreferenceManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.TextView; import com.maq.kitkitProvider.User; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import static com.maq.kitkitProvider.KitkitDBHandler.DATABASE_NAME; public class Util { public static String TAG = "TodoschoolLancher"; public static CustomViewGroup mBlockingView; public static void hideSystemUI(Activity activity) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); return; } activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |View.SYSTEM_UI_FLAG_FULLSCREEN |View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |View.SYSTEM_UI_FLAG_LAYOUT_STABLE |View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } public static class CustomViewGroup extends ViewGroup { public CustomViewGroup(Context context) { super(context); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } } public static void disableStatusBar(Activity activity) { WindowManager manager = ((WindowManager) activity.getApplicationContext().getSystemService(Context.WINDOW_SERVICE)); WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams(); localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR; localLayoutParams.gravity = Gravity.TOP; localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | // this is to enable the notification to receive touch events WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | // Draws over status bar WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; localLayoutParams.height = (int) (24 * activity.getResources().getDisplayMetrics().scaledDensity); localLayoutParams.format = PixelFormat.TRANSPARENT; mBlockingView = new CustomViewGroup(activity); } public static DisplayMetrics getWindowInfo(Activity activity) { DisplayMetrics result = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(result); return result; } public static Point getWindowSize(Activity activity) { Point result = new Point(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { WindowManager windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); display.getSize(result); return result; } activity.getWindowManager().getDefaultDisplay().getRealSize(result); return result; } public static float setScale(Activity activity, View rootView) { Point size = Util.getWindowSize(activity); float BASIC_HEIGHT = 1800.f; float fixedSizeWidth = BASIC_HEIGHT * size.x / size.y; float fixedSizeHeight = BASIC_HEIGHT; float scale = size.y / BASIC_HEIGHT; Log.i(TAG, "display width : " + size.x); Log.i(TAG, "display height : " + size.y); Log.i(TAG, "fixed width : " + fixedSizeWidth); Log.i(TAG, "fixed height : " + fixedSizeHeight); Log.i(TAG, "scale : " + scale); ViewGroup.LayoutParams params = rootView.getLayoutParams(); params.width = (int)(fixedSizeWidth + 0.5f); params.height = (int)(fixedSizeHeight + 0.5f); rootView.setPivotX(0); rootView.setPivotY(0); rootView.setScaleX(scale); rootView.setScaleY(scale); return scale; } public static void recycle(View view) { if (view == null) { return; } if (view.getBackground() != null) { view.getBackground().setCallback(null); } view.setBackgroundDrawable(null); if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { recycle(((ViewGroup) view).getChildAt(i)); } if ((view instanceof AdapterView) == false) { ((ViewGroup) view).removeAllViews(); } } if (view instanceof ImageView) { ((ImageView) view).setImageDrawable(null); } view = null; } public static void displayUserName(Activity activity, TextView tvUserName) { User user = ((LauncherApplication) activity.getApplication()).getDbHandler().getCurrentUser(); String name = ""; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); String displayName = user.getDisplayName(); String tabletNumber = prefs.getString("TABLET_NUMBER", ""); if ("user0".equalsIgnoreCase(user.getUserName())) { int userCount = ((LauncherApplication)activity.getApplication()).getDbHandler().numUserSeenLauncherTutorial(); if (userCount >= 2 || (userCount == 1 && user.isFinishLauncherTutorial() == false)) { name = user.getUserName(); } } else { name = user.getUserName(); } if (!name.isEmpty()) { String result = name; if (displayName != null && !displayName.isEmpty()) { result += ("-" + displayName); } if (!tabletNumber.isEmpty()) { result += ("-t" + tabletNumber); } tvUserName.setText(result); } else { tvUserName.setText(""); } } public static void copyDBFileToSDCard(Context context) { String file_url = "/data/data/" + context.getPackageName() + "/databases/" + DATABASE_NAME; File db = new File(file_url); if (db.exists()) { File outDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"); try { if (outDirectory.exists() == false) { outDirectory.mkdirs(); } InputStream in = new FileInputStream(file_url); OutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + DATABASE_NAME); byte buf[] = new byte[4096]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("Can't copy database. Database not created."); } } }
34.273913
139
0.627553
02e806d42bffa4744c7833e10d43620b594bed04
5,458
/* Copyright 2009-2019 David Hadka * * This file is part of the MOEA Framework. * * The MOEA Framework 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 3 of the License, or (at your * option) any later version. * * The MOEA Framework 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 the MOEA Framework. If not, see <http://www.gnu.org/licenses/>. */ package org.moeaframework.core.operator.subset; import java.util.HashSet; import java.util.Set; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.junit.Assert; import org.junit.Test; import org.moeaframework.TestThresholds; import org.moeaframework.core.PRNG; import org.moeaframework.core.Solution; import org.moeaframework.core.operator.ParentImmutabilityTest; import org.moeaframework.core.operator.TypeSafetyTest; import org.moeaframework.core.variable.Subset; /** * Tests the {@link SSX} class. */ public class SSXTest { /** * Tests if the SSX crossover operator is type-safe. */ @Test public void testTypeSafety() { TypeSafetyTest.testTypeSafety(new SSX(1.0)); } /** * Tests if the {@link SSX#evolve} method produces valid subset for fixed-size sets. */ @Test public void testEvolveFixedSize() { DescriptiveStatistics stats1 = new DescriptiveStatistics(); DescriptiveStatistics stats2 = new DescriptiveStatistics(); for (int i = 0; i < TestThresholds.SAMPLES; i++) { int n = PRNG.nextInt(1, 20); int k = PRNG.nextInt(0, n); Subset s1 = new Subset(k, n); Subset s2 = new Subset(k, n); s1.randomize(); s2.randomize(); Subset s1copy = s1.copy(); Subset s2copy = s2.copy(); SSX.evolve(s1copy, s2copy); s1copy.validate(); s2copy.validate(); countSwapped(s1, s2, s1copy, s2copy, stats1, stats2); } Assert.assertEquals(0.5, stats1.getMean(), TestThresholds.STATISTICS_EPS); Assert.assertEquals(0.5, stats1.getMean(), TestThresholds.STATISTICS_EPS); } /** * Tests if the {@link SSX#evolve} method produces valid subset for variable-size sets. */ @Test public void testEvolveVariableSize() { DescriptiveStatistics stats1 = new DescriptiveStatistics(); DescriptiveStatistics stats2 = new DescriptiveStatistics(); for (int i = 0; i < TestThresholds.SAMPLES; i++) { int n = PRNG.nextInt(1, 20); int l = PRNG.nextInt(0, n-1); int u = PRNG.nextInt(l+1, n); Subset s1 = new Subset(l, u, n); Subset s2 = new Subset(l, u, n); s1.randomize(); s2.randomize(); Subset s1copy = s1.copy(); Subset s2copy = s2.copy(); int size1 = s1copy.size(); int size2 = s2copy.size(); SSX.evolve(s1copy, s2copy); s1copy.validate(); s2copy.validate(); Assert.assertEquals(size1, s1copy.size()); Assert.assertEquals(size2, s2copy.size()); countSwapped(s1, s2, s1copy, s2copy, stats1, stats2); } Assert.assertEquals(0.5, stats1.getMean(), TestThresholds.STATISTICS_EPS); Assert.assertEquals(0.5, stats1.getMean(), TestThresholds.STATISTICS_EPS); } /** * Tests if the parents remain unchanged during variation. */ @Test public void testParentImmutability() { SSX ssx = new SSX(1.0); Subset p1 = new Subset(5, 10); Subset p2 = new Subset(5, 10); p1.randomize(); p2.randomize(); Solution s1 = new Solution(1, 0); s1.setVariable(0, p1); Solution s2 = new Solution(1, 0); s2.setVariable(0, p2); Solution[] parents = new Solution[] { s1, s2 }; ParentImmutabilityTest.test(parents, ssx); } /** * Records the percent of swapped values in each subset. * * @param original1 the first subset * @param original2 the second subset * @param new1 the first evolved subset * @param new2 the second evolved subset * @param stats1 the percent of swapped values for the first subset * @param stats2 the percent of swapped values for the second subset */ protected void countSwapped(Subset original1, Subset original2, Subset new1, Subset new2, DescriptiveStatistics stats1, DescriptiveStatistics stats2) { Set<Integer> original1set = original1.getSet(); Set<Integer> new1set = new1.getSet(); Set<Integer> original2set = original2.getSet(); Set<Integer> new2set = new2.getSet(); Set<Integer> intersection = new HashSet<Integer>(original1set); intersection.retainAll(original2set); original1set.removeAll(intersection); new1set.removeAll(intersection); original2set.removeAll(intersection); new2set.removeAll(intersection); int original1size = original1set.size(); int original2size = original2set.size(); int minSize = Math.min(original1size, original2size); if (minSize > 0) { original1set.retainAll(new1set); original2set.retainAll(new2set); stats1.addValue((original1size - original1set.size()) / (double)minSize); stats2.addValue((original2size - original2set.size()) / (double)minSize); } } }
30.322222
91
0.684683
a7e59674b482466cb2590b6c32f5b61c5677fe63
1,432
/* * Copyright 2014 Guillaume CHAUVET. * * 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.zatarox.chess.openchess.models.moves; import com.zatarox.chess.openchess.models.moves.exceptions.IllegalMoveException; import com.zatarox.chess.openchess.models.materials.*; public class BasicMove extends AbstractMove { public BasicMove(Square from, Square to) { super(from, to); } @Override protected void doPlay(ChessBoard board) throws IllegalMoveException { move(board, getFrom(), getTo()); } @Override protected void doUnplay(ChessBoard board) throws IllegalMoveException { unmove(board, getFrom(), getTo()); } @Override public void accept(MoveVisitor visitor) { visitor.visit(this); } @Override public String toString() { return getFrom() + "-" + getTo(); } }
29.833333
81
0.678771
bb8020ee36b5b373d9eaa4fc81ff24ded7cb9e7b
2,616
package dsa.stacks; import java.util.ArrayList; import java.util.EmptyStackException; import java.util.List; public class SetOfStacks { List<Stack> stacks = new ArrayList<>(); int capacity; public SetOfStacks(int capacity) { this.capacity = capacity; } public void push(int v) { Stack last = getLastStack(); if (last != null && !last.isFull()) { last.push(v); } else { Stack stack = new Stack(capacity); stack.push(v); stacks.add(stack); } } public int pop() { Stack last = getLastStack(); if (last == null) { throw new EmptyStackException(); } int v = last.pop(); if (last.size == 0) { stacks.remove(stacks.size() -1); } return v; } public int popAt(int index) { return leftShift(index, true); } public int leftShift(int index, boolean removeTop) { Stack stack = stacks.get(index); int removed_item; if (removeTop) { removed_item = stack.pop(); } else { removed_item = stack.removeBottom(); } if (stack.isEmpty()) { stacks.remove(index); } else if (stacks.size() > index + 1) { int v = leftShift(index + 1, false); stack.push(v); } return removed_item; } Stack getLastStack() { if (stacks.size() == 0) { return null; } return stacks.get(stacks.size()-1); } public boolean isEmpty() { Stack last = getLastStack(); return last == null || last.isEmpty(); } class Stack { private int capacity; Node top, bottom; int size = 0; public Stack(int capacity) { this.capacity = capacity; } public boolean isFull() { return capacity == size; } public void join(Node above, Node below) { if (below != null) { below.above = above; } if (above != null) { above.below = below; } } public boolean push(int v) { if (size >= capacity) { return false; } size++; Node n = new Node(v); if (size == 1) { bottom = n; } join(n, top); top = n; return true; } public int pop() { Node t = top; top = top.below; size--; return t.value; } public boolean isEmpty() { return size == 0; } public int removeBottom() { Node b = bottom; bottom = bottom.above; if (bottom != null) { bottom.below = null; } size--; return b.value; } } class Node { Node below, above; int value; public Node(int value) { this.value = value; } } }
19.094891
54
0.54052
434da41ad812cd7c0c35b08afd0a44e76884ca36
2,749
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xx; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.view.Surface; import android.view.WindowManager; public class Activity extends android.app.Activity { View mView; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); mView = new View(getApplication()); setContentView(mView); int options = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) options = View.GONE; getWindow().getDecorView().setSystemUiVisibility(options); if (Build.VERSION.SDK_INT >= 28) { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; getWindow().setAttributes(lp); } } @Override protected void onPause() { super.onPause(); mView.onPause(); } @Override protected void onResume() { super.onResume(); mView.onResume(); } // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("xxImGui"); } /** * A native method that is implemented by the 'xxImGui' native library, * which is packaged with this application. */ public static native void create(Context context, Surface surface); public static native void resize(int width, int height, Surface surface); public static native void step(Context context); public static native void shutdown(); public static native void pause(); public static native void resume(); public static native void touch(int type, float x, float y); }
33.120482
112
0.673336
ead8e04bca6eadf95a52d29a34ee9f55dbb8c6d4
2,647
//package com.k317h.restez.util; // //import java.util.Arrays; //import java.util.List; //import java.util.Optional; //import java.util.function.Function; //import java.util.stream.Collectors; // //import com.k317h.restez.io.Request; // //public class QueryParamUtil { // // private static Function<String[], Optional<String>> PARAM_TO_FIRST_VALUE = params -> { // if(params.length > 0) { // return Optional.of(params[0]); // } else { // return Optional.empty(); // } // }; // // public static Optional<String> asString(Request req, String paramName) { // return req.query(paramName).flatMap(PARAM_TO_FIRST_VALUE); // } // public static Optional<List<String>> asListOfStrings(Request req, String paramName) { // return req.query(paramName).map(params -> Arrays.asList(params)); // } // // // // public static Optional<Integer> qpAsInteger(Request req, String paramName) { // return qpAsMappedValue(req, paramName, p -> Integer.parseInt(p)); // } // public static Optional<List<Integer>> qpAsListOfIntegers(Request req, String paramName) { // return qpAsListOfMappedValue(req, paramName, p -> Integer.parseInt(p)); // } // // // // public static Optional<Float> qpAsFloat(Request req, String paramName) { // return qpAsMappedValue(req, paramName, p -> Float.parseFloat(p)); // } // public static Optional<List<Float>> qpAsListOfFloat(Request req, String paramName) { // return qpAsListOfMappedValue(req, paramName, p -> Float.parseFloat(p)); // } // // // // public static Optional<Double> qpAsDouble(Request req, String paramName) { // return qpAsMappedValue(req, paramName, p -> Double.parseDouble(p)); // } // public static Optional<List<Double>> qpAsListOfDouble(Request req, String paramName) { // return qpAsListOfMappedValue(req, paramName, p -> Double.parseDouble(p)); // } // // // public static Optional<Boolean> qpAsBoolean(Request req, String paramName) { // return qpAsMappedValue(req, paramName, p -> Boolean.parseBoolean(p)); // } // public static Optional<List<Boolean>> qpAsListOfBoolean(Request req, String paramName) { // return qpAsListOfMappedValue(req, paramName, p -> Boolean.parseBoolean(p)); // } // // // public static <T> Optional<T> qpAsMappedValue(Request req, String paramName, Function<String, T> mapper) { // return asString(req, paramName).map(mapper); // } // // public static <T> Optional<List<T>> qpAsListOfMappedValue(Request req, String paramName, Function<String, T> mapper) { // return asListOfStrings(req, paramName).map(ps -> ps.stream().map(mapper).collect(Collectors.toList())); // } // //}
36.260274
122
0.685304
de40ea7e6fcd285e0cec83bbd261df755627baa4
981
/* * Copyright 2021 ROCKSEA. All rights Reserved. * ROCKSEA PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package kr.co.sample.member.domain.query; import org.springframework.stereotype.Service; import kr.co.sample.member.domain.Member; import kr.co.sample.member.domain.repository.MemberNewRepository; @Service public class MemberNewQuery { private final MemberNewRepository memberNewRepository; public MemberNewQuery(MemberNewRepository memberNewRepository) { this.memberNewRepository = memberNewRepository; } public MemberQueryResult getMemberById(Integer id) { Member member = memberNewRepository.findMemberById(id); MemberQueryResult memberQueryResult = MemberQueryResult.builder() .id(member.getId()) .name(member.getName()) .age(member.getAge()) .build(); return memberQueryResult; } }
31.645161
69
0.67686
559cc53e63f09caafeae46f9357b57d4bab189b7
8,124
package gov.nist.javax.sip.address; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * 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% */ public class SipUri extends GenericURI implements SipURIExt, javax.sip.address.SipURI { // Fields protected Authority authority; protected gov.nist.core.NameValueList uriParms; protected gov.nist.core.NameValueList qheaders; protected TelephoneNumber telephoneSubscriber; // Constructors public SipUri(){ super(); } // Methods public boolean equals(java.lang.Object arg1){ return false; } public java.lang.String toString(){ return (java.lang.String) null; } public java.lang.Object clone(){ return (java.lang.Object) null; } public java.lang.String encode(){ return (java.lang.String) null; } public java.lang.StringBuffer encode(java.lang.StringBuffer arg1){ return (java.lang.StringBuffer) null; } @com.francetelecom.rd.stubs.annotation.FieldGet("method") public java.lang.String getMethod(){ return (java.lang.String) null; } @com.francetelecom.rd.stubs.annotation.FieldGet("authority") public Authority getAuthority(){ return (Authority) null; } @com.francetelecom.rd.stubs.annotation.FieldGet("scheme") public java.lang.String getScheme(){ return (java.lang.String) null; } @com.francetelecom.rd.stubs.annotation.FieldGet("host") public java.lang.String getHost(){ return (java.lang.String) null; } public int getPort(){ return 0; } public void setMethod(@com.francetelecom.rd.stubs.annotation.FieldSet("method") java.lang.String arg1){ } public gov.nist.core.NameValueList getParameters(){ return (gov.nist.core.NameValueList) null; } public boolean isSipURI(){ return false; } public void setIsdnSubAddress(java.lang.String arg1){ } public java.lang.String getParameter(java.lang.String arg1){ return (java.lang.String) null; } public void setParameter(java.lang.String arg1, java.lang.String arg2) throws java.text.ParseException{ } public java.util.Iterator<java.lang.String> getParameterNames(){ return (java.util.Iterator) null; } public void removeParameter(java.lang.String arg1){ } public void setSecure(boolean arg1){ } public boolean isSecure(){ return false; } @com.francetelecom.rd.stubs.annotation.FieldGet("hostPort") public gov.nist.core.HostPort getHostPort(){ return (gov.nist.core.HostPort) null; } public void setScheme(@com.francetelecom.rd.stubs.annotation.FieldSet("scheme") java.lang.String arg1){ } public void removeParameters(){ } public boolean hasParameter(java.lang.String arg1){ return false; } public void setHeader(java.lang.String arg1, java.lang.String arg2){ } public void removeHeader(java.lang.String arg1){ } public void removeHeaders(){ } public void setHost(gov.nist.core.Host arg1){ } public void setHost(@com.francetelecom.rd.stubs.annotation.FieldSet("host") java.lang.String arg1) throws java.text.ParseException{ } public java.lang.String getHeader(java.lang.String arg1){ return (java.lang.String) null; } public java.util.Iterator<java.lang.String> getHeaderNames(){ return (java.util.Iterator) null; } @com.francetelecom.rd.stubs.annotation.FieldGet("user") public java.lang.String getUser(){ return (java.lang.String) null; } public void setPort(int arg1){ } public void setUser(@com.francetelecom.rd.stubs.annotation.FieldSet("user") java.lang.String arg1){ } public void clearPassword(){ } public java.lang.String getUserType(){ return (java.lang.String) null; } public void removeUser(){ } public java.lang.String getUserAtHostPort(){ return (java.lang.String) null; } public void removePort(){ } public void setHostPort(@com.francetelecom.rd.stubs.annotation.FieldSet("hostPort") gov.nist.core.HostPort arg1){ } public boolean hasGrParam(){ return false; } public void setGrParam(@com.francetelecom.rd.stubs.annotation.FieldSet("grParam") java.lang.String arg1){ } public void setMAddrParam(@com.francetelecom.rd.stubs.annotation.FieldSet("mAddrParam") java.lang.String arg1) throws java.text.ParseException{ } public void setTransportParam(@com.francetelecom.rd.stubs.annotation.FieldSet("transportParam") java.lang.String arg1) throws java.text.ParseException{ } public void setUserPassword(@com.francetelecom.rd.stubs.annotation.FieldSet("userPassword") java.lang.String arg1){ } @com.francetelecom.rd.stubs.annotation.FieldGet("userPassword") public java.lang.String getUserPassword(){ return (java.lang.String) null; } @com.francetelecom.rd.stubs.annotation.FieldGet("transportParam") public java.lang.String getTransportParam(){ return (java.lang.String) null; } public boolean hasLrParam(){ return false; } public void setUserParam(@com.francetelecom.rd.stubs.annotation.FieldSet("userParam") java.lang.String arg1){ } public java.lang.String getLrParam(){ return (java.lang.String) null; } public void setLrParam(){ } @com.francetelecom.rd.stubs.annotation.FieldGet("mAddrParam") public java.lang.String getMAddrParam(){ return (java.lang.String) null; } public int getTTLParam(){ return 0; } public void setTTLParam(int arg1){ } public boolean hasTransport(){ return false; } @com.francetelecom.rd.stubs.annotation.FieldGet("userParam") public java.lang.String getUserParam(){ return (java.lang.String) null; } public void removeUserType(){ } public java.lang.String getUserAtHost(){ return (java.lang.String) null; } @com.francetelecom.rd.stubs.annotation.FieldGet("methodParam") public java.lang.String getMethodParam(){ return (java.lang.String) null; } public void setMethodParam(@com.francetelecom.rd.stubs.annotation.FieldSet("methodParam") java.lang.String arg1) throws java.text.ParseException{ } public void setMAddr(java.lang.String arg1){ } public void setUriParameter(gov.nist.core.NameValue arg1){ } public void setQHeader(gov.nist.core.NameValue arg1){ } public void clearUriParms(){ } public void clearQheaders(){ } public java.lang.Object getParm(java.lang.String arg1){ return (java.lang.Object) null; } @com.francetelecom.rd.stubs.annotation.FieldGet("qheaders") public gov.nist.core.NameValueList getQheaders(){ return (gov.nist.core.NameValueList) null; } @com.francetelecom.rd.stubs.annotation.FieldGet("telephoneSubscriber") public TelephoneNumber getTelephoneSubscriber(){ return (TelephoneNumber) null; } public boolean isUserTelephoneSubscriber(){ return false; } public void removeTTL(){ } public void removeMAddr(){ } public void removeTransport(){ } public void removeMethod(){ } public void setDefaultParm(java.lang.String arg1, java.lang.Object arg2){ } public void setAuthority(@com.francetelecom.rd.stubs.annotation.FieldSet("this.authority") Authority arg1){ } public void setUriParms(gov.nist.core.NameValueList arg1){ } public void setUriParm(java.lang.String arg1, java.lang.Object arg2){ } public void setQheaders(@com.francetelecom.rd.stubs.annotation.FieldSet("this.qheaders") gov.nist.core.NameValueList arg1){ } public void setTelephoneSubscriber(@com.francetelecom.rd.stubs.annotation.FieldSet("this.telephoneSubscriber") TelephoneNumber arg1){ } @com.francetelecom.rd.stubs.annotation.FieldGet("grParam") public java.lang.String getGrParam(){ return (java.lang.String) null; } }
31.366795
153
0.727351
805f148ff05933f0299e87666345135041e84dec
484
package com.lyh.springcolud.consul_client_producer_8009; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class ConsulClientProducer8009Application { public static void main(String[] args) { SpringApplication.run(ConsulClientProducer8009Application.class, args); } }
30.25
79
0.836777
184588566f37461efc67bf85706bf1cc20e5df22
722
package com.hoanghung.profilemanage.entity; import lombok.Data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * Created by hxhung on 8/24/2017. */ @Entity @Table(name = "person") @Data public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Column(name = "pcity") private String city; private String address; private boolean sex; public String toString() { return "Person [pid=" + id + ", pName=" + name + ", pCity=" + city + "]"; } }
19.513514
81
0.691136
6e098d818ccc24ce665142efdab73ae234424ffa
1,508
package questao03.despesa; import java.time.LocalDateTime; public class DespesaComEnergia extends Despesa { private static final double CUSTO_VALOR_KWH = 0.50D; private static final double CUSTO_ADICIONAL_100KWH = 1.20D; private static final double CUSTO_ADICIONAL_ILUMINACAO_0_50 = 2.00D; private static final double CUSTO_ADICIONAL_ILUMINACAO_51_200 = 15.00D; private static final double CUSTO_ADICIONAL_ILUMINACAO_201 = 35.00D; private double kWh; public DespesaComEnergia(LocalDateTime data,String descricao,double kWh) { super(data, descricao); this.setkWh(kWh); } @Override public double calcularTotal() { double valorTotal = 0; //Valor kWh valorTotal += kWh * CUSTO_VALOR_KWH; //Adicional por 100 kWh //Foi usado um artifício de cast aqui, para não utilizar condição valorTotal += ((int) (kWh/100)) * CUSTO_ADICIONAL_100KWH; //Taxa de iluminação pública if (kWh <= 50) valorTotal += CUSTO_ADICIONAL_ILUMINACAO_0_50; else if (kWh <= 200) valorTotal += CUSTO_ADICIONAL_ILUMINACAO_51_200; else valorTotal += CUSTO_ADICIONAL_ILUMINACAO_201; return valorTotal; } public void setkWh(double kWh) { if (kWh >= 0) { this.kWh = kWh; } } @Override public String toString() { return "DespesaComEnergia{" + "kWh=" + kWh + '}'; } }
27.925926
78
0.634615
429ebee82abd3fe53bf3cc48df234fe9c766c74b
1,395
package com.xuxiao415; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } public static int maxTurbulenceSize(int[] arr) { int[] up = new int[arr.length]; int[] down = new int[arr.length]; for (int i = 0; i < arr.length; i++) { up[i] = 1; down[i] =1; } int res = 1; for (int i = 1; i < arr.length; i++) { if (arr[i] > arr[i - 1]) { up[i] = down[i-1] + 1; } else if (arr[i] < arr[i - 1]) { down[i] = up[i-1] + 1; } else { up[i] = 1; down[i] = 1; } res = Math.max(res, Math.max(up[i], down[i])); } return res; } public static int maxTurbulenceSizeNew(int[] arr) { int up = 1; int down = 1; int res = 1; for (int i = 1; i < arr.length; i++) { if (arr[i] > arr[i - 1]) { up = down + 1; down = 1; } else if (arr[i] < arr[i - 1]) { down = up + 1; up = 1; } else { up = 1; down = 1; } res = Math.max(res, Math.max(up, down)); } return res; } }
24.051724
58
0.363441
d0e432c2a267014bb3d5c5c410b1c0aa902a0173
6,600
package net.n2oapp.framework.autotest.action; import net.n2oapp.framework.autotest.N2oSelenide; import net.n2oapp.framework.autotest.api.component.button.StandardButton; import net.n2oapp.framework.autotest.api.component.control.InputText; import net.n2oapp.framework.autotest.api.component.drawer.Drawer; import net.n2oapp.framework.autotest.api.component.modal.Modal; import net.n2oapp.framework.autotest.api.component.page.SimplePage; import net.n2oapp.framework.autotest.api.component.page.StandardPage; import net.n2oapp.framework.autotest.api.component.region.SimpleRegion; import net.n2oapp.framework.autotest.api.component.widget.FormWidget; import net.n2oapp.framework.autotest.api.component.widget.table.TableWidget; import net.n2oapp.framework.autotest.run.AutoTestBase; import net.n2oapp.framework.config.N2oApplicationBuilder; import net.n2oapp.framework.config.metadata.pack.N2oAllDataPack; import net.n2oapp.framework.config.metadata.pack.N2oAllPagesPack; import net.n2oapp.framework.config.metadata.pack.N2oApplicationPack; import net.n2oapp.framework.config.selective.CompileInfo; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Автотест для обновления виджета после закрытия модального окна */ public class RefreshAfterCloseModalAT extends AutoTestBase { @BeforeAll public static void beforeClass() { configureSelenide(); } @BeforeEach @Override public void setUp() throws Exception { super.setUp(); } @Override protected void configure(N2oApplicationBuilder builder) { super.configure(builder); builder.packs(new N2oAllPagesPack(), new N2oApplicationPack(), new N2oAllDataPack()); builder.sources(new CompileInfo("net/n2oapp/framework/autotest/action/close/refresh/index.page.xml"), new CompileInfo("net/n2oapp/framework/autotest/blank.application.xml"), new CompileInfo("net/n2oapp/framework/autotest/action/close/refresh/modal.page.xml")); } @Test public void testModal() { builder.sources(new CompileInfo("net/n2oapp/framework/autotest/action/close/refresh/modal/test.query.xml"), new CompileInfo("net/n2oapp/framework/autotest/action/close/refresh/modal/test.object.xml")); StandardPage page = open(StandardPage.class); page.breadcrumb().titleShouldHaveText("Обновление виджета после закрытия модального окна"); page.shouldExists(); TableWidget.Rows rows = page.regions().region(0, SimpleRegion.class).content() .widget(0, TableWidget.class).columns().rows(); rows.shouldHaveSize(4); StandardButton modalBtn = page.regions().region(0, SimpleRegion.class).content() .widget(1, FormWidget.class).toolbar().topLeft().button("Modal"); modalBtn.click(); Modal modalPage = N2oSelenide.modal(); modalPage.shouldExists(); FormWidget modalForm = modalPage.content(SimplePage.class).widget(FormWidget.class); StandardButton saveBtn = modalForm.toolbar().bottomLeft().button("Save"); StandardButton closeBtn = modalForm.toolbar().bottomLeft().button("Close"); InputText inputText = modalForm.fields().field("name").control(InputText.class); // close by button inputText.val("new1"); saveBtn.click(); closeBtn.click(); rows.shouldHaveSize(5); rows.row(0).cell(1).textShouldHave("new1"); // close by cross icon modalBtn.click(); modalPage.shouldExists(); inputText.val("new2"); saveBtn.click(); modalPage.close(); rows.shouldHaveSize(6); rows.row(0).cell(1).textShouldHave("new2"); // close by ESC button modalBtn.click(); modalPage.shouldExists(); inputText.val("new3"); saveBtn.click(); modalPage.closeByEsc(); rows.shouldHaveSize(7); rows.row(0).cell(1).textShouldHave("new3"); // close by click backdrop modalBtn.click(); modalPage.shouldExists(); inputText.val("new4"); saveBtn.click(); modalPage.clickBackdrop(); rows.shouldHaveSize(8); rows.row(0).cell(1).textShouldHave("new4"); } @Test public void testDrawer() { builder.sources(new CompileInfo("net/n2oapp/framework/autotest/action/close/refresh/drawer/test.query.xml"), new CompileInfo("net/n2oapp/framework/autotest/action/close/refresh/drawer/test.object.xml")); StandardPage page = open(StandardPage.class); page.breadcrumb().titleShouldHaveText("Обновление виджета после закрытия модального окна"); page.shouldExists(); TableWidget.Rows rows = page.regions().region(0, SimpleRegion.class).content() .widget(0, TableWidget.class).columns().rows(); rows.shouldHaveSize(4); StandardButton drawerBtn = page.regions().region(0, SimpleRegion.class).content() .widget(1, FormWidget.class).toolbar().topLeft().button("Drawer"); drawerBtn.click(); Drawer drawerPage = N2oSelenide.drawer(); drawerPage.shouldExists(); FormWidget modalForm = drawerPage.content(SimplePage.class).widget(FormWidget.class); StandardButton saveBtn = modalForm.toolbar().bottomLeft().button("Save"); StandardButton closeBtn = modalForm.toolbar().bottomLeft().button("Close"); InputText inputText = modalForm.fields().field("name").control(InputText.class); // close by button inputText.val("new1"); saveBtn.click(); closeBtn.click(); rows.shouldHaveSize(5); rows.row(0).cell(1).textShouldHave("new1"); // close by cross icon drawerBtn.click(); drawerPage.shouldExists(); inputText.val("new2"); saveBtn.click(); drawerPage.close(); rows.shouldHaveSize(6); rows.row(0).cell(1).textShouldHave("new2"); // close by ESC button drawerBtn.click(); drawerPage.shouldExists(); inputText.val("new3"); saveBtn.click(); drawerPage.closeByEsc(); rows.shouldHaveSize(7); rows.row(0).cell(1).textShouldHave("new3"); // close by click backdrop drawerBtn.click(); drawerPage.shouldExists(); inputText.val("new4"); saveBtn.click(); drawerPage.clickBackdrop(); rows.shouldHaveSize(8); rows.row(0).cell(1).textShouldHave("new4"); } }
37.931034
116
0.673636
d0ea4b766cb9e560784525c65a2b7775c6a74968
254
package jlssrc.annotations; class OneElement { @interface A { String value(); } @A("foo") Object annotated1; @A(value = "foo") Object annotated2; @A(true ? "foo" : "bar") Object valueIsConditionalExpression; }
14.941176
40
0.590551
9459d963540fe01a15d147db9a3c20de92b00d86
3,172
/*- * ---license-start * European Digital COVID Certificate Booking Demo / dgca-booking-demo-backend * --- * Copyright (C) 2021 T-Systems International GmbH and all other contributors * --- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ---license-end */ package eu.europa.ec.dgc.booking.controller; import eu.europa.ec.dgc.booking.dto.ResultStatusRequest; import eu.europa.ec.dgc.booking.service.BookingService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import javax.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @Slf4j @RestController @RequiredArgsConstructor public class ResultController { private static final String PATH = "/result/{subject}"; private final BookingService bookingService; /** * Receives the DCC Status of an subject from the validation decorator and update the passenger. * * @param passengerId Subject * @param result {@link ResultStatusRequest} */ @Operation(summary = "Result Route (private)", description = "Result Route (private)") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Bad Request / Validation errors"), @ApiResponse(responseCode = "404", description = "Not Found"), @ApiResponse(responseCode = "415", description = "Unsupported Media Type"), @ApiResponse(responseCode = "500", description = "Internal Server Error"), @ApiResponse(responseCode = "501", description = "Not Implemented") }) @ResponseStatus(code = HttpStatus.OK) @PutMapping(path = PATH, consumes = MediaType.APPLICATION_JSON_VALUE) public void resultSubject( @PathVariable(value = "subject", required = true) final String passengerId, @Valid @RequestBody final ResultStatusRequest result) { log.debug("Incoming PUT request to '{}' with passenger ID '{}' and content '{}'", PATH, passengerId, result); final int updateCount = bookingService.updateResult(passengerId, result); log.debug("Update '{}' passengers", updateCount); } }
42.864865
117
0.734552
a986fdd5386e91f761d830cf5741399d5aa6ba9d
867
package min15.structure; import node.AClassDef; import java.math.BigInteger; import java.util.*; /** * Created by Antoine-Ali on 18/02/2015. */ public class IntegerClassInfo extends ClassInfo { private final Map<BigInteger, Instance> _valueMap = new LinkedHashMap<>(); public IntegerClassInfo(ClassTable classTable, AClassDef definition) { super(classTable, definition); } @Override public Instance NewInstance() { throw new RuntimeException("Invalid Integer Instance Creation"); } public Instance NewInteger(BigInteger value) { Instance instance = this._valueMap.get(value); if (instance == null) { instance = new IntegerInstance(this, value); this._valueMap.put(value, instance); } return instance; } }
23.432432
79
0.633218
af460654e455726e87a4e503662a276165b5852c
7,278
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dx.mockito.inline; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.util.concurrent.WeakConcurrentMap; import org.mockito.internal.util.concurrent.WeakConcurrentSet; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.ProtectionDomain; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import java.util.Set; /** * Adds entry hooks (that eventually call into * {@link MockMethodAdvice#handle(Object, Method, Object[])} to all non-abstract methods of the * supplied classes. * * <p></p>Transforming a class to adding entry hooks follow the following simple steps: * <ol> * <li>{@link #mockClass(MockFeatures)}</li> * <li>{@link JvmtiAgent#requestTransformClasses(Class[])}</li> * <li>{@link JvmtiAgent#nativeRetransformClasses(Class[])}</li> * <li>agent.cc::Transform</li> * <li>{@link JvmtiAgent#runTransformers(ClassLoader, String, Class, ProtectionDomain, byte[])}</li> * <li>{@link #transform(Class, byte[])}</li> * <li>{@link #nativeRedefine(String, byte[])}</li> * </ol> * */ class ClassTransformer { // Some classes are so deeply optimized inside the runtime that they cannot be transformed private static final Set<Class<? extends java.io.Serializable>> EXCLUDES = new HashSet<>( Arrays.asList(Class.class, Boolean.class, Byte.class, Short.class, Character.class, Integer.class, Long.class, Float.class, Double.class, String.class)); private final static Random random = new Random(); /** Jvmti agent responsible for triggering transformation s*/ private final JvmtiAgent agent; /** Types that have already be transformed */ private final WeakConcurrentSet<Class<?>> mockedTypes; /** * A unique identifier that is baked into the transformed classes. The entry hooks will then * pass this identifier to * {@code com.android.dx.mockito.inline.MockMethodDispatcher#get(String, Object)} to * find the advice responsible for handling the method call interceptions. */ private final String identifier; /** * We can only have a single transformation going on at a time, hence synchronize the * transformation process via this lock. * * @see #mockClass(MockFeatures) */ private final static Object lock = new Object(); /** * Create a new generator. * * Creating more than one generator might cause transformations to overwrite each other. * * @param agent agent used to trigger transformations * @param dispatcherClass {@code com.android.dx.mockito.inline.MockMethodDispatcher} * that will dispatch method calls that might need to get intercepted. * @param mocks list of mocked objects. As all objects of a class use the same transformed * bytecode the {@link MockMethodAdvice} needs to check this list if a object is * mocked or not. */ ClassTransformer(JvmtiAgent agent, Class dispatcherClass, WeakConcurrentMap<Object, InvocationHandlerAdapter> mocks) { this.agent = agent; mockedTypes = new WeakConcurrentSet<>(WeakConcurrentSet.Cleaner.INLINE); identifier = Long.toString(random.nextLong()); MockMethodAdvice advice = new MockMethodAdvice(mocks); try { dispatcherClass.getMethod("set", String.class, Object.class).invoke(null, identifier, advice); } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { throw new IllegalStateException(e); } agent.addTransformer(this); } /** * Trigger the process to add entry hooks to a class (and all its parents). * * @param features specification what to mock */ <T> void mockClass(MockFeatures<T> features) { boolean subclassingRequired = !features.interfaces.isEmpty() || Modifier.isAbstract(features.mockedType.getModifiers()); if (subclassingRequired && !features.mockedType.isArray() && !features.mockedType.isPrimitive() && Modifier.isFinal(features.mockedType.getModifiers())) { throw new MockitoException("Unsupported settings with this type '" + features.mockedType.getName() + "'"); } synchronized (lock) { Set<Class<?>> types = new HashSet<>(); Class<?> type = features.mockedType; do { boolean wasAdded = mockedTypes.add(type); if (wasAdded) { if (!EXCLUDES.contains(type)) { types.add(type); } type = type.getSuperclass(); } else { break; } } while (type != null && !type.isInterface()); if (!types.isEmpty()) { try { agent.requestTransformClasses(types.toArray(new Class<?>[types.size()])); } catch (UnmodifiableClassException exception) { for (Class<?> failed : types) { mockedTypes.remove(failed); } throw new MockitoException("Could not modify all classes " + types, exception); } } } } /** * Add entry hooks to all methods of a class. * * <p>Called by the agent after triggering the transformation via * {@link #mockClass(MockFeatures)}. * * @param classBeingRedefined class the hooks should be added to * @param classfileBuffer original byte code of the class * * @return transformed class */ @SuppressWarnings("unused") public byte[] transform(Class<?> classBeingRedefined, byte[] classfileBuffer) throws IllegalClassFormatException { if (classBeingRedefined == null || !mockedTypes.contains(classBeingRedefined)) { return null; } else { try { return nativeRedefine(identifier, classfileBuffer); } catch (Throwable throwable) { throw new IllegalClassFormatException(); } } } private native byte[] nativeRedefine(String identifier, byte[] original); }
37.90625
100
0.620775
86fb539cf115cb80f358a3eda49480a9b011a9d0
1,162
package edu.diku.pyprob_java.distributions; import ch.ethz.idsc.tensor.Tensor; import ppx.Distribution; import edu.diku.pyprob_java.MessageHandler; public class Weibull implements TensorDistribution { private Tensor scale; private Tensor concentration; public Weibull(Tensor scale, Tensor concentration) { this.scale = scale; this.concentration = concentration; } public Tensor getScale() { return scale; } public void setScale(Tensor scale) { this.scale = scale; } public Tensor getConcentration() { return concentration; } public void setConcentration(Tensor concentration) { this.concentration = concentration; } @Override public byte fbDistType() { return Distribution.Weibull; } @Override public int fbCreateDist(MessageHandler messageHandler) { var builder = messageHandler.getBuilder(); var mScale = messageHandler.protocolTensor(this.scale); var mConcentration = messageHandler.protocolTensor(this.concentration); return ppx.Weibull.createWeibull(builder, mScale, mConcentration); } }
25.822222
79
0.693632
63d1c1d7cde6b73239430d46036373fc7c09f8a7
874
package uk.ac.manchester.sisp.punch.ui; public interface IUIPadding { public static IUIPadding PADDING_NULL = new IUIPadding() { /* Define negligible padding. */ @Override public int getPadding() { return 0; } }; public static class Impl implements IUIPadding.W { /* Member Variables. */ private int mPadding; /* Constructor. */ public Impl() { this(0); } /* Constructor. */ public Impl(final int pPadding) { this.mPadding = pPadding; } /* Getters and Setters. */ public void setPadding(final int pPadding) { this.mPadding = pPadding; } public int getPadding() { return this.mPadding; } } public static interface W extends IUIPadding { public abstract void setPadding(final int pPadding); } /* Returns the internal padding to be applied to a specific graphical component. */ public abstract int getPadding(); }
23
84
0.691076
22d807864b2889056833dc13a68e40f0f49dfb6f
1,137
/* * Copyright (C) 2015 备胎金服 * 未经授权允许不得进行拷贝和修改 * http://www.btjf.com/ */ package com.zxf.pintu.utils; import android.graphics.Bitmap; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Created by zhangman on 16/3/26 11:31. * Email: zhangman523@126.com */ public class ImageSplitter { public static final String TAG = "ImageSplitter"; /** * 将图片切成,piece*piece */ public static List<ImagePiece> split(Bitmap bitmap, int piece) { List<ImagePiece> pieces = new ArrayList<ImagePiece>(piece * piece); int width = bitmap.getWidth(); int height = bitmap.getHeight(); int pieceWidth = Math.min(width, height) / piece; Log.e(TAG, "imagePiece.index" + (piece)); for (int i = 0; i < piece; i++) { for (int j = 0; j < piece; j++) { ImagePiece imagePiece = new ImagePiece(); int xValue = j * pieceWidth; int yValue = i * pieceWidth; imagePiece.index = j + i * piece; imagePiece.bitmap = Bitmap.createBitmap(bitmap, xValue, yValue, pieceWidth, pieceWidth); pieces.add(imagePiece); } } return pieces; } }
27.071429
96
0.638522
2b54a6c3ba935e4db278c609451574ecd3a95f31
131
class pattern7 { public static void main(String args[]) { int x; x=50; x=(++x)+(++x)*(x++)+x; System.out.println(x); } }
11.909091
39
0.549618
265d4683c48d8aeac6b05e8824647c1aa49b8797
353
package ph.hatch.d3.infrastructure.event.publisher.simple; import ph.hatch.ddd.domain.DomainEvent; public class TestEvent extends DomainEvent { private String message; public TestEvent(String message) { this.message = message; } @Override public String toString() { return this.message; } }
19.611111
59
0.657224
d45a289b4ae579c4c2259f4c34386acb9a6665f1
3,806
package com.inari.firefly.control.behavior; import java.util.Set; import com.inari.commons.JavaUtils; import com.inari.commons.lang.aspect.IAspects; import com.inari.commons.lang.list.IntBag; import com.inari.firefly.FFInitException; import com.inari.firefly.control.action.EntityActionSystem; import com.inari.firefly.entity.EntityActivationEvent; import com.inari.firefly.entity.EntityActivationListener; import com.inari.firefly.system.FFContext; import com.inari.firefly.system.UpdateEvent; import com.inari.firefly.system.UpdateEventListener; import com.inari.firefly.system.component.ComponentSystem; import com.inari.firefly.system.component.SystemBuilderAdapter; import com.inari.firefly.system.component.SystemComponent.SystemComponentKey; import com.inari.firefly.system.component.SystemComponentMap; import com.inari.firefly.system.external.FFTimer; public final class BehaviorSystem extends ComponentSystem<BehaviorSystem> implements UpdateEventListener, EntityActivationListener { public static final FFSystemTypeKey<BehaviorSystem> SYSTEM_KEY = FFSystemTypeKey.create( BehaviorSystem.class ); private static final Set<SystemComponentKey<?>> SUPPORTED_COMPONENT_TYPES = JavaUtils.<SystemComponentKey<?>>unmodifiableSet( BehaviorNode.TYPE_KEY ); private final SystemComponentMap<BehaviorNode> behaviorNodes; private final IntBag entityIds; private EntityActionSystem actionSystem; BehaviorSystem() { super( SYSTEM_KEY ); behaviorNodes = new SystemComponentMap<>( this, BehaviorNode.TYPE_KEY, 20, 10 ); entityIds = new IntBag( 50, -1 ); } @Override public final void init( final FFContext context ) throws FFInitException { super.init( context ); actionSystem = context.getSystem( EntityActionSystem.SYSTEM_KEY ); context.registerListener( UpdateEvent.TYPE_KEY, this ); context.registerListener( EntityActivationEvent.TYPE_KEY, this ); } public final Set<SystemComponentKey<?>> supportedComponentTypes() { return SUPPORTED_COMPONENT_TYPES; } public final Set<SystemBuilderAdapter<?>> getSupportedBuilderAdapter() { return JavaUtils.<SystemBuilderAdapter<?>>unmodifiableSet( behaviorNodes.getBuilderAdapter() ); } public final boolean match( final IAspects aspects ) { return aspects.contains( EBehavoir.TYPE_KEY ); } public final void entityActivated( int entityId, final IAspects aspects ) { entityIds.add( entityId ); } public final void entityDeactivated( int entityId, final IAspects aspects ) { entityIds.remove( entityId ); } public final void update( final FFTimer timer ) { final int nullValue = entityIds.getNullValue(); for ( int i = 0; i < entityIds.length(); i++ ) { final int entityId = entityIds.get( i ); if ( nullValue == entityId ) { continue; } final EBehavoir behavior = context.getEntityComponent( entityId, EBehavoir.TYPE_KEY ); if ( behavior.runningActionId < 0 ) { behaviorNodes.get( behavior.getRootNodeId() ).nextAction( entityId, behavior, context ); } if ( behavior.runningActionId >= 0 ) { actionSystem.performAction( behavior.runningActionId, entityId ); } } } public final void dispose( final FFContext context ) { clearSystem(); context.disposeListener( UpdateEvent.TYPE_KEY, this ); context.disposeListener( EntityActivationEvent.TYPE_KEY, this ); actionSystem = null; } public final void clearSystem() { behaviorNodes.clear(); } }
37.313725
132
0.695481
07b279d9a739ebef29bddcf3289614dc17b6a487
4,442
/******************************************************************************* * Copyright (c) 2000, 2015 IBM Corporation and others. * 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 * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui.launcher; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class NameValuePairDialog extends Dialog { private String fName; private String fValue; private String fTitle; private String[] fFieldLabels; private String[] fInitialValues; private Label fNameLabel; private Text fNameText; private Label fValueLabel; private Text fValueText; public NameValuePairDialog(Shell shell, String title, String[] fieldLabels, String[] initialValues) { super(shell); fTitle = title; fFieldLabels = fieldLabels; fInitialValues = initialValues; } /** * @see Dialog#createDialogArea(Composite) */ @Override protected Control createDialogArea(Composite parent) { Font font = parent.getFont(); Composite comp = (Composite) super.createDialogArea(parent); ((GridLayout) comp.getLayout()).numColumns = 2; fNameLabel = new Label(comp, SWT.NONE); fNameLabel.setText(fFieldLabels[0]); fNameLabel.setFont(font); ModifyListener listener = new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updateButtons(); } }; fNameText = new Text(comp, SWT.BORDER | SWT.SINGLE); fNameText.setText(fInitialValues[0]); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.widthHint = 300; fNameText.setLayoutData(gd); fNameText.setFont(font); fNameText.addModifyListener(listener); fValueLabel = new Label(comp, SWT.NONE); fValueLabel.setText(fFieldLabels[1]); fValueLabel.setFont(font); fValueText = new Text(comp, SWT.BORDER | SWT.SINGLE); fValueText.setText(fInitialValues[1]); gd = new GridData(GridData.FILL_HORIZONTAL); gd.widthHint = 300; fValueText.setLayoutData(gd); fValueText.setFont(font); fValueText.addModifyListener(listener); applyDialogFont(comp); return comp; } /** * Return the name/value pair entered in this dialog. If the cancel button was hit, * both will be <code>null</code>. */ public String[] getNameValuePair() { return new String[] { fName, fValue }; } /** * @see Dialog#buttonPressed(int) */ @Override protected void buttonPressed(int buttonId) { if (buttonId == IDialogConstants.OK_ID) { fName = fNameText.getText().trim(); fValue = fValueText.getText().trim(); } else { fName = null; fValue = null; } super.buttonPressed(buttonId); } /** * @see Window#configureShell(Shell) */ @Override protected void configureShell(Shell shell) { super.configureShell(shell); if (fTitle != null) { shell.setText(fTitle); } } /** * Enable the OK button if valid input */ protected void updateButtons() { String name = fNameText.getText().trim(); String value = fValueText.getText().trim(); getButton(IDialogConstants.OK_ID).setEnabled((name.length() > 0) && (value.length() > 0)); } /** * Enable the buttons on creation. */ @Override public void create() { super.create(); updateButtons(); } }
30.424658
106
0.628771
a159fbf3c3c8617ddecb5bad54ebb376fd86e14a
2,779
package pl.cyfronet.datanet.deployer; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.zip.ZipException; import org.apache.commons.io.FileUtils; public class ZipByteArrayMapperBuilder implements MapperBuilder { private static final String MODEL_DIR_NAME_DEFAULT = "model"; private static final String TOKEN_FILE_PATH = "config/.secret"; private File outputDir; private File mapperDir; private File modelDir; private byte [] buffer; /** * * @param zipData ByteArray containing zip data. * @param outputDir Directory in which the archive will be extracted. This directory will be created if it does not exist and will be removed on cleanup. * @param mapperDirName Name of the mapper directory which is a subdirectory of the outputDir. */ public ZipByteArrayMapperBuilder(byte[] zipData, File outputDir, String mapperDirName) { this(zipData, outputDir, mapperDirName, null); } /** * * @param zipData ByteArray containing zip data. * @param outputDir Directory in which the archive will be extracted. This directory will be created if it does not exist and will be removed on cleanup. * @param mapperDirName Name of the mapper directory which is a subdirectory of the outputDir. * @param modelDirName Name of the directory in which the model files will be placed. */ public ZipByteArrayMapperBuilder(byte[] zipData, File outputDir, String mapperDirName, String modelDirName) { super(); this.buffer = zipData; this.outputDir = outputDir; this.mapperDir = new File(outputDir, mapperDirName); if (modelDirName == null) modelDirName = MODEL_DIR_NAME_DEFAULT; this.modelDir = new File(mapperDir, modelDirName); } @Override public File buildMapper(Map<String, String> models) throws ZipException, IOException { Unzip.extractOverridingAll(new ByteArrayInputStream(buffer), outputDir); if (!mapperDir.exists() || !mapperDir.isDirectory()) throw new IllegalStateException("Mapper directory does not exist: " + mapperDir.getAbsolutePath()); if (!modelDir.exists() || !modelDir.isDirectory()) throw new IllegalStateException("Model directory does not exist: " + modelDir.getAbsolutePath()); for (Entry<String, String> model : models.entrySet()) { String modelFileName = String.format("%s.json", model.getKey()); File modelFile = new File(modelDir, modelFileName); FileUtils.writeStringToFile(modelFile, model.getValue()); } return mapperDir; } @Override public void deleteMapper() { FileUtils.deleteQuietly(mapperDir); } @Override public void writeToken(String token) throws IOException { FileUtils.writeStringToFile(new File(mapperDir, TOKEN_FILE_PATH), token); } }
35.628205
154
0.756387
d4f17d79c94a9eab32e9c745bfbab301077918b2
4,604
package com.ustudy.info.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty.Access; public class Examinee implements Serializable { /** * */ private static final long serialVersionUID = 1646823396136227256L; private long id = 0; private String stuName = null; private String stuId = null; private String examCode = null; private long examId = 0; private String schId = null; private long gradeId = 0; private long classId = 0; private String className = null; // sub ids selected for the examinee private List<Long> subs = null; // subjects names separated by ',' @JsonIgnore private String subN = null; // subject ids separated by ',' @JsonIgnore private String subI = null; @JsonProperty(value = "subNames", access = Access.READ_ONLY) private List<String> subDetails = null; public Examinee() { super(); // TODO Auto-generated constructor stub } public Examinee(String stuName, String stuId, String stuExamId, long examId, long gradeId, long classId, List<Long> subs) { super(); this.stuName = stuName; this.stuId = stuId; this.examCode = stuExamId; this.examId = examId; this.gradeId = gradeId; this.classId = classId; this.subs = subs; } public Examinee(String stuName, String stuId, String stuExamId, long examId, String schId, long gradeId, long classId, String className) { super(); this.stuName = stuName; this.stuId = stuId; this.examCode = stuExamId; this.examId = examId; this.schId = schId; this.gradeId = gradeId; this.classId = classId; this.className = className; } public Examinee(int id, String stuName, String stuId, String stuExamId, long examId, String schId, long gradeId, long classId, String className) { super(); this.id = id; this.stuName = stuName; this.stuId = stuId; this.examCode = stuExamId; this.examId = examId; this.schId = schId; this.gradeId = gradeId; this.classId = classId; this.className = className; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getExamId() { return examId; } public long getGradeId() { return gradeId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public String getStuId() { return stuId; } public void setStuId(String stuId) { this.stuId = stuId; } public String getExamCode() { return examCode; } public void setExamCode(String examCode) { this.examCode = examCode; } public long getClassId() { return classId; } public void setClassId(long classId) { this.classId = classId; } public void setExamId(long examId) { this.examId = examId; } public void setGradeId(long gradeId) { this.gradeId = gradeId; } public String getSchId() { return schId; } public void setSchId(String schId) { this.schId = schId; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public List<Long> getSubs() { return subs; } public void setSubs(List<Long> subs) { this.subs = subs; // only set for creating examinees if (subs != null && subs.size() > 0) { this.subI = subs.toString(); } } public List<String> getSubDetails() { return subDetails; } public void setSubDetails(List<String> subDetails) { this.subDetails = subDetails; } public String getSubN() { return subN; } public void setSubN(String subN) { this.subN = subN; if (this.subN != null && this.subN.length() > 0) { this.subDetails = new ArrayList<String>(); String [] datas = this.subN.split(","); for (String da: datas) { this.subDetails.add(da); } } } public String getSubI() { return subI; } public void setSubI(String subI) { this.subI = subI; if (this.subI != null && this.subI.length() > 0) { this.subs = new ArrayList<Long>(); String [] datas = this.subI.split(","); for (String da: datas) { this.subs.add(Long.valueOf(da)); } } } @Override public String toString() { return "Examinee [id=" + id + ", stuName=" + stuName + ", stuId=" + stuId + ", examCode=" + examCode + ", examId=" + examId + ", schId=" + schId + ", gradeId=" + gradeId + ", classId=" + classId + ", className=" + className + ", subs=" + subs + ", subN=" + subN + ", subI=" + subI + ", subDetails=" + subDetails + "]"; } }
21.022831
107
0.67159
dfd40f555de7c458ee87e243fc1898bf43fd2ad2
2,461
package airbrake; import java.util.HashMap; import java.util.Map; import org.apache.wicket.Session; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.Url; import org.apache.wicket.request.cycle.RequestCycle; import com.tegonal.wicket.authentication.DbAuthenticatedWebSessionIF; import com.tegonal.wicket.authentication.WebUserIF; public class WicketAirbrakeAppender extends AirbrakeAppender { public AirbrakeNotice newNoticeFor(final Throwable throwable) { AirbrakeNoticeBuilderUsingFilteredSystemProperties noticeBuilder = new AirbrakeNoticeBuilderUsingFilteredSystemProperties( apiKey, backtrace, throwable, env); Session websession = null; try { websession = Session.get(); } catch (WicketRuntimeException | ClassCastException e) { //ok, we tried it all. } if (websession != null) { Map<String, Object> sessiontMap = new HashMap<String, Object>(); for(String attributeName : websession.getAttributeNames()) { sessiontMap.put(attributeName, websession.getAttribute(attributeName)); } noticeBuilder.session(sessiontMap); if(websession instanceof DbAuthenticatedWebSessionIF) { DbAuthenticatedWebSessionIF dbAuthenticatedWebSession = (DbAuthenticatedWebSessionIF) websession; WebUserIF webUser = dbAuthenticatedWebSession.getWebUser(); if (webUser != null) { noticeBuilder.setUser(webUser.getUserIdentification(), webUser.getUserBezeichnung(), webUser.getUserEmail(), webUser.getUserIdentification()); } } } RequestCycle requestCycle = null; try { requestCycle = RequestCycle.get(); } catch(Exception e) { } if(requestCycle != null) { Url url = requestCycle.getRequest().getUrl(); String action = null; String component = null; noticeBuilder.setRequest(url.toString(), component, action); IRequestParameters requestParameters = requestCycle.getRequest().getRequestParameters(); Map<String, Object> requestMap = new HashMap<String, Object>(); for(String paramName : requestParameters.getParameterNames()) { requestMap.put(paramName, requestParameters.getParameterValue(paramName)); } noticeBuilder.request(requestMap); } return noticeBuilder.newNotice(); } }
35.157143
126
0.71028
b27620024917d813ebdcf5f2ee044831ed8311cb
853
/* /* * 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 controller; import dao.DaoCliente; import java.sql.SQLException; import java.util.List; import model.Cliente; /** * * @author edilson */ public class ControleCliente { dao.DaoCliente daoCliente = new DaoCliente(); public void cadastrar(Cliente o) throws SQLException { daoCliente.cadastrar(o); } public void excluir (Integer o) throws SQLException { daoCliente.excluir(o); } public void alterar(Cliente o) throws SQLException { daoCliente.alterar(o); } public List listarTodos() throws SQLException{ return daoCliente.listarTodos(); } }
20.804878
79
0.658851
17a88a917017d70c6e024c13fb4373ba5d7153e5
1,574
package hype; import hype.interfaces.HConstants; public class HColors implements HConstants { public static int[] explode(int clr) { int[] explodedColors = new int[4]; for(int i=0; i<4; ++i) explodedColors[3-i] = (clr >>> (i*8)) & 0xFF; return explodedColors; } public static int merge(int a, int r, int g, int b) { if(a < 0) a = 0; else if(a > 255) a = 255; if(r < 0) r = 0; else if(r > 255) r = 255; if(g < 0) g = 0; else if(g > 255) g = 255; if(b < 0) b = 0; else if(b > 255) b = 255; return (a<<24) | (r<<16) | (g<<8) | b; } public static int setAlpha(int clr, int newClr) { if(newClr < 0) newClr = 0; else if(newClr > 255) newClr = 255; return clr & 0x00FFFFFF | (newClr << 24); } public static int setRed(int clr, int newClr) { if(newClr < 0) newClr = 0; else if(newClr > 255) newClr = 255; return clr & 0xFF00FFFF | (newClr << 16); } public static int setGreen(int clr, int newClr) { if(newClr < 0) newClr = 0; else if(newClr > 255) newClr = 255; return clr & 0xFFFF00FF | (newClr << 8); } public static int setBlue(int clr, int newClr) { if(newClr < 0) newClr = 0; else if(newClr > 255) newClr = 255; return clr & 0xFFFFFF00 | newClr; } public static int getAlpha(int clr) { return clr >>> 24; } public static int getRed(int clr) { return (clr >>> 16) & 255; } public static int getGreen(int clr) { return (clr >>> 8) & 255; } public static int getBlue(int clr) { return clr & 255; } public static boolean isTransparent(int clr) { return (clr & 0xFF000000) == 0; } }
21.561644
54
0.605464
2922cee9afd16bac38625aaac0c433edf98ceb58
776
package ru.vyarus.guice.ext.core.util; import com.google.inject.TypeLiteral; import com.google.inject.matcher.AbstractMatcher; /** * Object class matcher. * Useful to limit post processors appliance scope by specific package (and sub packages) * * @author Vyacheslav Rusakov * @since 30.06.2014 * @param <T> matched object type */ public class ObjectPackageMatcher<T> extends AbstractMatcher<T> { private final String pkg; public ObjectPackageMatcher(final String pkg) { this.pkg = pkg; } @Override public boolean matches(final T o) { final Class<?> type = o instanceof TypeLiteral ? ((TypeLiteral) o).getRawType() : o.getClass(); return Utils.isPackageValid(type) && type.getPackage().getName().startsWith(pkg); } }
28.740741
103
0.703608
64e31a3907b1ce02ad83dcce44f69ebf4a7adab8
1,995
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2019 Adobe ~ ~ 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.adobe.cq.commerce.core.components.models.productcarousel; import java.util.List; import javax.annotation.Nonnull; import com.adobe.cq.commerce.core.components.models.common.ProductListItem; import com.adobe.cq.commerce.core.components.models.retriever.AbstractProductsRetriever; import com.adobe.cq.wcm.core.components.models.Component; public interface ProductCarousel extends Component { /** * Returns the list of products to be displayed in the carousel. * * @return {@link List} of {@link ProductListItem}s */ @Nonnull List<ProductListItem> getProducts(); @Nonnull List<ProductListItem> getProductIdentifiers(); /** * Returns in instance of the products retriever for fetching product data via GraphQL. * * @return products retriever instance */ AbstractProductsRetriever getProductsRetriever(); /** * Returns true if the component is correctly configured, false otherwise. * * @return true or false */ boolean isConfigured(); /** * Should return the HTML tag type for the component title. * * @return The HTML tag type that should be used to display the component title. */ String getTitleType(); }
33.25
91
0.659649
89ea8a7dd2877961de7c7edbbfd8e1a047b16c11
6,536
package com.mjiayou.trejava.module.test; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.net.URLEncoder; import java.security.MessageDigest; import java.text.CollationKey; import java.text.Collator; import java.text.RuleBasedCollator; import java.util.*; /** * 超级宝项目ApiKey计算算法,两种方式比较 */ public class ApiKeyUtils { private static String KEY_1 = "def", VALUE_1 = "V 2.2.1 debug"; private static String KEY_2 = "abc", VALUE_2 = "44"; private static String KEY_3 = "xyz", VALUE_3 = "123"; public static void main(String[] args) { List<NameValuePair> paramsX = new ArrayList<>(); paramsX.add(new NameValuePair() { @Override public String getName() { return KEY_1; } @Override public String getValue() { return VALUE_1; } }); paramsX.add(new NameValuePair() { @Override public String getName() { return KEY_2; } @Override public String getValue() { return VALUE_2; } }); paramsX.add(new NameValuePair() { @Override public String getName() { return KEY_3; } @Override public String getValue() { return VALUE_3; } }); System.out.println("******************************** xUtils ********************************"); System.out.println("getApiKey(paramsX) -> " + getApiKey(paramsX)); System.out.println("******************************** OkHttp ********************************"); Map<String, String> paramsOK = new TreeMap<>(); paramsOK.put(KEY_1, VALUE_1); paramsOK.put(KEY_2, VALUE_2); paramsOK.put(KEY_3, VALUE_3); System.out.println("getApiKey(paramsOK) -> " + getApiKey(paramsOK)); System.out.println("******************************** END ********************************"); } /** * zoudong * * @param params * @return */ public static String getApiKey(List<NameValuePair> params) { String source = getSource(params); System.out.println("source = " + source); String md5 = md5(source); System.out.println("md5 = " + md5); char[] carr = md5.toCharArray(); return new String(new char[]{carr[20], carr[15], carr[0], carr[3], carr[1], carr[5]}); } private static String getSource(List<NameValuePair> params) { StringBuffer sb = new StringBuffer(); List<NameValuePair> list = getList(params); for (int i = 0; i < list.size(); i++) { NameValuePair nameValuePair = list.get(i); System.out.println(nameValuePair.getName() + " = " + nameValuePair.getValue()); sb.append(nameValuePair.getName()); sb.append("="); if (nameValuePair.getValue() != null) { sb.append(nameValuePair.getValue()); } if (i < list.size() - 1) { sb.append("&"); } else { sb.append("m1K5@BcxUn!"); } } return sb.toString(); } public static List<NameValuePair> getList(List<NameValuePair> list) { /* * 排序 */ if (list == null || list.size() == 0) return null; Collections.sort(list, new Comparator<NameValuePair>() { private RuleBasedCollator collator = (RuleBasedCollator) Collator.getInstance(java.util.Locale.ENGLISH); @Override public int compare(NameValuePair lhs, NameValuePair rhs) { CollationKey c1 = collator.getCollationKey(lhs.getName()); CollationKey c2 = collator.getCollationKey(rhs.getName()); return collator.compare(c1.getSourceString(), c2.getSourceString()); } }); return list; } public static String md5(String sourceStr) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(sourceStr.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); } catch (Exception e) { e.printStackTrace(); } return result; } // ******************************** okhttp ******************************** public static String getApiKey(Map<String, String> params) { String source = getSource(params); System.out.println("source = " + source); String md5 = md5(source); System.out.println("md5 = " + md5); char[] carr = md5.toCharArray(); return new String(new char[]{carr[20], carr[15], carr[0], carr[3], carr[1], carr[5]}); } private static String getSource(Map<String, String> params) { // 对KEY排序 List<String> keyList = new ArrayList<>(params.keySet()); Collections.sort(keyList, new EnglishComparator()); StringBuilder builder = new StringBuilder(); int index = 0; for (String key : keyList) { System.out.println(key + " = " + params.get(key)); builder.append(key); builder.append("="); if (params.get(key) != null) { builder.append(params.get(key)); } if (index < keyList.size() - 1) { builder.append("&"); } else { builder.append("m1K5@BcxUn!"); } index++; } return builder.toString(); } /** * EnglishComparator */ private static class EnglishComparator implements Comparator<String> { private RuleBasedCollator collator = (RuleBasedCollator) Collator.getInstance(java.util.Locale.ENGLISH); public int compare(String o1, String o2) { CollationKey c1 = collator.getCollationKey(o1); CollationKey c2 = collator.getCollationKey(o2); return collator.compare(c1.getSourceString(), c2.getSourceString()); } } }
33.517949
116
0.516524
7f6cf7043486b6172b8393154d1ebeab19f95398
12,118
/* * Copyright (c) 2001 by Matt Welsh and The Regents of the University of * California. All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice and the following * two paragraphs appear in all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Author: Matt Welsh <mdw@cs.berkeley.edu> * */ package seda.sandStorm.core; import seda.sandStorm.api.*; import seda.sandStorm.api.internal.ThreadManagerIF; import java.util.Hashtable; /** * The FiniteQueue class is a simple implementation of the QueueIF * interface, using a linked list. * * @author Matt Welsh * @see seda.sandStorm.api.QueueIF */ public class FiniteQueue implements QueueIF, ProfilableIF { private static final boolean DEBUG = false; private ssLinkedList qlist; private int queueSize; private Object blocker; private Hashtable provisionalTbl; private EnqueuePredicateIF pred; private String name; private boolean closed; private ThreadManagerIF threadmgr; /** * Create a FiniteQueue with the given enqueue predicate, name, and * thread manager. */ public FiniteQueue(EnqueuePredicateIF pred, String name, ThreadManagerIF threadmgr) { this.name = name; this.pred = pred; qlist = new ssLinkedList(); queueSize = 0; blocker = new Object(); provisionalTbl = new Hashtable(1); this.threadmgr = threadmgr; } /** * Create a FiniteQueue with the given enqueue predicate. */ public FiniteQueue(EnqueuePredicateIF pred) { this(pred, null, null); } /** * Create a FiniteQueue with the given enqueue predicate and thread manager. */ public FiniteQueue(EnqueuePredicateIF pred, ThreadManagerIF threadmgr) { this(pred, null, threadmgr); } /** * Create a FiniteQueue with no enqueue predicate. */ public FiniteQueue() { this((EnqueuePredicateIF)null); } /** * Create a FiniteQueue with no enqueue predicate, but inlude a thread * manager. */ public FiniteQueue(ThreadManagerIF threadmgr) { this((EnqueuePredicateIF)null, null, threadmgr); } /** * Create a FiniteQueue with no enqueue or thread manager, but include * the given name. Used for debugging. */ public FiniteQueue(String name) { this((EnqueuePredicateIF)null, name, null); } /** * Create a FiniteQueue with no enqueue, but include a thread manager and * the given name. Used for debugging. */ public FiniteQueue(String name, ThreadManagerIF threadmgr) { this((EnqueuePredicateIF)null, name, threadmgr); } /** * Return the size of the queue. */ public int size() { synchronized(blocker) { synchronized(qlist) { return queueSize; } } } public void enqueue(QueueElementIF enqueueMe) throws SinkException { if (DEBUG) System.err.println("**** ENQUEUE ("+name+") **** Entered"); if( closed ) { throw new SinkClosedException( "This queue is no longer accepting " + " events." ); } synchronized(blocker) { synchronized(qlist) { if (DEBUG) System.err.println("**** ENQUEUE ("+name+") **** Checking pred"); if ((pred != null) && (!pred.accept(enqueueMe))) throw new SinkFullException("FiniteQueue is full!"); queueSize++; if (DEBUG) System.err.println("**** ENQUEUE ("+name+") **** Add to tail"); qlist.add_to_tail(enqueueMe); // wake up one blocker } if (DEBUG) System.err.println("**** ENQUEUE ("+name+") **** Doing notify"); blocker.notifyAll(); } if(threadmgr!=null) threadmgr.wake(); if (DEBUG) System.err.println("**** ENQUEUE ("+name+") **** Exiting"); } public boolean enqueue_lossy(QueueElementIF enqueueMe) { try { this.enqueue(enqueueMe); } catch (Exception e) { return false; } return true; } public void enqueue_many(QueueElementIF[] enqueueMe) throws SinkException { if( closed ) { throw new SinkClosedException( "This queue is no longer accepting " + " events." ); } synchronized(blocker) { int qlen = enqueueMe.length; synchronized(qlist) { if (pred != null) { int i = 0; while ((i < qlen) && (pred.accept(enqueueMe[i]))) i++; if (i != qlen) throw new SinkFullException("FiniteQueue is full!"); } queueSize += qlen; for (int i=0; i<qlen; i++) { qlist.add_to_tail(enqueueMe[i]); } } blocker.notifyAll(); // wake up all sleepers } if(threadmgr!=null) threadmgr.wake(); } public QueueElementIF dequeue() { QueueElementIF el = null; synchronized(blocker) { synchronized(qlist) { if (qlist.size() == 0) return null; el = (QueueElementIF) qlist.remove_head(); queueSize--; return el; } } } public QueueElementIF[] dequeue_all() { synchronized(blocker) { synchronized(qlist) { int qs = qlist.size(); if (qs == 0) return null; QueueElementIF[] retIF = new QueueElementIF[qs]; for (int i=0; i<qs; i++) retIF[i] = (QueueElementIF) qlist.remove_head(); queueSize -= qs; return retIF; } } } public QueueElementIF[] dequeue(int num) { synchronized(blocker) { synchronized(qlist) { int qs = Math.min(qlist.size(), num); if (qs == 0) return null; QueueElementIF[] retIF = new QueueElementIF[qs]; for (int i=0; i<qs; i++) retIF[i] = (QueueElementIF) qlist.remove_head(); queueSize -= qs; return retIF; } } } public QueueElementIF[] dequeue(int num, boolean mustReturnNum) { synchronized(blocker) { synchronized(qlist) { int qs; if (!mustReturnNum) { qs = Math.min(qlist.size(), num); } else { if (qlist.size() < num) return null; qs = num; } if (qs == 0) return null; QueueElementIF[] retIF = new QueueElementIF[qs]; for (int i=0; i<qs; i++) retIF[i] = (QueueElementIF) qlist.remove_head(); queueSize -= qs; return retIF; } } } public QueueElementIF[] blocking_dequeue_all(int timeout_millis) { QueueElementIF[] rets = null; long goal_time; int num_spins = 0; if (DEBUG) System.err.println("**** B_DEQUEUE_A ("+name+") **** Entered"); goal_time = System.currentTimeMillis() + timeout_millis; while (true) { synchronized(blocker) { if (DEBUG) System.err.println("**** B_DEQUEUE_A ("+name+") **** Doing D_A"); rets = this.dequeue_all(); if (DEBUG) System.err.println("**** B_DEQUEUE_A ("+name+") **** RETS IS "+rets); if ((rets != null) || (timeout_millis == 0)) { if (DEBUG) System.err.println("**** B_DEQUEUE_A ("+name+") **** RETURNING (1)"); return rets; } if (timeout_millis == -1) { try { blocker.wait(); } catch (InterruptedException ie) { } } else { try { if (DEBUG) System.err.println("**** B_DEQUEUE_A ("+name+") **** WAITING ON BLOCKER"); blocker.wait(timeout_millis); } catch (InterruptedException ie) { } } if (DEBUG) System.err.println("**** B_DEQUEUE_A ("+name+") **** Doing D_A (2)"); rets = this.dequeue_all(); if (DEBUG) System.err.println("**** B_DEQUEUE_A ("+name+") **** RETS(2) IS "+rets); if (rets != null) { if (DEBUG) System.err.println("**** B_DEQUEUE_A ("+name+") **** RETURNING(2)"); return rets; } if (timeout_millis != -1) { if (System.currentTimeMillis() >= goal_time) { if (DEBUG) System.err.println("**** B_DEQUEUE_A ("+name+") **** RETURNING(3)"); return null; } } } } } public QueueElementIF[] blocking_dequeue(int timeout_millis, int num, boolean mustReturnNum) { QueueElementIF[] rets = null; long goal_time; int num_spins = 0; goal_time = System.currentTimeMillis() + timeout_millis; while (true) { synchronized(blocker) { rets = this.dequeue(num, mustReturnNum); if ((rets != null) || (timeout_millis == 0)) { return rets; } if (timeout_millis == -1) { try { blocker.wait(); } catch (InterruptedException ie) { } } else { try { blocker.wait(timeout_millis); } catch (InterruptedException ie) { } } rets = this.dequeue(num, mustReturnNum); if (rets != null) { return rets; } if (timeout_millis != -1) { if (System.currentTimeMillis() >= goal_time) { // Timeout - take whatever we can get return this.dequeue(num); } } } } } public QueueElementIF[] blocking_dequeue(int timeout_millis, int num) { return blocking_dequeue(timeout_millis, num, false); } public QueueElementIF blocking_dequeue(int timeout_millis) { QueueElementIF rets = null; long goal_time; int num_spins = 0; goal_time = System.currentTimeMillis() + timeout_millis; while (true) { synchronized(blocker) { rets = this.dequeue(); if ((rets != null) || (timeout_millis == 0)) { return rets; } if (timeout_millis == -1) { try { blocker.wait(); } catch (InterruptedException ie) { } } else { try { blocker.wait(timeout_millis); } catch (InterruptedException ie) { } } rets = this.dequeue(); if (rets != null) { return rets; } if (timeout_millis != -1) { if (System.currentTimeMillis() >= goal_time) return null; } } } } /** * Return the profile size of the queue. */ public int profileSize() { return size(); } /** * Provisionally enqueue the given elements. */ public Object enqueue_prepare(QueueElementIF enqueueMe[]) throws SinkException { if( closed ) { throw new SinkClosedException( "This queue is no longer accepting " + " events." ); } int qlen = enqueueMe.length; synchronized(blocker) { synchronized(qlist) { if (pred != null) { int i = 0; while ((i < qlen) && (pred.accept(enqueueMe[i]))) i++; if (i != qlen) throw new SinkFullException("FiniteQueue is full!"); } queueSize += qlen; Object key = new Object(); provisionalTbl.put(key, enqueueMe); return key; } } } /** * Commit a provisional enqueue. */ public void enqueue_commit(Object key) { synchronized(blocker) { synchronized(qlist) { QueueElementIF elements[] = (QueueElementIF[])provisionalTbl.remove(key); if (elements == null) throw new IllegalArgumentException("Unknown enqueue key "+key); for (int i=0; i<elements.length; i++) { qlist.add_to_tail(elements[i]); } } blocker.notifyAll(); } if(threadmgr!=null) threadmgr.wake(); } /** * Abort a provisional enqueue. */ public void enqueue_abort(Object key) { synchronized(blocker) { synchronized(qlist) { QueueElementIF elements[] = (QueueElementIF[])provisionalTbl.remove(key); if (elements == null) throw new IllegalArgumentException("Unknown enqueue key "+key); queueSize -= elements.length; } } } /** * Set the enqueue predicate for this sink. */ public void setEnqueuePredicate(EnqueuePredicateIF pred) { this.pred = pred; } /** * Return the enqueue predicate for this sink. */ public EnqueuePredicateIF getEnqueuePredicate() { return pred; } /** * Indicate that this queue will not be used anymore. Causes an * exception to be thrown every time enqueue is called. */ public void close() { closed = true; } public String toString() { return "FiniteQueue <"+name+">"; } }
24.882957
96
0.639132
af70dd74d7d74b055e656188eeb202989a9f0c18
31,818
package com.cyc.cycjava.cycl; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.UnaryFunction; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.SubLStructDecl; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.CommonSymbols; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.SubLStructDeclNative; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLStructNative; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.ConsesLow; import com.cyc.tool.subl.jrtl.translatedCode.sublisp.visitation; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.Equality; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.SubLSpecialOperatorDeclarations; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.Structures; import com.cyc.tool.subl.jrtl.translatedCode.sublisp.print_high; import com.cyc.tool.subl.util.SubLFiles; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.SubLThread; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLProcess; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory; import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.*; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.Numbers; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.Symbols; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.Functions; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.Errors; import com.cyc.tool.subl.jrtl.translatedCode.sublisp.conses_high; import com.cyc.tool.subl.jrtl.translatedCode.sublisp.compatibility; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObject; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLString; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLList; import com.cyc.tool.subl.jrtl.nativeCode.type.symbol.SubLSymbol; import com.cyc.tool.subl.util.SubLFile; import com.cyc.tool.subl.util.SubLTranslatedFile; public final class module0393 extends SubLTranslatedFile { public static final SubLFile me; public static final String myName = "com.cyc.cycjava.cycl.module0393"; public static final String myFingerPrint = "ca40ebbe75243f028843d4ae937853722381d42b2ca33d4186046f8c39bc2d18"; public static SubLSymbol $g3282$; private static final SubLSymbol $ic0$; private static final SubLSymbol $ic1$; private static final SubLList $ic2$; private static final SubLList $ic3$; private static final SubLList $ic4$; private static final SubLList $ic5$; private static final SubLSymbol $ic6$; private static final SubLSymbol $ic7$; private static final SubLList $ic8$; private static final SubLSymbol $ic9$; private static final SubLSymbol $ic10$; private static final SubLSymbol $ic11$; private static final SubLSymbol $ic12$; private static final SubLSymbol $ic13$; private static final SubLSymbol $ic14$; private static final SubLSymbol $ic15$; private static final SubLSymbol $ic16$; private static final SubLSymbol $ic17$; private static final SubLSymbol $ic18$; private static final SubLSymbol $ic19$; private static final SubLSymbol $ic20$; private static final SubLSymbol $ic21$; private static final SubLSymbol $ic22$; private static final SubLSymbol $ic23$; private static final SubLSymbol $ic24$; private static final SubLSymbol $ic25$; private static final SubLSymbol $ic26$; private static final SubLString $ic27$; private static final SubLSymbol $ic28$; private static final SubLSymbol $ic29$; private static final SubLSymbol $ic30$; private static final SubLSymbol $ic31$; private static final SubLSymbol $ic32$; private static final SubLSymbol $ic33$; private static final SubLSymbol $ic34$; private static final SubLSymbol $ic35$; private static final SubLSymbol $ic36$; private static final SubLSymbol $ic37$; private static final SubLSymbol $ic38$; private static final SubLSymbol $ic39$; public static SubLObject f27961(final SubLObject var1, final SubLObject var2) { compatibility.default_struct_print_function(var1, var2, (SubLObject)ZERO_INTEGER); return (SubLObject)NIL; } public static SubLObject f27962(final SubLObject var1) { return (SubLObject)((var1.getClass() == $sX31090_native.class) ? T : NIL); } public static SubLObject f27963(final SubLObject var1) { assert NIL != f27962(var1) : var1; return var1.getField2(); } public static SubLObject f27964(final SubLObject var1) { assert NIL != f27962(var1) : var1; return var1.getField3(); } public static SubLObject f27965(final SubLObject var1) { assert NIL != f27962(var1) : var1; return var1.getField4(); } public static SubLObject f27966(final SubLObject var1) { assert NIL != f27962(var1) : var1; return var1.getField5(); } public static SubLObject f27967(final SubLObject var1) { assert NIL != f27962(var1) : var1; return var1.getField6(); } public static SubLObject f27968(final SubLObject var1) { assert NIL != f27962(var1) : var1; return var1.getField7(); } public static SubLObject f27969(final SubLObject var1, final SubLObject var4) { assert NIL != f27962(var1) : var1; return var1.setField2(var4); } public static SubLObject f27970(final SubLObject var1, final SubLObject var4) { assert NIL != f27962(var1) : var1; return var1.setField3(var4); } public static SubLObject f27971(final SubLObject var1, final SubLObject var4) { assert NIL != f27962(var1) : var1; return var1.setField4(var4); } public static SubLObject f27972(final SubLObject var1, final SubLObject var4) { assert NIL != f27962(var1) : var1; return var1.setField5(var4); } public static SubLObject f27973(final SubLObject var1, final SubLObject var4) { assert NIL != f27962(var1) : var1; return var1.setField6(var4); } public static SubLObject f27974(final SubLObject var1, final SubLObject var4) { assert NIL != f27962(var1) : var1; return var1.setField7(var4); } public static SubLObject f27975(SubLObject var5) { if (var5 == UNPROVIDED) { var5 = (SubLObject)NIL; } final SubLObject var6 = (SubLObject)new $sX31090_native(); SubLObject var7; SubLObject var8; SubLObject var9; SubLObject var10; for (var7 = (SubLObject)NIL, var7 = var5; NIL != var7; var7 = conses_high.cddr(var7)) { var8 = var7.first(); var9 = conses_high.cadr(var7); var10 = var8; if (var10.eql((SubLObject)$ic21$)) { f27969(var6, var9); } else if (var10.eql((SubLObject)$ic22$)) { f27970(var6, var9); } else if (var10.eql((SubLObject)$ic23$)) { f27971(var6, var9); } else if (var10.eql((SubLObject)$ic24$)) { f27972(var6, var9); } else if (var10.eql((SubLObject)$ic25$)) { f27973(var6, var9); } else if (var10.eql((SubLObject)$ic26$)) { f27974(var6, var9); } else { Errors.error((SubLObject)$ic27$, var8); } } return var6; } public static SubLObject f27976(final SubLObject var11, final SubLObject var12) { Functions.funcall(var12, var11, (SubLObject)$ic28$, (SubLObject)$ic29$, (SubLObject)SIX_INTEGER); Functions.funcall(var12, var11, (SubLObject)$ic30$, (SubLObject)$ic21$, f27963(var11)); Functions.funcall(var12, var11, (SubLObject)$ic30$, (SubLObject)$ic22$, f27964(var11)); Functions.funcall(var12, var11, (SubLObject)$ic30$, (SubLObject)$ic23$, f27965(var11)); Functions.funcall(var12, var11, (SubLObject)$ic30$, (SubLObject)$ic24$, f27966(var11)); Functions.funcall(var12, var11, (SubLObject)$ic30$, (SubLObject)$ic25$, f27967(var11)); Functions.funcall(var12, var11, (SubLObject)$ic30$, (SubLObject)$ic26$, f27968(var11)); Functions.funcall(var12, var11, (SubLObject)$ic31$, (SubLObject)$ic29$, (SubLObject)SIX_INTEGER); return var11; } public static SubLObject f27977(final SubLObject var11, final SubLObject var12) { return f27976(var11, var12); } public static SubLObject f27978(final SubLObject var13) { final SubLObject var14 = f27975((SubLObject)UNPROVIDED); f27969(var14, module0077.f5313(Symbols.symbol_function((SubLObject)EQ), (SubLObject)UNPROVIDED)); f27970(var14, module0077.f5313(Symbols.symbol_function((SubLObject)EQ), (SubLObject)UNPROVIDED)); f27971(var14, var13); f27972(var14, module0067.f4880(Symbols.symbol_function((SubLObject)EQ), (SubLObject)UNPROVIDED)); f27973(var14, module0067.f4880(Symbols.symbol_function((SubLObject)EQ), (SubLObject)UNPROVIDED)); f27974(var14, module0067.f4880(Symbols.symbol_function((SubLObject)EQ), (SubLObject)UNPROVIDED)); return var14; } public static SubLObject f27979(final SubLObject var15) { assert NIL != module0397.f28129(var15) : var15; final SubLObject var16 = module0367.f25056(var15); return f27963(var16); } public static SubLObject f27980(final SubLObject var15) { assert NIL != module0397.f28129(var15) : var15; final SubLObject var16 = module0367.f25056(var15); return f27964(var16); } public static SubLObject f27981(final SubLObject var15) { assert NIL != module0397.f28129(var15) : var15; final SubLObject var16 = module0367.f25056(var15); return f27965(var16); } public static SubLObject f27982(final SubLObject var15) { assert NIL != module0397.f28129(var15) : var15; final SubLObject var16 = module0367.f25056(var15); return f27966(var16); } public static SubLObject f27983(final SubLObject var15) { assert NIL != module0397.f28129(var15) : var15; final SubLObject var16 = module0367.f25056(var15); return f27967(var16); } public static SubLObject f27984(final SubLObject var15) { assert NIL != module0397.f28129(var15) : var15; final SubLObject var16 = module0367.f25056(var15); return f27968(var16); } public static SubLObject f27985(final SubLObject var15, final SubLObject var16) { assert NIL != module0387.f27528(var16) : var16; return module0077.f5320(var16, f27979(var15)); } public static SubLObject f27986(final SubLObject var15, final SubLObject var17) { assert NIL != module0397.f28129(var15) : var15; assert NIL != module0373.f26150(var17) : var17; final SubLObject var18 = module0373.f26152(var17); return f27985(var15, var18); } public static SubLObject f27987(final SubLObject var15, final SubLObject var18) { assert NIL != module0363.f24478(var18) : var18; return module0077.f5320(var18, f27980(var15)); } public static SubLObject f27988(final SubLObject var15, final SubLObject var18) { assert NIL != module0363.f24478(var18) : var18; final SubLObject var19 = f27982(var15); return Numbers.plusp(module0067.f4885(var19, var18, (SubLObject)ZERO_INTEGER)); } public static SubLObject f27989(final SubLObject var15, final SubLObject var18) { assert NIL != module0363.f24478(var18) : var18; if (NIL == f27988(var15, var18)) { final SubLObject var19 = f27983(var15); final SubLObject var20 = module0067.f4885(var19, var18, (SubLObject)NIL); if (NIL != var20 && NIL == module0077.f5316(var20)) { return (SubLObject)T; } } return (SubLObject)NIL; } public static SubLObject f27990(final SubLObject var15, final SubLObject var21) { assert NIL != module0387.f27526(var21) : var21; final SubLObject var22 = module0387.f27530(var21); final SubLObject var23 = f27983(var15); final SubLObject var24 = module0067.f4885(var23, var22, (SubLObject)NIL); return (SubLObject)makeBoolean(NIL != module0077.f5302(var24) && NIL != module0077.f5320(var21, var24)); } public static SubLObject f27991(final SubLObject var15, final SubLObject var21) { assert NIL != module0387.f27526(var21) : var21; final SubLObject var22 = module0387.f27530(var21); final SubLObject var23 = f27984(var15); final SubLObject var24 = module0067.f4885(var23, var22, (SubLObject)NIL); return (SubLObject)makeBoolean(NIL != module0077.f5302(var24) && NIL != module0077.f5320(var21, var24)); } public static SubLObject f27992(final SubLObject var15) { return module0367.f25062(var15); } public static SubLObject f27993(final SubLObject var15) { final SubLObject var16 = f27981(var15); if (NIL == module0054.f3970(var16)) { return module0054.f3975(var16); } return (SubLObject)NIL; } public static SubLObject f27994(final SubLObject var15, final SubLObject var18) { assert NIL != module0397.f28129(var15) : var15; assert NIL != module0363.f24478(var18) : var18; return module0367.f25099(var15, var18); } public static SubLObject f27995(final SubLObject var15, final SubLObject var16) { assert NIL != module0397.f28129(var15) : var15; assert NIL != module0387.f27528(var16) : var16; return module0077.f5326(var16, f27979(var15)); } public static SubLObject f27996(final SubLObject var15, final SubLObject var18) { assert NIL != module0397.f28129(var15) : var15; assert NIL != module0363.f24478(var18) : var18; module0077.f5326(var18, f27980(var15)); module0367.f25107(var18, var15); return (SubLObject)NIL; } public static SubLObject f27997(final SubLObject var15, final SubLObject var18) { assert NIL != module0397.f28129(var15) : var15; assert NIL != module0363.f24478(var18) : var18; module0077.f5327(var18, f27980(var15)); module0367.f25239(var18, var15); module0367.f25241(var18, var15); return (SubLObject)NIL; } public static SubLObject f27998(final SubLObject var15, final SubLObject var21) { assert NIL != module0397.f28129(var15) : var15; assert NIL != module0387.f27532(var21) : var21; final SubLObject var22 = f27981(var15); module0054.f3973(var21, var22); final SubLObject var23 = module0387.f27530(var21); final SubLObject var24 = f27982(var15); SubLObject var25 = module0067.f4885(var24, var23, (SubLObject)ZERO_INTEGER); var25 = Numbers.add(var25, (SubLObject)ONE_INTEGER); if (ONE_INTEGER.numE(var25)) { f27997(var15, var23); } module0067.f4886(var24, var23, var25); return var25; } public static SubLObject f27999(final SubLObject var15) { module0054.f3969(f27981(var15)); module0067.f4881(f27982(var15)); return var15; } public static SubLObject f28000(final SubLObject var15) { assert NIL != module0397.f28129(var15) : var15; return module0054.f3972(f27981(var15)); } public static SubLObject f28001(final SubLObject var15) { final SubLObject var16 = f27981(var15); return module0054.f3974(var16); } public static SubLObject f28002(final SubLObject var15, final SubLObject var21) { assert NIL != module0397.f28129(var15) : var15; assert NIL != module0387.f27532(var21) : var21; final SubLObject var22 = f27983(var15); final SubLObject var23 = module0387.f27530(var21); SubLObject var24 = module0067.f4885(var22, var23, (SubLObject)NIL); if (NIL != module0365.f24819(var21)) { module0367.f25231(var21, var15, (SubLObject)UNPROVIDED); } module0367.f25179(var23, var15); module0367.f25107(var23, var15); if (NIL == module0077.f5302(var24)) { var24 = module0077.f5313(Symbols.symbol_function((SubLObject)EQ), (SubLObject)UNPROVIDED); module0067.f4886(var22, var23, var24); } return module0077.f5326(var21, var24); } public static SubLObject f28003(final SubLObject var15) { final SubLThread var16 = SubLProcess.currentSubLThread(); assert NIL != module0397.f28129(var15) : var15; final SubLObject var17 = f27983(var15); SubLObject var18; for (var18 = module0066.f4838(module0067.f4891(var17)); NIL == module0066.f4841(var18); var18 = module0066.f4840(var18)) { var16.resetMultipleValues(); final SubLObject var19 = module0066.f4839(var18); final SubLObject var20 = var16.secondMultipleValue(); var16.resetMultipleValues(); if (NIL != module0363.f24504(var19)) { f27997(var15, var19); } } module0066.f4842(var18); module0067.f4881(var17); return var15; } public static SubLObject f28004(final SubLObject var15, final SubLObject var21) { assert NIL != module0397.f28129(var15) : var15; assert NIL != module0387.f27532(var21) : var21; if (NIL != module0365.f24819(var21)) { module0367.f25228(var21, var15, (SubLObject)UNPROVIDED); if (NIL != module0380.f26969(var21)) { SubLObject var22 = module0363.f24517(module0365.f24850(var21)); SubLObject var23 = (SubLObject)NIL; var23 = var22.first(); while (NIL != var22) { if (NIL != module0363.f24524(var23, (SubLObject)$ic39$) && !var23.eql(var21)) { module0367.f25233(var23, var15); } var22 = var22.rest(); var23 = var22.first(); } } } final SubLObject var24 = f27984(var15); final SubLObject var25 = module0387.f27530(var21); SubLObject var26 = module0067.f4885(var24, var25, (SubLObject)NIL); if (NIL == module0077.f5302(var26)) { var26 = module0077.f5313(Symbols.symbol_function((SubLObject)EQ), (SubLObject)UNPROVIDED); module0067.f4886(var24, var25, var26); } return module0077.f5326(var21, var26); } public static SubLObject f28005(final SubLObject var15) { assert NIL != module0397.f28129(var15) : var15; return module0054.f3970(f27981(var15)); } public static SubLObject f28006(final SubLObject var15) { f28003(var15); return var15; } public static SubLObject f28007() { SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27961", "S#31092", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27962", "S#31091", 1, 0, false); new $f27962$UnaryFunction(); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27963", "S#31093", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27964", "S#31094", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27965", "S#31095", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27966", "S#31096", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27967", "S#31097", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27968", "S#31098", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27969", "S#31099", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27970", "S#31100", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27971", "S#31101", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27972", "S#31102", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27973", "S#31103", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27974", "S#31104", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27975", "S#31105", 0, 1, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27976", "S#31106", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27977", "S#31107", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27978", "S#31108", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27979", "S#31109", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27980", "S#31110", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27981", "S#31111", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27982", "S#31112", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27983", "S#31113", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27984", "S#31114", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27985", "S#31115", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27986", "S#31116", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27987", "S#31117", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27988", "S#31118", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27989", "S#31119", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27990", "S#31120", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27991", "S#31121", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27992", "S#31122", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27993", "S#31123", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27994", "S#31124", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27995", "S#31125", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27996", "S#31126", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27997", "S#31127", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27998", "S#31128", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f27999", "S#31129", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f28000", "S#31130", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f28001", "S#31131", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f28002", "S#31132", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f28003", "S#31133", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f28004", "S#31134", 2, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f28005", "S#31135", 1, 0, false); SubLFiles.declareFunction("com.cyc.cycjava.cycl.module0393", "f28006", "S#31136", 1, 0, false); return (SubLObject)NIL; } public static SubLObject f28008() { $g3282$ = SubLFiles.defconstant("S#31137", (SubLObject)$ic0$); return (SubLObject)NIL; } public static SubLObject f28009() { Structures.register_method(print_high.$print_object_method_table$.getGlobalValue(), $g3282$.getGlobalValue(), Symbols.symbol_function((SubLObject)$ic7$)); SubLSpecialOperatorDeclarations.proclaim((SubLObject)$ic8$); Structures.def_csetf((SubLObject)$ic9$, (SubLObject)$ic10$); Structures.def_csetf((SubLObject)$ic11$, (SubLObject)$ic12$); Structures.def_csetf((SubLObject)$ic13$, (SubLObject)$ic14$); Structures.def_csetf((SubLObject)$ic15$, (SubLObject)$ic16$); Structures.def_csetf((SubLObject)$ic17$, (SubLObject)$ic18$); Structures.def_csetf((SubLObject)$ic19$, (SubLObject)$ic20$); Equality.identity((SubLObject)$ic0$); Structures.register_method(visitation.$visit_defstruct_object_method_table$.getGlobalValue(), $g3282$.getGlobalValue(), Symbols.symbol_function((SubLObject)$ic32$)); return (SubLObject)NIL; } public void declareFunctions() { f28007(); } public void initializeVariables() { f28008(); } public void runTopLevelForms() { f28009(); } static { me = (SubLFile)new module0393(); $g3282$ = null; $ic0$ = makeSymbol("S#31090", "CYC"); $ic1$ = makeSymbol("S#31091", "CYC"); $ic2$ = ConsesLow.list((SubLObject)makeSymbol("S#31138", "CYC"), (SubLObject)makeSymbol("S#31139", "CYC"), (SubLObject)makeSymbol("S#31140", "CYC"), (SubLObject)makeSymbol("S#31141", "CYC"), (SubLObject)makeSymbol("S#31142", "CYC"), (SubLObject)makeSymbol("S#31143", "CYC")); $ic3$ = ConsesLow.list((SubLObject)makeKeyword("LINK-HEADS-MOTIVATED"), (SubLObject)makeKeyword("PROBLEMS-PENDING"), (SubLObject)makeKeyword("REMOVAL-STRATEGEM-INDEX"), (SubLObject)makeKeyword("PROBLEM-TOTAL-STRATEGEMS-ACTIVE"), (SubLObject)makeKeyword("PROBLEM-STRATEGEMS-SET-ASIDE"), (SubLObject)makeKeyword("PROBLEM-STRATEGEMS-THROWN-AWAY")); $ic4$ = ConsesLow.list((SubLObject)makeSymbol("S#31093", "CYC"), (SubLObject)makeSymbol("S#31094", "CYC"), (SubLObject)makeSymbol("S#31095", "CYC"), (SubLObject)makeSymbol("S#31096", "CYC"), (SubLObject)makeSymbol("S#31097", "CYC"), (SubLObject)makeSymbol("S#31098", "CYC")); $ic5$ = ConsesLow.list((SubLObject)makeSymbol("S#31099", "CYC"), (SubLObject)makeSymbol("S#31100", "CYC"), (SubLObject)makeSymbol("S#31101", "CYC"), (SubLObject)makeSymbol("S#31102", "CYC"), (SubLObject)makeSymbol("S#31103", "CYC"), (SubLObject)makeSymbol("S#31104", "CYC")); $ic6$ = makeSymbol("DEFAULT-STRUCT-PRINT-FUNCTION"); $ic7$ = makeSymbol("S#31092", "CYC"); $ic8$ = ConsesLow.list((SubLObject)makeSymbol("OPTIMIZE-FUNCALL"), (SubLObject)makeSymbol("S#31091", "CYC")); $ic9$ = makeSymbol("S#31093", "CYC"); $ic10$ = makeSymbol("S#31099", "CYC"); $ic11$ = makeSymbol("S#31094", "CYC"); $ic12$ = makeSymbol("S#31100", "CYC"); $ic13$ = makeSymbol("S#31095", "CYC"); $ic14$ = makeSymbol("S#31101", "CYC"); $ic15$ = makeSymbol("S#31096", "CYC"); $ic16$ = makeSymbol("S#31102", "CYC"); $ic17$ = makeSymbol("S#31097", "CYC"); $ic18$ = makeSymbol("S#31103", "CYC"); $ic19$ = makeSymbol("S#31098", "CYC"); $ic20$ = makeSymbol("S#31104", "CYC"); $ic21$ = makeKeyword("LINK-HEADS-MOTIVATED"); $ic22$ = makeKeyword("PROBLEMS-PENDING"); $ic23$ = makeKeyword("REMOVAL-STRATEGEM-INDEX"); $ic24$ = makeKeyword("PROBLEM-TOTAL-STRATEGEMS-ACTIVE"); $ic25$ = makeKeyword("PROBLEM-STRATEGEMS-SET-ASIDE"); $ic26$ = makeKeyword("PROBLEM-STRATEGEMS-THROWN-AWAY"); $ic27$ = makeString("Invalid slot ~S for construction function"); $ic28$ = makeKeyword("BEGIN"); $ic29$ = makeSymbol("S#31105", "CYC"); $ic30$ = makeKeyword("SLOT"); $ic31$ = makeKeyword("END"); $ic32$ = makeSymbol("S#31107", "CYC"); $ic33$ = makeSymbol("S#29327", "CYC"); $ic34$ = makeSymbol("S#30620", "CYC"); $ic35$ = makeSymbol("S#27602", "CYC"); $ic36$ = makeSymbol("S#26082", "CYC"); $ic37$ = makeSymbol("S#30616", "CYC"); $ic38$ = makeSymbol("S#30622", "CYC"); $ic39$ = makeKeyword("SPLIT"); } public static final class $sX31090_native extends SubLStructNative { public SubLObject $link_heads_motivated; public SubLObject $problems_pending; public SubLObject $removal_strategem_index; public SubLObject $problem_total_strategems_active; public SubLObject $problem_strategems_set_aside; public SubLObject $problem_strategems_thrown_away; public static final SubLStructDeclNative structDecl; public $sX31090_native() { this.$link_heads_motivated = (SubLObject)CommonSymbols.NIL; this.$problems_pending = (SubLObject)CommonSymbols.NIL; this.$removal_strategem_index = (SubLObject)CommonSymbols.NIL; this.$problem_total_strategems_active = (SubLObject)CommonSymbols.NIL; this.$problem_strategems_set_aside = (SubLObject)CommonSymbols.NIL; this.$problem_strategems_thrown_away = (SubLObject)CommonSymbols.NIL; } public SubLStructDecl getStructDecl() { return (SstructDecl; } public SubLObject getField2() { return this.$link_heads_motivated; } public SubLObject getField3() { return this.$problems_pending; } public SubLObject getField4() { return this.$removal_strategem_index; } public SubLObject getField5() { return this.$problem_total_strategems_active; } public SubLObject getField6() { return this.$problem_strategems_set_aside; } public SubLObject getField7() { return this.$problem_strategems_thrown_away; } public SubLObject setField2(final SubLObject value) { return this.$link_heads_motivated = value; } public SubLObject setField3(final SubLObject value) { return this.$problems_pending = value; } public SubLObject setField4(final SubLObject value) { return this.$removal_strategem_index = value; } public SubLObject setField5(final SubLObject value) { return this.$problem_total_strategems_active = value; } public SubLObject setField6(final SubLObject value) { return this.$problem_strategems_set_aside = value; } public SubLObject setField7(final SubLObject value) { return this.$problem_strategems_thrown_away = value; } static { structDecl = Structures.makeStructDeclNative((Class)$sX31090_native.class, $ic0$, $ic1$, $ic2$, $ic3$, new String[] { "$link_heads_motivated", "$problems_pending", "$removal_strategem_index", "$problem_total_strategems_active", "$problem_strategems_set_aside", "$problem_strategems_thrown_away" }, $ic4$, $ic5$, $ic6$); } } public static final class $f27962$UnaryFunction extends UnaryFunction { public $f27962$UnaryFunction() { super(SubLTranslatedFile.extractFunctionNamed("S#31091")); } public SubLObject processItem(final SubLObject var3) { return f27962(var3); } } } /* DECOMPILATION REPORT Decompiled from: G:\opt\CYC_JRTL_with_CommonLisp\platform\lib\cyc-oc4.0-unzipped/com/cyc/cycjava/cycl/class Total time: 155 ms Decompiled with Procyon 0.5.32. */
47.489552
353
0.650764
a9cd66c4cc3cbb7994ea76eed273e8f6260ade30
700
package readbiomed.mme.util; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; public class Trie<T> extends gov.nih.nlm.nls.utils.Trie<T> { private static final long serialVersionUID = 7252238938341206601L; public int size() { return map.size(); } private Map<String, T> map = new HashMap<>(); public void insert(String key, T value) { map.put(key, value); } public T get(String key) { return map.get(key); } public void traverse() { map.entrySet().stream().forEach(e -> System.out.println(e)); } public Map<T, String> getTermMap() { return map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); } }
21.875
99
0.701429
6fee2186837cfce096ed43b5d028d0ec8642d203
3,165
package com.github.jntakpe.sleuthkafka; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.kafka.KafkaProperties; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; import org.springframework.kafka.support.SendResult; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import reactor.kafka.sender.KafkaSender; import reactor.kafka.sender.SenderOptions; import reactor.kafka.sender.SenderRecord; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; @SpringBootApplication public class SleuthKafkaApplication { private static final Log log = LogFactory.getLog(SleuthKafkaApplication.class); @RestController @RequestMapping("/kafka") class KafkaResource { private AtomicInteger correlationId = new AtomicInteger(); private final KafkaSender<String, String> kafkaSender; private final ObjectMapper objectMapper; private final KafkaTemplate<String, String> kafkaTemplate; KafkaResource(KafkaProperties kafkaProperties, ObjectMapper objectMapper) { Map<String, Object> properties = kafkaProperties.buildProducerProperties(); properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); this.kafkaSender = KafkaSender.create(SenderOptions.create(properties)); this.kafkaTemplate = new KafkaTemplate<>( new DefaultKafkaProducerFactory<String, String>(properties)); this.objectMapper = objectMapper; } @GetMapping("/reactor") public Mono<User> reactor() throws JsonProcessingException { User user = new User().setUsername("reactor-user").setAge(20); SenderRecord<String, String, Integer> record = SenderRecord .create("some-topic", 0, null, user.getUsername(), this.objectMapper.writeValueAsString(user), this.correlationId.incrementAndGet()); log.info("[TEST] Sending the response for reactor"); return this.kafkaSender.send(Mono.just(record)).map(i -> user).single(); } @GetMapping("/template") public User template() throws JsonProcessingException, ExecutionException, InterruptedException { User user = new User().setUsername("template-user").setAge(30); SendResult<String, String> stringStringSendResult = this.kafkaTemplate .send("some-topic", this.objectMapper.writeValueAsString(user)).get(); log.info("[TEST] Sending the response for template"); return user; } } public static void main(String[] args) { SpringApplication.run(SleuthKafkaApplication.class, args); } }
39.074074
80
0.795261
ce5ed40ac26d99d2f4c02dd40467652893478b21
5,032
/** * Copyright 2012 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.ios; import cli.MonoTouch.CoreGraphics.CGBitmapContext; import cli.MonoTouch.CoreGraphics.CGBlendMode; import cli.MonoTouch.CoreGraphics.CGColorSpace; import cli.MonoTouch.CoreGraphics.CGImage; import cli.MonoTouch.CoreGraphics.CGImageAlphaInfo; import cli.MonoTouch.UIKit.UIColor; import cli.MonoTouch.UIKit.UIImage; import cli.System.Drawing.RectangleF; import playn.core.Image; import playn.core.Pattern; import playn.core.ResourceCallback; import playn.core.gl.GLContext; import playn.core.gl.ImageGL; import playn.core.gl.Scale; /** * Provides some shared bits for {@link IOSImage} and {@link IOSCanvasImage}. */ public abstract class IOSAbstractImage extends ImageGL implements Image, IOSCanvas.Drawable { /** * Returns a core graphics image that can be used to paint this image into a canvas. */ protected abstract CGImage cgImage(); @Override public boolean isReady() { return true; // we're always ready } @Override public void addCallback(ResourceCallback<? super Image> callback) { callback.done(this); // we're always ready } @Override public Region subImage(float x, float y, float width, float height) { return new IOSImageRegion(this, x, y, width, height); } @Override public Pattern toPattern() { // this is a circuitous route, but I'm not savvy enough to find a more direct one return new IOSPattern(this, UIColor.FromPatternImage(new UIImage(cgImage())).get_CGColor()); } @Override public void getRgb(int startX, int startY, int width, int height, int[] rgbArray, int offset, int scanSize) { CGImage image = cgImage(); int bytesPerRow = 4 * width; byte[] regionBytes = new byte[bytesPerRow * height]; CGBitmapContext context = new CGBitmapContext(regionBytes, width, height, 8, bytesPerRow, // PremultipliedFirst for ARGB, same as BufferedImage in Java. CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.wrap(CGImageAlphaInfo.PremultipliedFirst)); context.SetBlendMode(CGBlendMode.wrap(CGBlendMode.Copy)); // UIImage and CGImage use coordinate spaces with relatively inverted Y. Less 1 pixel to adjust // the proper row to the top of the region int invertedY = image.get_Height() - startY - height + 1; context.TranslateCTM(-startX, -invertedY); context.DrawImage(new RectangleF(0, 0, image.get_Width(), image.get_Height()), image); int x = 0; int y = 0; for (int px = 0; px < regionBytes.length; px += 4) { int a = (int)regionBytes[px ] & 0xFF; int r = (int)regionBytes[px + 1] & 0xFF; int g = (int)regionBytes[px + 2] & 0xFF; int b = (int)regionBytes[px + 3] & 0xFF; rgbArray[offset + y * scanSize + x] = a << 24 | r << 16 | g << 8 | b; x++; if (x == width) { x = 0; y++; } } } @Override public void draw(CGBitmapContext bctx, float x, float y, float width, float height) { CGImage cgImage = cgImage(); // pesky fiddling to cope with the fact that UIImages are flipped; TODO: make sure drawing a // canvas image on a canvas image does the right thing y += height; bctx.TranslateCTM(x, y); bctx.ScaleCTM(1, -1); bctx.DrawImage(new RectangleF(0, 0, width, height), cgImage); bctx.ScaleCTM(1, -1); bctx.TranslateCTM(-x, -y); } @Override public void draw(CGBitmapContext bctx, float dx, float dy, float dw, float dh, float sx, float sy, float sw, float sh) { // adjust our source rect to account for the scale factor sx *= scale.factor; sy *= scale.factor; sw *= scale.factor; sh *= scale.factor; CGImage cgImage = cgImage(); float iw = cgImage.get_Width(), ih = cgImage.get_Height(); float scaleX = dw/sw, scaleY = dh/sh; // pesky fiddling to cope with the fact that UIImages are flipped bctx.SaveState(); bctx.TranslateCTM(dx, dy+dh); bctx.ScaleCTM(1, -1); bctx.ClipToRect(new RectangleF(0, 0, dw, dh)); bctx.TranslateCTM(-sx*scaleX, -(ih-(sy+sh))*scaleY); bctx.DrawImage(new RectangleF(0, 0, iw*scaleX, ih*scaleY), cgImage); bctx.RestoreState(); } @Override public Image transform(BitmapTransformer xform) { UIImage ximage = new UIImage(((IOSBitmapTransformer) xform).transform(cgImage())); return new IOSImage(ctx, ximage, scale); } protected IOSAbstractImage(GLContext ctx, Scale scale) { super(ctx, scale); } }
34.944444
99
0.687401
61b17cda1cfd9fbe1a093d2de7e9ea7cb31651d4
13,419
package org.funz.api; import java.io.File; import java.io.FileFilter; import java.util.HashMap; import java.util.Map; import org.funz.log.Log; import org.funz.log.LogFile; import org.funz.script.RMathExpression; import org.funz.util.ASCII; import static org.funz.util.Data.newMap; import org.funz.util.Disk; import static org.funz.util.Format.ArrayMapToMDString; import org.funz.util.Parser; import org.junit.Before; import org.junit.Test; /** * * @author richet */ public class DesignShellTest extends org.funz.api.TestUtils { @Before public void setUp() throws Exception { Funz_v1.init(); } public static void main(String args[]) { org.junit.runner.JUnitCore.main(DesignShellTest.class.getName()); } // @Test public void testDirect() throws Exception { System.err.println("+++++++++++++++++++++++++ testDirect"); Funz.setVerbosity(3); HashMap<String, String> variable_bounds = new HashMap<String, String>(); variable_bounds.put("x1", "[0,1]"); variable_bounds.put("x2", "[0,1]"); DesignShell_v1 shell = new DesignShell_v1(branin, "Test direct", variable_bounds, null); shell.startComputationAndWait(); System.err.println(ArrayMapToMDString(shell.getResultsArrayMap())); } // @Test public void testIterative() throws Exception { System.err.println("+++++++++++++++++++++++++ testIterative"); Funz.setVerbosity(3); HashMap<String, String> variable_bounds = new HashMap<String, String>(); variable_bounds.put("x1", "[0,1]"); variable_bounds.put("x2", "[0,1]"); DesignShell_v1 shell = new DesignShell_v1(branin, "Test iterative", variable_bounds, null); shell.setDesignOption("N", "5"); shell.setDesignOption("repeat", "10"); shell.startComputationAndWait(); System.err.println(ArrayMapToMDString(shell.getResultsArrayMap())); } @Test public void testRGradientDescent() throws Exception { System.err.println("+++++++++++++++++++++++++ testRGradientDescent"); Funz.setVerbosity(3); HashMap<String, String> variable_bounds = new HashMap<String, String>(); variable_bounds.put("x1", "["+mult_x1_min+","+mult_x1_max+"]"); variable_bounds.put("x2", "["+mult_x2_min+","+mult_x2_max+"]"); DesignShell_v1 shell = new DesignShell_v1(mult, "GradientDescent", variable_bounds, null); shell.setArchiveDirectory(newTmpDir("testRGradientDescent")); shell.setDesignOption("nmax", "3"); shell.startComputationAndWait(); Map<String, Object[]> res = shell.getResultsArrayMap(); assert res.get("state") != null : "Status null:" + res; assert res.get("state").length == 1 : "Status: '" + ASCII.cat(",", res.get("state")) + "'"; assert res.get("state")[0].toString().contains("Design over") : "Status: '" + res.get("state")[0] + "'"; assert ASCII.cat("\n", res.get("analysis")).contains("minimum is ") : "No convergence :" + ASCII.cat("\n", res.get("analysis")); double min_found = Double.parseDouble(Parser.after(ASCII.cat("\n", res.get("analysis")),"minimum is ").trim().substring(0,4)); assert min_found >= mult_min: "Wrong convergence :" + ASCII.cat("\n", res.get("analysis")); System.err.println(ArrayMapToMDString(shell.getResultsStringArrayMap())); } @Test public void testOldRGradientDescent() throws Exception { System.err.println("+++++++++++++++++++++++++ testOldRGradientDescent"); Funz.setVerbosity(3); HashMap<String, String> variable_bounds = new HashMap<String, String>(); variable_bounds.put("x1", "["+mult_x1_min+","+mult_x1_max+"]"); variable_bounds.put("x2", "["+mult_x2_min+","+mult_x2_max+"]"); DesignShell_v1 shell = new DesignShell_v1(mult, "oldgradientdescent", variable_bounds, null); shell.setArchiveDirectory(newTmpDir("testOldRGradientDescent")); shell.setDesignOption("nmax", "10"); shell.startComputationAndWait(); Map<String, Object[]> res = shell.getResultsArrayMap(); assert res.get("state") != null : "Status null:" + res; assert res.get("state").length == 1 : "Status: '" + ASCII.cat(",", res.get("state")) + "'"; assert res.get("state")[0].toString().contains("Design over") : "Status: '" + res.get("state")[0] + "'"; assert ASCII.cat("\n", res.get("analysis")).contains("minimum is ") : "No convergence :" + ASCII.cat("\n", res.get("analysis")); double min_found = Double.parseDouble(Parser.after(ASCII.cat("\n", res.get("analysis")),"minimum is ").trim().substring(0,4)); assert min_found >= mult_min: "Wrong convergence :" + ASCII.cat("\n", res.get("analysis")); System.err.println(ArrayMapToMDString(shell.getResultsStringArrayMap())); } @Test public void testOldREGO() throws Exception { System.err.println("+++++++++++++++++++++++++ testOldREGO"); if (!RMathExpression.GetEngineName().contains("Rserve")) {System.err.println("Not using Rserve, so skipping test"); return;} // Do not run if using Renjin or R2js... Log.setCollector(new LogFile("testOldREGO.log")); Funz.setVerbosity(3); HashMap<String, String> variable_bounds = new HashMap<String, String>(); variable_bounds.put("x1", "[0,1]"); variable_bounds.put("x2", "[0,1]"); DesignShell_v1 shell = new DesignShell_v1(branin, "oldEGO", variable_bounds, newMap("iterations", "15")); shell.setArchiveDirectory(newTmpDir("testOldRGradientDescent")); assert shell.startComputationAndWait(); assert shell.stopComputation(); Map<String, Object[]> res = shell.getResultsArrayMap(); assert res.get("state") != null : "Status null"; assert res.get("state").length == 1 : "Status: '" + ASCII.cat(",", res.get("state")) + "'"; assert res.get("state")[0].toString().contains("Design over") : "Status: '" + res.get("state")[0] + "'"; assert ASCII.cat("\n", res.get("analysis")).contains("minimum is ") : "No convergence :" + ASCII.cat("\n", res.get("analysis")); double min_found = Double.parseDouble(Parser.after(ASCII.cat("\n", res.get("analysis")),"minimum is ").trim().substring(0,3)); assert min_found <= branin_min: "Wrong convergence :" + org.apache.commons.io.FileUtils.readFileToString(new File("testOldREGO.log")); System.err.println(ArrayMapToMDString(shell.getResultsStringArrayMap())); } @Test public void testREGO() throws Exception { System.err.println("+++++++++++++++++++++++++ testREGO"); if (!RMathExpression.GetEngineName().contains("Rserve")) {System.err.println("Not using Rserve, so skipping test"); return;} // Do not run if using Renjin or R2js... Funz.setVerbosity(3); Log.setCollector(new LogFile("testREGO.log")); HashMap<String, String> variable_bounds = new HashMap<String, String>(); variable_bounds.put("x1", "[0,1]"); variable_bounds.put("x2", "[0,1]"); DesignShell_v1 shell = new DesignShell_v1(branin, "EGO", variable_bounds, newMap("iterations", "15")); shell.setArchiveDirectory(newTmpDir("testOldRGradientDescent")); assert shell.startComputationAndWait(); assert shell.stopComputation(); Map<String, Object[]> res = shell.getResultsArrayMap(); shell.shutdown(); assert res.get("state") != null : "Status null: res=" + res; assert res.get("state").length == 1 : "Status: '" + ASCII.cat(",", res.get("state")) + "'"; assert res.get("state")[0].toString().contains("Design over") : "Status: '" + res.get("state")[0] + "'"; assert ASCII.cat("\n", res.get("analysis")).contains("minimum is ") : "No convergence :" + ASCII.cat("\n", res.get("analysis")); double min_found = Double.parseDouble(Parser.after(ASCII.cat("\n", res.get("analysis")),"minimum is ").trim().substring(0,3)); assert min_found <= branin_min: "Wrong convergence :" + org.apache.commons.io.FileUtils.readFileToString(new File("testREGO.log")); System.out.println("analysis:\n" + ASCII.cat("\n", res.get("analysis"))); } @Test public void testMoveProject() throws Exception { System.err.println("+++++++++++++++++++++++++ testMoveProject"); Funz.setVerbosity(3); Log.setCollector(new LogFile("testMoveProject.log")); HashMap<String, String> variable_bounds = new HashMap<String, String>(); variable_bounds.put("x1", "[0,1]"); variable_bounds.put("x2", "[0,1]"); DesignShell_v1 shell = new DesignShell_v1(branin, "GradientDescent", variable_bounds, null); File bad_res = newTmpDir("testMoveProject_gradientdescent.res"); if (bad_res.exists()) { Disk.removeDir(bad_res); assert !bad_res.exists() : "Could not delete " + bad_res; } File good_res = newTmpDir("testMoveProject_gradientdescent.res.good"); if (good_res.exists()) { Disk.removeDir(good_res); assert !good_res.exists() : "Could not delete " + good_res; } shell.setArchiveDirectory(good_res); shell.redirectOutErr(); shell.setDesignOption("nmax", "3"); shell.startComputationAndWait(); //System.err.println(ArrayMapToMDString(shell.getDataAsArray())); shell.setProjectDir(good_res); assert !bad_res.exists() : "Used the old archive dir"; assert good_res.isDirectory() : "Did not created the defined archive dir"; assert good_res.listFiles(new FileFilter() { public boolean accept(File file) { return file.getName().endsWith("project.xml"); } }).length == 1 : "Did not used the defined archive dir"; assert good_res.listFiles(new FileFilter() { public boolean accept(File file) { return file.getName().endsWith(".out"); } }).length == 1 : "Did not built the error stream in the defined archive dir"; } // @Test /*public void testGradientDescentWithCache() throws Exception { Funz.setVerbosity(3); HashMap<String, String> variable_bounds = new HashMap<String, String>(); variable_bounds.put("x1", "[0,1]"); variable_bounds.put("x2", "[0,1]"); DesignShell_v1 shell_nocache = new DesignShell_v1(branin,"gradientdescent", variable_bounds); shell_nocache.setDesignOption("nmax", "10"); DesignShell_v1 shell_cache = new DesignShell_v1(branin,"gradientdescent", variable_bounds); shell_cache.setDesignOption("nmax", "10"); shell_cache.setCacheExperiments(true); Map<String, String[]> X_nocache = shell_nocache.initDesign(); Map<String, String[]> X_cache = shell_cache.initDesign(); assert Utils.ArrayMapToMDString(X_nocache).equals(Utils.ArrayMapToMDString(X_cache)); boolean end = false; while (!end) { X_nocache = shell_nocache.nextDesign(branin(X_nocache)); X_cache = shell_cache.nextDesign(branin(X_cache)); if (X_nocache == null && X_cache == null) { end = true; } else if (X_nocache == null) { assert false : "X_nocache == null"; } else if (X_cache == null) { assert false : "X_cache == null"; } else { if (!Utils.ArrayMapToMDString(X_nocache).equals(Utils.ArrayMapToMDString(X_cache))) { System.err.println("Cache activated :\n" + Utils.ArrayMapToMDString(X_nocache) + " !=\n" + Utils.ArrayMapToMDString(X_cache)); } } } Map<String, String> analyse_cache = shell_cache.analyseDesign(); System.err.println(analyse_cache); Map<String, String> analyse_nocache = shell_nocache.analyseDesign(); System.err.println(analyse_nocache); for (String k : analyse_cache.keySet()) { assert analyse_cache.get(k).equals(analyse_nocache.get(k)) : "Difference in analyse for key " + k + "\n" + analyse_cache.get(k) + "\n != \n" + analyse_nocache.get(k); } }*/ // static String[] branin(Map<String, String[]> X) { // String[] Y = new String[X.get("x1").length]; // for (int i = 0; i < Y.length; i++) { // double y = 0; // for (String x : X.keySet()) { // y = y + Double.parseDouble(X.get(x)[i]); // } // Y[i] = "" + y; // } // System.err.println(Utils.ArrayMapToMDString(X) + "------>\n" + ASCII.cat("\n", Y)); // return Y; // } @Test public void testError() throws Exception { System.err.println("+++++++++++++++++++++++++ testError"); Funz.setVerbosity(3); HashMap<String, String> variable_bounds = new HashMap<String, String>(); variable_bounds.put("x1", "["+mult_x1_min+","+mult_x1_max+"]"); variable_bounds.put("x2", "["+mult_x2_min+","+mult_x2_max+"]"); DesignShell_v1 shell = new DesignShell_v1(mult, "GradientDescent", variable_bounds, null); shell.setArchiveDirectory(newTmpDir("testOldRGradientDescent")); shell.setDesignOption("nmax", "NaN"); boolean failed = false; try { failed = !shell.startComputationAndWait(); } catch (Exception e) { failed = true; } assert failed : "Did not correclty failed"; } }
43.710098
173
0.621581
75b1626329fd3fbe5751ada01ffbd9ed17f8a31b
57
package com.squareup.okhttp; public interface Call { }
9.5
28
0.754386
5208277434d93735ba0a7016b832cb0d63d471fe
5,518
package dev.linwood.api.ui; import dev.linwood.api.ui.item.GuiItem; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Consumer; /** * @author CodeDoctorDE */ public class GuiCollection extends Gui { protected final List<Gui> guis = new ArrayList<>(); private int current; public GuiCollection() { super(0, 0); } public void registerGui(Gui gui) { guis.add(gui); } public void unregisterGui(Gui gui) { guis.remove(gui); } public void clearGuis() { guis.clear(); } @Override public void show(Player... players) { if (hasAccess()) getGui().show(players); } @Override public void hide(Player... players) { if (hasAccess()) getGui().hide(players); } @Override public void reload(@NotNull Player... players) { if (hasAccess()) getGui().reload(players); } @Override public Player[] getOpenedPlayers() { if (hasAccess()) return getGui().getOpenedPlayers(); return new Player[0]; } @Override public boolean hasCurrentGui(@NotNull Player player) { if (hasAccess()) return super.hasCurrentGui(player); return false; } public Gui @NotNull [] getGuis() { return guis.toArray(new Gui[0]); } public @Nullable Gui getGui() { if (guis.size() < current) return null; return guis.get(current); } public boolean hasGui(Gui gui) { return guis.contains(gui); } public boolean hasAccess() { return current >= 0 && current < guis.size(); } public void setOpenAction(@Nullable Consumer<Player> openAction) { if (hasAccess()) getGui().setOpenAction(openAction); } public void setCloseAction(@Nullable Consumer<Player> closeAction) { if (hasAccess()) getGui().setCloseAction(closeAction); } public int getCurrent() { return current; } public void setCurrent(int current) { if (current < 0 || current >= getGuis().length) return; Player[] players = getOpenedPlayers(); this.current = current; show(players); } public void next() { Player[] players = getOpenedPlayers(); current++; show(players); } public void previous() { Player[] players = getOpenedPlayers(); current--; show(players); } public void toFirst() { Player[] players = getOpenedPlayers(); current = 0; show(players); } public void toLast() { Player[] players = getOpenedPlayers(); current = guis.size() - 1; show(players); } @Override public int getHeight() { return Optional.ofNullable(getGui()).map(GuiPane::getHeight).orElse(0); } @Override public int getWidth() { return getGui().getWidth(); } @Override public void registerItem(int x, int y, GuiItem item) { if (hasAccess()) getGui().registerItem(x, y, item); } @Override public void unregisterItem(int x, int y) { if (hasAccess()) getGui().unregisterItem(x, y); } public boolean isFirst() { return current == 0; } public boolean isLast() { return current == guis.size() - 1; } @Override protected void register(@NotNull Player player) { if (hasAccess()) getGui().register(player); } @Override protected void unregister(@NotNull Player player) { if (hasAccess()) getGui().unregister(player); } @Override public void reloadAll() { if (hasAccess()) getGui().reloadAll(); } @Override protected void onOpen(@NotNull Player player) { if (hasAccess()) getGui().onOpen(player); } @Override protected void onClose(@NotNull Player player) { if (hasAccess()) getGui().onClose(player); } @Override public @Nullable GuiItem getItem(int x, int y) { if (hasAccess()) getGui().getItem(x, y); return null; } @Override public void fillItems(int startX, int startY, int endX, int endY, @Nullable GuiItem item) { if (hasAccess()) getGui().fillItems(startX, startY, endX, endY, item); } @Override public boolean containsItem(int x, int y) { if (hasAccess()) return getGui().containsItem(x, y); return false; } @Override public void addItem(@NotNull GuiItem item) { if (hasAccess()) getGui().addItem(item); } @Override public int getItemCount() { if (hasAccess()) return getGui().getItemCount(); return 0; } @Override public void addPane(@NotNull GuiPane pane) { if (hasAccess()) getGui().addPane(pane); } @Override public void addPane(int offsetX, int offsetY, @NotNull GuiPane pane) { if (hasAccess()) getGui().addPane(offsetX, offsetY, pane); } @Override public @Nullable GuiPane offset(int x, int y) { if (hasAccess()) getGui().offset(x, y); return null; } }
22.614754
95
0.566872
8e01f8375a218f63df0f522d9d6ed2243c386335
642
package Core.code; import graphics.levelselect; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class saving { public saving(){ } public void save(){ String fileName = "save.dat"; try { ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void Load(){ } }
13.956522
82
0.674455
c60216b97a8c139c3f3727537835e89fc53ed8c2
1,322
package com.jasmine; import org.junit.Test; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * optional * * @author guangchang * @create 2019-07-30 21:31 **/ public class OptionalDemo { public static void main(String[] args) { Optional<Object> empty = Optional.empty(); // empty.get(); nullPointException Optional<String> s = Optional.of(""); System.err.println(s); // Optional<Optional<Object>> opt = Optional.of(null); // System.err.println(opt); Optional<Object> opt1 = Optional.ofNullable(null); System.err.println(opt1); /** * 创建optional of/ofNullable * optional.of()会产生nullPointException * 取optional对象中的值 * get() * isPresent() 检查是否有值 接受一个consumer参数 * 返回对象值 * orElse() * */ } @Test public void test(){ Optional<String> name = Optional.ofNullable("name"); String s1 = name.get(); System.err.println(s1); boolean present = name.isPresent(); assertTrue(name.isPresent()); assertEquals("name",name.get()); Optional<String> s = Optional.ofNullable(name).orElse(null); System.err.println(s); } }
24.036364
68
0.591528
cdafd6937bc54b7e3fa9af9e6c1779a39a40581d
1,234
package org.sunny.aframe.cache.domain; import java.io.Serializable; import org.sunny.aframe.db.annotation.Id; import org.sunny.aframe.db.annotation.Table; @Table(name = "entry") public class Entry implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id private String id; private String className; private String content; private String key; private long time; private long deadLine; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public long getDeadLine() { return deadLine; } public void setDeadLine(long deadLine) { this.deadLine = deadLine; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public boolean isValide() { if(deadLine>0) { if(System.currentTimeMillis() - time > deadLine*1000) { return false; } } else { return true; } return true; } }
14.022727
56
0.675851
67a6e73f650c7f3e4bcb83c3569570a1cabb5c73
1,615
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.code; import net.sourceforge.plantuml.StringUtils; public class ArobaseStringCompressor2 implements StringCompressor { public String compress(String data) { return clean2(data); } public String decompress(String s) { return clean2(s); } private String clean2(String s) { // s = s.replace("\0", ""); s = StringUtils.trin(s); // s = s.replace("\r", "").replaceAll("\n+$", ""); if (s.startsWith("@start")) { return s; } return "@startuml\n" + s + "\n@enduml"; } }
28.839286
76
0.626625
f7cb8f4cedc806cb9d63c57f1e47c9cd4c7b99b1
16,425
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.api.changes; import com.google.gerrit.extensions.api.changes.AbandonInput; import com.google.gerrit.extensions.api.changes.AddReviewerInput; import com.google.gerrit.extensions.api.changes.AssigneeInput; import com.google.gerrit.extensions.api.changes.ChangeApi; import com.google.gerrit.extensions.api.changes.Changes; import com.google.gerrit.extensions.api.changes.FixInput; import com.google.gerrit.extensions.api.changes.HashtagsInput; import com.google.gerrit.extensions.api.changes.MoveInput; import com.google.gerrit.extensions.api.changes.RestoreInput; import com.google.gerrit.extensions.api.changes.RevertInput; import com.google.gerrit.extensions.api.changes.ReviewerApi; import com.google.gerrit.extensions.api.changes.RevisionApi; import com.google.gerrit.extensions.api.changes.SubmittedTogetherInfo; import com.google.gerrit.extensions.api.changes.SubmittedTogetherOption; import com.google.gerrit.extensions.client.ListChangesOption; import com.google.gerrit.extensions.common.AccountInfo; import com.google.gerrit.extensions.common.ChangeInfo; import com.google.gerrit.extensions.common.CommentInfo; import com.google.gerrit.extensions.common.EditInfo; import com.google.gerrit.extensions.common.SuggestedReviewerInfo; import com.google.gerrit.extensions.restapi.IdString; import com.google.gerrit.extensions.restapi.Response; import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.server.change.Abandon; import com.google.gerrit.server.change.ChangeEdits; import com.google.gerrit.server.change.ChangeJson; import com.google.gerrit.server.change.ChangeResource; import com.google.gerrit.server.change.Check; import com.google.gerrit.server.change.DeleteAssignee; import com.google.gerrit.server.change.DeleteDraftChange; import com.google.gerrit.server.change.GetAssignee; import com.google.gerrit.server.change.GetHashtags; import com.google.gerrit.server.change.GetPastAssignees; import com.google.gerrit.server.change.GetTopic; import com.google.gerrit.server.change.Index; import com.google.gerrit.server.change.ListChangeComments; import com.google.gerrit.server.change.ListChangeDrafts; import com.google.gerrit.server.change.Move; import com.google.gerrit.server.change.PostHashtags; import com.google.gerrit.server.change.PostReviewers; import com.google.gerrit.server.change.PublishDraftPatchSet; import com.google.gerrit.server.change.PutAssignee; import com.google.gerrit.server.change.PutTopic; import com.google.gerrit.server.change.Restore; import com.google.gerrit.server.change.Revert; import com.google.gerrit.server.change.Reviewers; import com.google.gerrit.server.change.Revisions; import com.google.gerrit.server.change.SubmittedTogether; import com.google.gerrit.server.change.SuggestChangeReviewers; import com.google.gerrit.server.git.UpdateException; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; import java.io.IOException; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; class ChangeApiImpl implements ChangeApi { interface Factory { ChangeApiImpl create(ChangeResource change); } private final Changes changeApi; private final Reviewers reviewers; private final Revisions revisions; private final ReviewerApiImpl.Factory reviewerApi; private final RevisionApiImpl.Factory revisionApi; private final SuggestChangeReviewers suggestReviewers; private final ChangeResource change; private final Abandon abandon; private final Revert revert; private final Restore restore; private final Provider<SubmittedTogether> submittedTogether; private final PublishDraftPatchSet.CurrentRevision publishDraftChange; private final DeleteDraftChange deleteDraftChange; private final GetTopic getTopic; private final PutTopic putTopic; private final PostReviewers postReviewers; private final ChangeJson.Factory changeJson; private final PostHashtags postHashtags; private final GetHashtags getHashtags; private final PutAssignee putAssignee; private final GetAssignee getAssignee; private final GetPastAssignees getPastAssignees; private final DeleteAssignee deleteAssignee; private final ListChangeComments listComments; private final ListChangeDrafts listDrafts; private final Check check; private final Index index; private final ChangeEdits.Detail editDetail; private final Move move; @Inject ChangeApiImpl(Changes changeApi, Reviewers reviewers, Revisions revisions, ReviewerApiImpl.Factory reviewerApi, RevisionApiImpl.Factory revisionApi, SuggestChangeReviewers suggestReviewers, Abandon abandon, Revert revert, Restore restore, Provider<SubmittedTogether> submittedTogether, PublishDraftPatchSet.CurrentRevision publishDraftChange, DeleteDraftChange deleteDraftChange, GetTopic getTopic, PutTopic putTopic, PostReviewers postReviewers, ChangeJson.Factory changeJson, PostHashtags postHashtags, GetHashtags getHashtags, PutAssignee putAssignee, GetAssignee getAssignee, GetPastAssignees getPastAssignees, DeleteAssignee deleteAssignee, ListChangeComments listComments, ListChangeDrafts listDrafts, Check check, Index index, ChangeEdits.Detail editDetail, Move move, @Assisted ChangeResource change) { this.changeApi = changeApi; this.revert = revert; this.reviewers = reviewers; this.revisions = revisions; this.reviewerApi = reviewerApi; this.revisionApi = revisionApi; this.suggestReviewers = suggestReviewers; this.abandon = abandon; this.restore = restore; this.submittedTogether = submittedTogether; this.publishDraftChange = publishDraftChange; this.deleteDraftChange = deleteDraftChange; this.getTopic = getTopic; this.putTopic = putTopic; this.postReviewers = postReviewers; this.changeJson = changeJson; this.postHashtags = postHashtags; this.getHashtags = getHashtags; this.putAssignee = putAssignee; this.getAssignee = getAssignee; this.getPastAssignees = getPastAssignees; this.deleteAssignee = deleteAssignee; this.listComments = listComments; this.listDrafts = listDrafts; this.check = check; this.index = index; this.editDetail = editDetail; this.move = move; this.change = change; } @Override public String id() { return Integer.toString(change.getId().get()); } @Override public RevisionApi current() throws RestApiException { return revision("current"); } @Override public RevisionApi revision(int id) throws RestApiException { return revision(String.valueOf(id)); } @Override public RevisionApi revision(String id) throws RestApiException { try { return revisionApi.create( revisions.parse(change, IdString.fromDecoded(id))); } catch (OrmException | IOException e) { throw new RestApiException("Cannot parse revision", e); } } @Override public ReviewerApi reviewer(String id) throws RestApiException { try { return reviewerApi.create( reviewers.parse(change, IdString.fromDecoded(id))); } catch (OrmException e) { throw new RestApiException("Cannot parse reviewer", e); } } @Override public void abandon() throws RestApiException { abandon(new AbandonInput()); } @Override public void abandon(AbandonInput in) throws RestApiException { try { abandon.apply(change, in); } catch (OrmException | UpdateException e) { throw new RestApiException("Cannot abandon change", e); } } @Override public void restore() throws RestApiException { restore(new RestoreInput()); } @Override public void restore(RestoreInput in) throws RestApiException { try { restore.apply(change, in); } catch (OrmException | UpdateException e) { throw new RestApiException("Cannot restore change", e); } } @Override public void move(String destination) throws RestApiException { MoveInput in = new MoveInput(); in.destinationBranch = destination; move(in); } @Override public void move(MoveInput in) throws RestApiException { try { move.apply(change, in); } catch (OrmException | UpdateException e) { throw new RestApiException("Cannot move change", e); } } @Override public ChangeApi revert() throws RestApiException { return revert(new RevertInput()); } @Override public ChangeApi revert(RevertInput in) throws RestApiException { try { return changeApi.id(revert.apply(change, in)._number); } catch (OrmException | IOException | UpdateException | NoSuchChangeException e) { throw new RestApiException("Cannot revert change", e); } } @Override public List<ChangeInfo> submittedTogether() throws RestApiException { SubmittedTogetherInfo info = submittedTogether( EnumSet.noneOf(ListChangesOption.class), EnumSet.noneOf(SubmittedTogetherOption.class)); return info.changes; } @Override public SubmittedTogetherInfo submittedTogether( EnumSet<SubmittedTogetherOption> options) throws RestApiException { return submittedTogether(EnumSet.noneOf(ListChangesOption.class), options); } @Override public SubmittedTogetherInfo submittedTogether( EnumSet<ListChangesOption> listOptions, EnumSet<SubmittedTogetherOption> submitOptions) throws RestApiException { try { return submittedTogether.get() .addListChangesOption(listOptions) .addSubmittedTogetherOption(submitOptions) .applyInfo(change); } catch (IOException | OrmException e) { throw new RestApiException("Cannot query submittedTogether", e); } } @Override public void publish() throws RestApiException { try { publishDraftChange.apply(change, null); } catch (UpdateException e) { throw new RestApiException("Cannot publish change", e); } } @Override public void delete() throws RestApiException { try { deleteDraftChange.apply(change, null); } catch (UpdateException e) { throw new RestApiException("Cannot delete change", e); } } @Override public String topic() throws RestApiException { return getTopic.apply(change); } @Override public void topic(String topic) throws RestApiException { PutTopic.Input in = new PutTopic.Input(); in.topic = topic; try { putTopic.apply(change, in); } catch (UpdateException e) { throw new RestApiException("Cannot set topic", e); } } @Override public void addReviewer(String reviewer) throws RestApiException { AddReviewerInput in = new AddReviewerInput(); in.reviewer = reviewer; addReviewer(in); } @Override public void addReviewer(AddReviewerInput in) throws RestApiException { try { postReviewers.apply(change, in); } catch (OrmException | IOException | UpdateException e) { throw new RestApiException("Cannot add change reviewer", e); } } @Override public SuggestedReviewersRequest suggestReviewers() throws RestApiException { return new SuggestedReviewersRequest() { @Override public List<SuggestedReviewerInfo> get() throws RestApiException { return ChangeApiImpl.this.suggestReviewers(this); } }; } @Override public SuggestedReviewersRequest suggestReviewers(String query) throws RestApiException { return suggestReviewers().withQuery(query); } private List<SuggestedReviewerInfo> suggestReviewers(SuggestedReviewersRequest r) throws RestApiException { try { suggestReviewers.setQuery(r.getQuery()); suggestReviewers.setLimit(r.getLimit()); return suggestReviewers.apply(change); } catch (OrmException | IOException e) { throw new RestApiException("Cannot retrieve suggested reviewers", e); } } @Override public ChangeInfo get(EnumSet<ListChangesOption> s) throws RestApiException { try { return changeJson.create(s).format(change); } catch (OrmException e) { throw new RestApiException("Cannot retrieve change", e); } } @Override public ChangeInfo get() throws RestApiException { return get(EnumSet.complementOf(EnumSet.of(ListChangesOption.CHECK))); } @Override public EditInfo getEdit() throws RestApiException { try { Response<EditInfo> edit = editDetail.apply(change); return edit.isNone() ? null : edit.value(); } catch (IOException | OrmException e) { throw new RestApiException("Cannot retrieve change edit", e); } } @Override public ChangeInfo info() throws RestApiException { return get(EnumSet.noneOf(ListChangesOption.class)); } @Override public void setHashtags(HashtagsInput input) throws RestApiException { try { postHashtags.apply(change, input); } catch (RestApiException | UpdateException e) { throw new RestApiException("Cannot post hashtags", e); } } @Override public Set<String> getHashtags() throws RestApiException { try { return getHashtags.apply(change).value(); } catch (IOException | OrmException e) { throw new RestApiException("Cannot get hashtags", e); } } @Override public AccountInfo setAssignee(AssigneeInput input) throws RestApiException { try { return putAssignee.apply(change, input).value(); } catch (UpdateException | IOException | OrmException e) { throw new RestApiException("Cannot set assignee", e); } } @Override public AccountInfo getAssignee() throws RestApiException { try { Response<AccountInfo> r = getAssignee.apply(change); return r.isNone() ? null : r.value(); } catch (OrmException e) { throw new RestApiException("Cannot get assignee", e); } } @Override public List<AccountInfo> getPastAssignees() throws RestApiException { try { return getPastAssignees.apply(change).value(); } catch (Exception e) { throw new RestApiException("Cannot get past assignees", e); } } @Override public AccountInfo deleteAssignee() throws RestApiException { try { Response<AccountInfo> r = deleteAssignee.apply(change, null); return r.isNone() ? null : r.value(); } catch (UpdateException e) { throw new RestApiException("Cannot delete assignee", e); } } @Override public Map<String, List<CommentInfo>> comments() throws RestApiException { try { return listComments.apply(change); } catch (OrmException e) { throw new RestApiException("Cannot get comments", e); } } @Override public Map<String, List<CommentInfo>> drafts() throws RestApiException { try { return listDrafts.apply(change); } catch (OrmException e) { throw new RestApiException("Cannot get drafts", e); } } @Override public ChangeInfo check() throws RestApiException { try { return check.apply(change).value(); } catch (OrmException e) { throw new RestApiException("Cannot check change", e); } } @Override public ChangeInfo check(FixInput fix) throws RestApiException { try { return check.apply(change, fix).value(); } catch (OrmException e) { throw new RestApiException("Cannot check change", e); } } @Override public void index() throws RestApiException { try { index.apply(change, new Index.Input()); } catch (IOException | OrmException e) { throw new RestApiException("Cannot index change", e); } } }
32.39645
83
0.734186
68e8cef6acde90aa28365387526d76b198f5676f
10,617
/* * Copyright (C) 2017 Synacts GmbH, Switzerland (info@synacts.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // TODO: //package net.digitalid.core.client; // //import java.io.IOException; //import java.sql.SQLException; // //import javax.annotation.Nonnull; //import javax.annotation.Nullable; // //import net.digitalid.utility.annotations.method.Pure; //import net.digitalid.utility.collections.list.FreezableArrayList; //import net.digitalid.utility.collections.list.ReadOnlyList; //import net.digitalid.utility.freezable.annotations.Frozen; //import net.digitalid.utility.exceptions.ExternalException; //import net.digitalid.utility.validation.annotations.elements.NonNullableElements; //import net.digitalid.utility.validation.annotations.type.Immutable; // //import net.digitalid.database.annotations.transaction.NonCommitting; // //import net.digitalid.core.entity.Entity; //import net.digitalid.core.entity.NonHostEntity; //import net.digitalid.core.identification.Category; //import net.digitalid.core.identification.identifier.HostIdentifier; //import net.digitalid.core.identification.identifier.InternalNonHostIdentifier; //import net.digitalid.core.identification.identifier.NonHostIdentifier; //import net.digitalid.core.identification.identity.NonHostIdentity; //import net.digitalid.core.identification.identity.SemanticType; //import net.digitalid.core.packet.exceptions.InvalidDeclarationException; //import net.digitalid.core.service.CoreService; // ///** // * Initializes a new account with the given states. // */ //@Immutable //public final class AccountInitialize extends CoreServiceInternalAction { // // /** // * Stores the semantic type {@code state.initialize.account@core.digitalid.net}. // */ // private static final @Nonnull SemanticType STATE = SemanticType.map("state.initialize.account@core.digitalid.net").load(TupleWrapper.XDF_TYPE, Predecessor.TYPE, CoreService.STATE); // // /** // * Stores the semantic type {@code initialize.account@core.digitalid.net}. // */ // public static final @Nonnull SemanticType TYPE = SemanticType.map("initialize.account@core.digitalid.net").load(ListWrapper.XDF_TYPE, STATE); // // // /** // * Stores the states to merge into the new account. // */ // private final @Nonnull @Frozen @NonNullableElements ReadOnlyList<ReadOnlyPair<Predecessor, Block>> states; // // /** // * Creates an action to initialize a new account. // * // * @param role the role to which this handler belongs. // * @param states the states to merge into the new account. // */ // @NonCommitting // AccountInitialize(@Nonnull NativeRole role, @Nonnull @Frozen @NonNullableElements ReadOnlyList<ReadOnlyPair<Predecessor, Block>> states) throws ExternalException { // super(role); // // this.states = states; // } // // /** // * Creates an action that decodes the given block. // * // * @param entity the entity to which this handler belongs. // * @param signature the signature of this handler (or a dummy that just contains a subject). // * @param recipient the recipient of this method. // * @param block the content which is to be decoded. // * // * @require signature.hasSubject() : "The signature has a subject."; // * @require block.getType().isBasedOn(TYPE) : "The block is based on the indicated type."; // * // * @ensure hasSignature() : "This handler has a signature."; // */ // @NonCommitting // private AccountInitialize(@Nonnull Entity entity, @Nonnull SignatureWrapper signature, @Nonnull HostIdentifier recipient, @Nonnull Block block) throws ExternalException { // super(entity, signature, recipient); // // final @Nonnull InternalNonHostIdentifier subject = getSubject().castTo(InternalNonHostIdentifier.class); // if (isOnHost() && FreezablePredecessors.exist(subject)) { throw RequestException.get(RequestErrorCode.METHOD, "The subject " + subject + " is already initialized."); } // // final @Nonnull Category category = entity.getIdentity().getCategory(); // final @Nonnull ReadOnlyList<Block> elements = ListWrapper.decodeNonNullableElements(block); // if (elements.size() > 1 && !category.isInternalPerson()) { throw InvalidDeclarationException.get("Only internal persons may have more than one predecessor.", subject); } // // final @Nonnull FreezableList<ReadOnlyPair<Predecessor, Block>> states = FreezableArrayList.getWithCapacity(elements.size()); // for (final @Nonnull Block element : elements) { // final @Nonnull TupleWrapper tuple = TupleWrapper.decode(element); // final @Nonnull Predecessor predecessor = new Predecessor(tuple.getNonNullableElement(0)); // final @Nonnull NonHostIdentifier identifier = predecessor.getIdentifier(); // final @Nonnull NonHostIdentity identity = identifier.getIdentity(); // final @Nonnull String message = "The claimed predecessor " + identifier + " of " + subject; // if (!(identity.getCategory().isExternalPerson() && category.isInternalPerson() || identity.getCategory() == category)) { throw InvalidDeclarationException.get(message + " has a wrong category.", subject); } // if (identifier instanceof InternalNonHostIdentifier) { // if (!FreezablePredecessors.get((InternalNonHostIdentifier) identifier).equals(predecessor.getPredecessors())) { throw InvalidDeclarationException.get(message + " has other predecessors.", subject); } // } else { // if (!predecessor.getPredecessors().isEmpty()) { throw InvalidDeclarationException.get(message + " is an external person and may not have any predecessors.", subject); } // } // if (!Successor.getReloaded(identifier).equals(subject)) { throw InvalidDeclarationException.get(message + " does not link back.", subject); } // states.add(new FreezablePair<>(predecessor, tuple.getNullableElement(1)).freeze()); // } // this.states = states.freeze(); // } // // @Pure // @Override // public @Nonnull Block toBlock() { // final @Nonnull FreezableList<Block> elements = FreezableArrayList.getWithCapacity(states.size()); // for (final @Nonnull ReadOnlyPair<Predecessor, Block> state : states) { // elements.add(TupleWrapper.encode(STATE, state.getElement0(), state.getElement1()).toBlock()); // } // return ListWrapper.encode(TYPE, elements.freeze()); // } // // @Pure // @Override // public @Nonnull String getDescription() { // return "Initializes the new account."; // } // // // @Pure // @Override // public @Nullable PublicKey getPublicKey() { // return null; // } // // @Pure // @Override // public @Nonnull ReadOnlyAgentPermissions getRequiredPermissionsToSeeAudit() { // return FreezableAgentPermissions.GENERAL_WRITE; // } // // @Pure // @Override // public @Nonnull Restrictions getRequiredRestrictionsToSeeAudit() { // return Restrictions.MAX; // } // // // @Override // @NonCommitting // protected void executeOnBoth() throws DatabaseException { // final @Nonnull NonHostEntity entity = getNonHostEntity(); // // try { // @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") // final @Nonnull FreezablePredecessors predecessors = new FreezablePredecessors(states.size()); // final @Nonnull FreezableList<NonHostIdentity> identities = FreezableArrayList.getWithCapacity(states.size()); // for (final @Nonnull ReadOnlyPair<Predecessor, Block> state : states) { // final @Nonnull Predecessor predecessor = state.getElement0(); // identities.add(predecessor.getIdentifier().getIdentity().castTo(NonHostIdentity.class)); // CoreService.SERVICE.addState(entity, state.getElement1()); // predecessors.add(predecessor); // } // Mapper.mergeIdentities(identities.freeze(), entity.getIdentity()); // predecessors.set(getSubject().castTo(InternalNonHostIdentifier.class), null); // } catch (@Nonnull IOException | RequestException | ExternalException exception) { // throw new SQLException("A problem occurred while adding a state.", exception); // } // // if (states.isEmpty()) { PasswordModule.set(entity, ""); } // } // // @Pure // @Override // public boolean interferesWith(@Nonnull Action action) { // return false; // } // // @Pure // @Override // public @Nonnull AccountClose getReverse() { // return new AccountClose(getRole().toNativeRole(), null); // } // // // @Pure // @Override // public boolean equals(@Nullable Object object) { // return protectedEquals(object) && object instanceof AccountInitialize && this.states.equals(((AccountInitialize) object).states); // } // // @Pure // @Override // public int hashCode() { // return 89 * protectedHashCode() + states.hashCode(); // } // // // @Pure // @Override // public @Nonnull SemanticType getType() { // return TYPE; // } // // @Pure // @Override // public @Nonnull StateModule getModule() { // return CoreService.SERVICE; // } // // /** // * The factory class for the surrounding method. // */ // private static final class Factory extends Method.Factory { // // static { Method.add(TYPE, new Factory()); } // // @Pure // @Override // @NonCommitting // protected @Nonnull Method create(@Nonnull Entity entity, @Nonnull SignatureWrapper signature, @Nonnull HostIdentifier recipient, @Nonnull Block block) throws ExternalException { // return new AccountInitialize(entity, signature, recipient, block); // } // // } // //}
44.2375
220
0.667326
1c899cbe7b46a6324011d4c71421c157459ef65a
641
package xyz.brassgoggledcoders.streetsweeper; import net.minecraft.data.DataGenerator; import net.minecraft.data.EntityTypeTagsProvider; import net.minecraft.entity.EntityType; import net.minecraftforge.common.data.ExistingFileHelper; public class SSEntityTagsProvider extends EntityTypeTagsProvider { public SSEntityTagsProvider(DataGenerator generator, ExistingFileHelper existingFileHelper) { super(generator, StreetSweeper.MODID, existingFileHelper); } @Override protected void registerTags() { this.getOrCreateBuilder(StreetSweeper.SWEEPABLES).add(EntityType.ITEM, EntityType.EXPERIENCE_ORB); } }
35.611111
106
0.808112
60b106b08083351945b538a9283e291bb8e1914e
525
package team.flint.flint.model.table; import lombok.Getter; import lombok.Setter; import java.util.Date; @Getter @Setter public class ResourceAuthority { private Integer resourceId; /** * 资源名字 */ private String name; /** * 资源路径 */ private String path; private Long authorityId; /** * 0 禁用 1启用 */ private Integer status; /** * 0 禁用 1启用 */ private String statusLabel; /** * 创建时间 */ private Date createTime; }
12.804878
37
0.56
4af9b8d321f629c8738693fb55a96534e8ca89b5
828
package kungzhi.muse.osc.transform; import com.illposed.osc.OSCMessage; import kungzhi.muse.model.Battery; import kungzhi.muse.runtime.Transformer; import static kungzhi.muse.osc.service.MessageAddress.BATTERY; import static kungzhi.muse.osc.transform.MessageHelper.argumentAt; @Transformer(BATTERY) public class BatteryTransformer implements MessageTransformer<Battery> { @Override public Battery fromMessage(long time, OSCMessage message) throws Exception { return new Battery(time) .withStateOfCharge(argumentAt(message, Integer.class, 0)) .withFuelGaugeVoltage(argumentAt(message, Integer.class, 1)) .withAdcVoltage(argumentAt(message, Integer.class, 2)) .withTemperature(argumentAt(message, Integer.class, 3)); } }
34.5
76
0.719807
61ee5ffcf0979ecf625f008bc182bb507c0bcadf
10,150
/** * 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.knox.gateway.deploy.impl; import org.apache.knox.gateway.config.GatewayConfig; import org.apache.knox.gateway.config.impl.GatewayConfigImpl; import org.apache.knox.gateway.deploy.DeploymentContext; import org.apache.knox.gateway.deploy.DeploymentException; import org.apache.knox.gateway.deploy.ServiceDeploymentContributorBase; import org.apache.knox.gateway.descriptor.FilterDescriptor; import org.apache.knox.gateway.descriptor.FilterParamDescriptor; import org.apache.knox.gateway.descriptor.ResourceDescriptor; import org.apache.knox.gateway.filter.XForwardedHeaderFilter; import org.apache.knox.gateway.filter.rewrite.api.CookieScopeServletFilter; import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor; import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory; import org.apache.knox.gateway.service.definition.Policy; import org.apache.knox.gateway.service.definition.Rewrite; import org.apache.knox.gateway.service.definition.Route; import org.apache.knox.gateway.service.definition.ServiceDefinition; import org.apache.knox.gateway.topology.Application; import org.apache.knox.gateway.topology.Service; import org.apache.knox.gateway.topology.Version; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; public class ApplicationDeploymentContributor extends ServiceDeploymentContributorBase { private static final String SERVICE_DEFINITION_FILE_NAME = "service.xml"; private static final String REWRITE_RULES_FILE_NAME = "rewrite.xml"; private static final String XFORWARDED_FILTER_NAME = "XForwardedHeaderFilter"; private static final String XFORWARDED_FILTER_ROLE = "xforwardedheaders"; private static final String COOKIE_SCOPING_FILTER_NAME = "CookieScopeServletFilter"; private static final String COOKIE_SCOPING_FILTER_ROLE = "cookiescopef"; private ServiceDefinition serviceDefinition; private UrlRewriteRulesDescriptor serviceRules; private static ServiceDefinition loadServiceDefinition( Application application, File file ) throws JAXBException, FileNotFoundException, IOException { ServiceDefinition definition; if( !file.exists() ) { definition = new ServiceDefinition(); definition.setName( application.getName() ); List<Route> routes = new ArrayList<Route>(1); Route route; route = new Route(); route.setPath( "/?**" ); routes.add( route ); route = new Route(); route.setPath( "/**?**" ); routes.add( route ); definition.setRoutes( routes ); } else { JAXBContext context = JAXBContext.newInstance( ServiceDefinition.class ); Unmarshaller unmarshaller = context.createUnmarshaller(); try( FileInputStream inputStream = new FileInputStream( file ) ) { definition = (ServiceDefinition) unmarshaller.unmarshal( inputStream ); } } return definition; } private static UrlRewriteRulesDescriptor loadRewriteRules( Application application, File file ) throws IOException { UrlRewriteRulesDescriptor rules; if( !file.exists() ) { rules = UrlRewriteRulesDescriptorFactory.load( "xml", new StringReader( "<rules/>" ) ); } else { InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); rules = UrlRewriteRulesDescriptorFactory.load( "xml", reader ); reader.close(); } return rules; } public ApplicationDeploymentContributor( GatewayConfig config, Application application ) throws DeploymentException { try { File appsDir = new File( config.getGatewayApplicationsDir() ); File appDir = new File( appsDir, application.getName() ); File serviceFile = new File( appDir, SERVICE_DEFINITION_FILE_NAME ); File rewriteFile = new File( appDir, REWRITE_RULES_FILE_NAME ); serviceDefinition = loadServiceDefinition( application, serviceFile ); serviceRules = loadRewriteRules( application, rewriteFile ); } catch ( IOException e ) { throw new DeploymentException( "Failed to deploy application: " + application.getName(), e ); } catch ( JAXBException e ){ throw new DeploymentException( "Failed to deploy application: " + application.getName(), e ); } } @Override public String getRole() { return serviceDefinition.getRole(); } @Override public String getName() { return serviceDefinition.getName(); } @Override public Version getVersion() { return new Version(serviceDefinition.getVersion()); } @Override public void contributeService(DeploymentContext context, Service service) throws Exception { contributeRewriteRules(context, service); contributeResources(context, service); } private void contributeRewriteRules(DeploymentContext context, Service service) { if ( serviceRules != null ) { UrlRewriteRulesDescriptor clusterRules = context.getDescriptor("rewrite"); // Coverity CID 1352312 if( clusterRules != null ) { clusterRules.addRules( serviceRules ); } } } private void contributeResources(DeploymentContext context, Service service) { Map<String, String> filterParams = new HashMap<>(); List<Route> bindings = serviceDefinition.getRoutes(); for ( Route binding : bindings ) { List<Rewrite> filters = binding.getRewrites(); if ( filters != null && !filters.isEmpty() ) { filterParams.clear(); for ( Rewrite filter : filters ) { filterParams.put(filter.getTo(), filter.getApply()); } } try { contributeResource(context, service, binding, filterParams); } catch ( URISyntaxException e ) { e.printStackTrace(); } } } private void contributeResource( DeploymentContext context, Service service, Route binding, Map<String, String> filterParams) throws URISyntaxException { List<FilterParamDescriptor> params = new ArrayList<FilterParamDescriptor>(); ResourceDescriptor resource = context.getGatewayDescriptor().addResource(); resource.role(service.getRole()); resource.pattern(binding.getPath()); //add x-forwarded filter if enabled in config if (context.getGatewayConfig().isXForwardedEnabled()) { resource.addFilter().name(XFORWARDED_FILTER_NAME).role(XFORWARDED_FILTER_ROLE).impl(XForwardedHeaderFilter.class); } if (context.getGatewayConfig().isCookieScopingToPathEnabled()) { FilterDescriptor filter = resource.addFilter().name(COOKIE_SCOPING_FILTER_NAME).role(COOKIE_SCOPING_FILTER_ROLE).impl(CookieScopeServletFilter.class); filter.param().name(GatewayConfigImpl.HTTP_PATH).value(context.getGatewayConfig().getGatewayPath()); } List<Policy> policyBindings = binding.getPolicies(); if ( policyBindings == null ) { policyBindings = serviceDefinition.getPolicies(); } if ( policyBindings == null ) { //add default set addDefaultPolicies(context, service, filterParams, params, resource); } else { addPolicies(context, service, filterParams, params, resource, policyBindings); } } private void addPolicies( DeploymentContext context, Service service, Map<String, String> filterParams, List<FilterParamDescriptor> params, ResourceDescriptor resource, List<Policy> policyBindings) throws URISyntaxException { for ( Policy policyBinding : policyBindings ) { String role = policyBinding.getRole(); if ( role == null ) { throw new IllegalArgumentException("Policy defined has no role for service " + service.getName()); } role = role.trim().toLowerCase(Locale.ROOT); if ( "rewrite".equals(role) ) { addRewriteFilter(context, service, filterParams, params, resource); } else if ( topologyContainsProviderType(context, role) ) { context.contributeFilter(service, resource, role, policyBinding.getName(), null); } } } private void addDefaultPolicies( DeploymentContext context, Service service, Map<String, String> filterParams, List<FilterParamDescriptor> params, ResourceDescriptor resource) throws URISyntaxException { addWebAppSecFilters(context, service, resource); addAuthenticationFilter(context, service, resource); addRewriteFilter(context, service, filterParams, params, resource); addIdentityAssertionFilter(context, service, resource); addAuthorizationFilter(context, service, resource); } private void addRewriteFilter( DeploymentContext context, Service service, Map<String, String> filterParams, List<FilterParamDescriptor> params, ResourceDescriptor resource) throws URISyntaxException { if ( !filterParams.isEmpty() ) { for ( Map.Entry<String, String> filterParam : filterParams.entrySet() ) { params.add(resource.createFilterParam().name(filterParam.getKey()).value(filterParam.getValue())); } } addRewriteFilter(context, service, resource, params); } }
43.939394
227
0.744236
b34df914b40e49abf95911a82928114247e1d6d2
2,211
/* * Copyright 2008-2009 LinkedIn, 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 voldemort.serialization; import voldemort.utils.ByteUtils; import voldemort.versioning.VectorClock; import voldemort.versioning.Version; import voldemort.versioning.Versioned; /** * A Serializer that removes the Versioned wrapper and delegates to a * user-supplied serializer to deal with the remaining bytes * * * @param <T> The Versioned type */ public class VersionedSerializer<T> implements Serializer<Versioned<T>> { private final Serializer<T> innerSerializer; public VersionedSerializer(Serializer<T> innerSerializer) { this.innerSerializer = innerSerializer; } public byte[] toBytes(Versioned<T> versioned) { byte[] versionBytes = null; if(versioned.getVersion() == null) versionBytes = new byte[] { -1 }; else versionBytes = ((VectorClock) versioned.getVersion()).toBytes(); byte[] objectBytes = innerSerializer.toBytes(versioned.getValue()); return ByteUtils.cat(versionBytes, objectBytes); } public Versioned<T> toObject(byte[] bytes) { VectorClock vectorClock = getVectorClock(bytes); int size = 1; if(vectorClock != null) size = vectorClock.sizeInBytes(); T t = innerSerializer.toObject(ByteUtils.copy(bytes, size, bytes.length)); return new Versioned<T>(t, vectorClock); } public Version getVersion(byte[] bytes) { return getVectorClock(bytes); } private VectorClock getVectorClock(byte[] bytes) { if(bytes[0] >= 0) return new VectorClock(bytes); return null; } }
31.140845
82
0.687472
2fe12d98c13ea5796c4c7a7c8c73b4e3c42904da
742
package tech.jhipster.lite.generator.server.springboot.cache.jcache.infrastructure.config; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import tech.jhipster.lite.IntegrationTest; import tech.jhipster.lite.generator.server.springboot.cache.jcache.domain.SpringBootJCacheDomainService; @IntegrationTest class SpringBootJCacheBeanConfigurationIT { @Autowired ApplicationContext applicationContext; @Test void shouldGetBean() { assertThat(applicationContext.getBean("springBootJCacheService")).isNotNull().isInstanceOf(SpringBootJCacheDomainService.class); } }
33.727273
132
0.84097
144ec33a43dde800f200b7d5c8ee7c1d9925d062
2,093
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license ******************************************************************************/ package org.caleydo.vis.lineup.internal.prefs; import java.util.ArrayList; import java.util.Collection; import org.caleydo.vis.lineup.internal.Activator; import org.eclipse.jface.preference.ColorFieldEditor; import org.eclipse.jface.preference.FieldEditorPreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** * @author Samuel Gratzl * */ public class MyPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { private Collection<Label> labels = new ArrayList<>(); public MyPreferencePage() { super(GRID); } @Override public void createFieldEditors() { final Composite parent = getFieldEditorParent(); createLabel("Transitions", parent); addField(new ColorFieldEditor("transitions.color.up", "Rank Increase", parent)); addField(new ColorFieldEditor("transitions.color.down", "Rank Decrease", parent)); } private void createLabel(String label, final Composite parent) { Label l = new Label(parent, SWT.NONE); l.setText(label); l.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); labels.add(l); } @Override protected void adjustGridLayout() { super.adjustGridLayout(); int cols = ((GridLayout) (getFieldEditorParent().getLayout())).numColumns; for (Label label : labels) ((GridData) label.getLayoutData()).horizontalSpan = cols; } @Override public void init(IWorkbench workbench) { setPreferenceStore(Activator.getDefault().getPreferenceStore()); setDescription("LineUp View settings"); } }
33.758065
101
0.70903
26f694b5f4ef04823ac4d4482853b0cac21f4b97
3,969
package cl.zpricing.avant.servicios.ibatis; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import cl.zpricing.avant.model.Parametro; import cl.zpricing.avant.servicios.ServiciosRevenueManager; public class ServiciosRevenueManagerImpl extends SqlMapClientDaoSupport implements ServiciosRevenueManager{ private Logger log = (Logger) Logger.getLogger(this.getClass()); /* (non-Javadoc) * @see cl.zpricing.revman.servicios.ServiciosRevenueManager#obtenerParametro(java.lang.String, java.lang.String) */ public Parametro obtenerParametro(String sistema, String subSistema){ /* log.debug("Iniciando obtenerParametro..."); log.debug("Sistema : [" + sistema + "]"); log.debug("SubSistema : [" + subSistema + "]"); */ Map<String, Object> param = new HashMap<String, Object>(2); param.put("sistema", sistema); param.put("subSistema", subSistema); Object result = getSqlMapClientTemplate().queryForObject("obtenerParametro", param); /*log.debug("result : [" + result + "]");*/ return (Parametro)result; } /* (non-Javadoc) * @see cl.zpricing.revman.servicios.ServiciosRevenueManager#obtenerStringParametro(java.lang.String, java.lang.String) */ @Override public String obtenerStringParametro(String sistema, String subSistema) { Parametro reg = this.obtenerParametro(sistema, subSistema); log.debug("sistema = "+sistema+"\tsubsistema = "+subSistema); log.debug(reg==null?"reg = null":"reg = not null"); return reg == null ? null : reg.getCodigo(); } /* (non-Javadoc) * @see cl.zpricing.revman.servicios.ServiciosRevenueManager#obtenerIntParametro(java.lang.String, java.lang.String) */ public int obtenerIntParametro(String sistema, String subSistema) throws Exception{ Parametro reg = this.obtenerParametro(sistema, subSistema); int resultado = 0; try{ resultado = Integer.parseInt(reg.getCodigo()); }catch(Exception e){ throw e; } return resultado; } /* (non-Javadoc) * @see cl.zpricing.revman.servicios.ServiciosRevenueManager#obtenerDoubleParametro(java.lang.String, java.lang.String) */ public double obtenerDoubleParametro(String sistema, String subSistema) throws Exception{ Parametro reg = this.obtenerParametro(sistema, subSistema); double resultado = 0; try{ resultado = Double.parseDouble(reg.getCodigo()); }catch(Exception e){ throw e; } return resultado; } /* (non-Javadoc) * @see cl.zpricing.revman.servicios.ServiciosRevenueManager#obtenerParametro(java.lang.String) */ @SuppressWarnings("unchecked") public ArrayList<Parametro> obtenerParametro(String sistema){ ArrayList<Parametro> parametros = (ArrayList<Parametro>) getSqlMapClientTemplate().queryForList("obtenerParametrosSistema", sistema); return parametros; } /* (non-Javadoc) * @see cl.zpricing.revman.servicios.ServiciosRevenueManager#obtenerSistemas() */ @SuppressWarnings("unchecked") @Override public ArrayList<String> obtenerSistemas() { ArrayList<String> sistemas = (ArrayList<String>) getSqlMapClientTemplate().queryForList("obtenerSistemas"); return sistemas; } /* (non-Javadoc) * @see cl.zpricing.revman.servicios.ServiciosRevenueManager#actualizarParametro(cl.zpricing.revman.model.Parametro) */ @Override public void actualizarParametro(Parametro parametro) { log.debug("actualizarParametro..."); log.debug("Sistema: " + parametro.getSistema()); log.debug("SubSistema: " + parametro.getSubSistema()); log.debug("codigo: " + parametro.getCodigo()); getSqlMapClientTemplate().update("actualizarParametro", parametro); } /* (non-Javadoc) * @see cl.zpricing.revman.servicios.ServiciosRevenueManager#nuevoParametro(cl.zpricing.revman.model.Parametro) */ @Override public void nuevoParametro(Parametro parametro) { getSqlMapClientTemplate().insert("nuevoParametro", parametro); } }
33.923077
135
0.746788
7cf8ffb4d8b84d5b34c6f7d49caa0219aae6aa00
58,708
package totok.sulistyo.s0; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.RotateDrawable; import android.graphics.drawable.VectorDrawable; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat; import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.text.DecimalFormat; public class StakeOut extends AppCompatActivity { Button btocc, btso, btsr, btsd, btbs, btmsr; final Context context = this; DataHelper dbcenter; private AnimationDrawable anim; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stake_out); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); btocc = findViewById(R.id.btOcc); btso = findViewById(R.id.btSO); btsr = findViewById(R.id.btSR); btsd = findViewById(R.id.btSD); btbs = findViewById(R.id.btbs); btmsr = findViewById(R.id.btmsr); final ImageView iv = findViewById(R.id.iV5); final ImageView ivi = findViewById(R.id.iV6); final TextView tvclk = (TextView)findViewById(R.id.tvclick); tvclk.setVisibility(View.INVISIBLE); iv.setImageDrawable(null); ivi.setImageDrawable(null); // iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_fsbs1)); dbcenter = new DataHelper(this); final SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); final SharedPreferences.Editor editor = pref.edit(); final String id_pro=getIntent().getStringExtra("id"); final String pro=getIntent().getStringExtra("pro"); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(StakeOut.this, Project_Activity.class); i.putExtra("no",id_pro); i.putExtra("nama_pro",pro); startActivity(i); finish(); } }); btocc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.occupy); dialog.setTitle("Title..."); final EditText etRemarks =(EditText)dialog.findViewById(R.id.etRemarks); etRemarks.setText(String.valueOf(pref.getString("ket", ""))); final EditText etHI =(EditText)dialog.findViewById(R.id.etHI); etHI.setText(String.valueOf(pref.getFloat("hi", (float) 0.000))); final EditText etXA =(EditText)dialog.findViewById(R.id.etXA); etXA.setText(String.valueOf(pref.getFloat("xA", (float) 0.000))); final EditText etYA =(EditText)dialog.findViewById(R.id.etYA); etYA.setText(String.valueOf(pref.getFloat("yA", (float) 0.000))); final EditText etZA =(EditText)dialog.findViewById(R.id.etZA); etZA.setText(String.valueOf(pref.getFloat("zA", (float) 0.000))); Button btclr=(Button)dialog.findViewById(R.id.btclr); btclr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { etRemarks.setText(""); etHI.setText(""); etXA.setText(""); etYA.setText(""); etZA.setText(""); } }); Button btsave=(Button)dialog.findViewById(R.id.btsave); btsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String ket=etRemarks.getText().toString(); float hi=Float.parseFloat(etHI.getText().toString()); float xA=Float.parseFloat(etXA.getText().toString()); float yA=Float.parseFloat(etYA.getText().toString()); float zA=Float.parseFloat(etZA.getText().toString()); editor.putString("ket", ket); editor.putFloat("hi", hi); editor.putFloat("xA", xA); editor.putFloat("yA", yA); editor.putFloat("zA", zA); editor.commit(); dialog.dismiss(); } }); Button btcancel=(Button)dialog.findViewById(R.id.btcancel); btcancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.show(); } }); btbs.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.bs); dialog.setTitle("Title..."); Button btcancel=(Button)dialog.findViewById(R.id.btcancel); Button btA=(Button)dialog.findViewById(R.id.btA); Button btC=(Button)dialog.findViewById(R.id.btC); btA.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog2 = new Dialog(context); dialog2.setContentView(R.layout.bsa); dialog2.setTitle("Title..."); final EditText etD=(EditText)dialog2.findViewById(R.id.etX); etD.setText(String.valueOf(pref.getInt("dBS",0))); final EditText etM=(EditText)dialog2.findViewById(R.id.etY); etM.setText(String.valueOf(pref.getInt("mBS", 0))); final EditText etS=(EditText)dialog2.findViewById(R.id.etZ); etS.setText(String.valueOf(pref.getInt("sBS", 0))); Button btclr=(Button)dialog2.findViewById(R.id.btclr); btclr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { etD.setText(""); etM.setText(""); etS.setText(""); } }); Button btsave=(Button)dialog2.findViewById(R.id.btsave); btsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int dBS=Integer.parseInt(etD.getText().toString()); int mBS=Integer.parseInt(etM.getText().toString()); int sBS=Integer.parseInt(etS.getText().toString()); editor.putInt("dBS", dBS); editor.putInt("mBS", mBS); editor.putInt("sBS", sBS); editor.remove("xBS"); editor.remove("yBS"); editor.remove("zBS"); editor.commit(); final Dialog dialog3 = new Dialog(context); dialog3.setContentView(R.layout.kosong); dialog3.setTitle("Title..."); RelativeLayout cl =(RelativeLayout)dialog3.findViewById(R.id.cL1); cl.setVisibility(View.GONE); TextView textInfo=(TextView)dialog3.findViewById(R.id.txtInfo); Button btok=(Button)dialog3.findViewById(R.id.btOK); textInfo.setText("\bRotate & Turn Telescope align to Back Sight Peg/Pole/Stake, then fasten the horisontal lock and press button 0-SET in LCD Panel of Your Theodolite, and make sure the HR has value 0º0'0'', then release horisontal lock. \n " + "\bPutar & Luruskan Teleskop dengan Patok Back Sight, kemudian kencangkan penguci horisontal dan tekan tombol 0-SET pada panel LCD Theodolite anda, dan pastikan nilai HR 0º0'0'', kemudian lepas kunci horisontal."); btok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog3.dismiss(); } }); ImageView img = (ImageView)dialog3.findViewById(R.id.simple_anim); img.setImageDrawable(null); img.setBackgroundResource(R.drawable.anim); AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground(); frameAnimation.start(); LinearLayout ll = (LinearLayout)dialog3.findViewById(R.id.lL1); ll.setVisibility(View.VISIBLE); TextView lcd= (TextView)dialog3.findViewById(R.id.tvHR); lcd.setText("HR 0º0'0''"); dialog3.show(); dialog2.dismiss(); } }); Button btcancel=(Button)dialog2.findViewById(R.id.btcancel); btcancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog2.dismiss(); } }); dialog2.show(); dialog.dismiss(); } }); btC.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog2 = new Dialog(context); dialog2.setContentView(R.layout.bsc); dialog2.setTitle("Title..."); final EditText etX=(EditText)dialog2.findViewById(R.id.etX); etX.setText(String.valueOf(pref.getFloat("xBS",0))); final EditText etY=(EditText)dialog2.findViewById(R.id.etY); etY.setText(String.valueOf(pref.getFloat("yBS", 0))); final EditText etZ=(EditText)dialog2.findViewById(R.id.etZ); etZ.setText(String.valueOf(pref.getFloat("zBS", 0))); Button btclr=(Button)dialog2.findViewById(R.id.btclr); btclr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { etX.setText(""); etY.setText(""); etZ.setText(""); } }); Button btsave=(Button)dialog2.findViewById(R.id.btsave); btsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { float xBS=Float.parseFloat(etX.getText().toString()); float yBS=Float.parseFloat(etY.getText().toString()); float zBS=Float.parseFloat(etZ.getText().toString()); editor.putFloat("xBS", xBS); editor.putFloat("yBS", yBS); editor.putFloat("zBS", zBS); editor.remove("dBS"); editor.remove("mBS"); editor.remove("sBS"); editor.commit(); final Dialog dialog3 = new Dialog(context); dialog3.setContentView(R.layout.kosong); dialog3.setTitle("Title..."); RelativeLayout cl =(RelativeLayout)dialog3.findViewById(R.id.cL1); cl.setVisibility(View.GONE); TextView textInfo=(TextView)dialog3.findViewById(R.id.txtInfo); Button btok=(Button)dialog3.findViewById(R.id.btOK); textInfo.setText("\bRotate & Turn Telescope align to Back Sight Peg/Pole/Stake, then fasten the horisontal lock and press button 0-SET in LCD Panel of Your Theodolite, and make sure the HR has value 0º0'0'', then release horisontal lock \n " + "\bPutar & Luruskan Teleskop dengan Patok Back Sight, kemudian kencangkan penguci horisontal dan tekan tombol 0-SET pada panel LCD Theodolite anda, dan pastkan nilai HR 0º0'0'', kemudia lepas kunci horisontal"); btok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog3.dismiss(); } }); ImageView img = (ImageView)dialog3.findViewById(R.id.simple_anim); img.setImageDrawable(null); img.setBackgroundResource(R.drawable.anim); AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground(); frameAnimation.start(); LinearLayout ll = (LinearLayout)dialog3.findViewById(R.id.lL1); ll.setVisibility(View.VISIBLE); TextView lcd= (TextView)dialog3.findViewById(R.id.tvHR); lcd.setText("HR 0º0'0''"); dialog3.show(); dialog3.show(); dialog2.dismiss(); } }); Button btcancel=(Button)dialog2.findViewById(R.id.btcancel); btcancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog2.dismiss(); } }); dialog2.show(); dialog.dismiss(); } }); btcancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.show(); } }); btso.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.so); dialog.setTitle("Title..."); final EditText etKodeSO=(EditText)dialog.findViewById(R.id.etKODESO); etKodeSO.setText(String.valueOf(pref.getString("kodeSO",""))); final EditText etXSO=(EditText)dialog.findViewById(R.id.etXSO); etXSO.setText(String.valueOf(pref.getFloat("xSO",0))); final EditText etYSO=(EditText)dialog.findViewById(R.id.etYSO); etYSO.setText(String.valueOf(pref.getFloat("ySO",0))); final EditText etZSO=(EditText)dialog.findViewById(R.id.etZSO); etZSO.setText(String.valueOf(pref.getFloat("zSO",0))); Button btclr=(Button)dialog.findViewById(R.id.btclr); final TextView trtele=(TextView)findViewById(R.id.txtTR); btclr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { etKodeSO.setText(""); etXSO.setText(""); etYSO.setText(""); etZSO.setText(""); } }); Button btsave=(Button)dialog.findViewById(R.id.btsave); btsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String kodeSO=etKodeSO.getText().toString(); final float xSO=Float.parseFloat(etXSO.getText().toString()); final float ySO=Float.parseFloat(etYSO.getText().toString()); final float zSO=Float.parseFloat(etZSO.getText().toString()); editor.putString("kodeSO", kodeSO); editor.putFloat("xSO", xSO); editor.putFloat("ySO", ySO); editor.putFloat("zSO", zSO); editor.commit(); // call //Occupy String ket = pref.getString("ket", ""); float hi=pref.getFloat("hi", (float) 0.000); float xA=pref.getFloat("xA", (float) 0.000); float yA=pref.getFloat("yA", (float) 0.000); float zA=pref.getFloat("zA", (float) 0.000); //BS Angle int dBS=pref.getInt("dBS",800); int mBS=pref.getInt("mBS", 0); int sBS=pref.getInt("sBS", 0); //BS Coordinate float xBS=pref.getFloat("xBS",0); float yBS=pref.getFloat("yBS", 0); float zBS=pref.getFloat("zBS", 0); //SO Data //String kodeSO=pref.getString("kodeSO",""); //float xSO=pref.getFloat("xSO",0); //float ySO=pref.getFloat("ySO",0); //float zSO=pref.getFloat("zSO",0); //SR Data int vAD=pref.getInt("vAD",0); int vAM=pref.getInt("vAM",0); int vAS=pref.getInt("vAS",0); int ba=pref.getInt("ba",0); int bt=pref.getInt("bt",0); int bb=pref.getInt("bb",0); double azbs=0; double az=0; double tel_dir=0; if(dBS==800){ // float az; double xb= xA - xBS; double yb= yA - yBS; double ab = xb / yb; double azimuthbs = Math.toDegrees(Math.atan(ab)); if (xb >0 && yb >0) { azbs = azimuthbs; } else if (xb >0 && yb <0) { azbs = 180 + azimuthbs; } else if (xb <0 && yb <0) { azbs = 180 + azimuthbs; } else if (xb <0 && yb >0) { azbs = 360 + azimuthbs; } else if (xb == 0 && yb >0) { azbs = 0; } else if (xb == 0 && yb <0) { azbs = 180; } else if (xb >0 && yb == 0) { azbs = 90; } else if (xb <0 && yb == 0) { azbs = 270; } double x = xA - xSO; double y = yA - ySO; double a = x / y; double azimuth = Math.toDegrees(Math.atan(a)); double hd = Math.pow(Math.pow((x), 2) + Math.pow((y), 2), 0.5); if (x >0 && y >0) { az = azimuth; } else if (x >0 && y <0) { az = 180 + azimuth; } else if (x <0 && y <0) { az = 180 + azimuth; } else if (x <0 && y >0) { az = 360 + azimuth; } else if (x == 0 && y >0) { az = 0; } else if (x == 0 && y <0) { az = 180; } else if (x >0 && y == 0) { az = 90; } else if (x <0 && y == 0) { az = 270; } if(azbs<az){ tel_dir = az - azbs; }else{ tel_dir=(360-azbs)+ az; } int der_tel=(int)tel_dir; int men_tel=(int)((tel_dir - der_tel)*60); float sec_tel=(float)((tel_dir - der_tel - (men_tel/60))*60); trtele.setText(String.valueOf(der_tel)+"º "+String.valueOf(men_tel)+"' "+String.valueOf((int)Math.round(sec_tel))+'"'); }else{ // float az; double azimuthbs = dBS+(mBS/60)+(sBS/3600); if(azimuthbs>180){ azbs = azimuthbs - 180; }else { azbs = azimuthbs + 180; } double x = xA - xSO; double y = yA - ySO; double a = x / y; double azimuth = Math.toDegrees(Math.atan(a)); double hd = Math.pow(Math.pow((x), 2) + Math.pow((y), 2), 0.5); if (x >0 && y >0) { az = azimuth; } else if (x >0 && y <0) { az = 180 + azimuth; } else if (x <0 && y <0) { az = 180 + azimuth; } else if (x <0 && y >0) { az = 360 + azimuth; } else if (x == 0 && y >0) { az = 0; } else if (x == 0 && y <0) { az = 180; } else if (x >0 && y == 0) { az = 90; } else if (x <0 && y == 0) { az = 270; } if(azbs<az){ tel_dir = az - azbs; }else{ tel_dir=(360-azbs)+ az; } int der_tel=(int)tel_dir; int men_tel=(int)((tel_dir - der_tel)*60); float sec_tel=(float)((tel_dir - der_tel - (men_tel/60))*60); TextView trtele=(TextView)findViewById(R.id.txtTR); TextView dist_staff=(TextView)findViewById(R.id.txtRambu); trtele.setText(String.valueOf(der_tel)+"º "+String.valueOf(men_tel)+"' "+String.valueOf((int)Math.round(sec_tel))+'"'); String turn_tele=String.valueOf(der_tel)+"º "+String.valueOf(men_tel)+"' "+String.valueOf((int)Math.round(sec_tel))+'"'; String hor_dist=String.format("%.3f",hd); dist_staff.setText(hor_dist+" M"); } final Dialog dialog2 = new Dialog(context); dialog2.setContentView(R.layout.kosong); dialog2.setTitle("Title..."); RelativeLayout cl =(RelativeLayout)dialog2.findViewById(R.id.cL1); cl.setVisibility(View.GONE); TextView tvInfo =(TextView)dialog2.findViewById(R.id.txtInfo); Button btok=(Button)dialog2.findViewById(R.id.btOK); String turn_tele=trtele.getText().toString(); tvInfo.setText("\b Kindly Rotate Theodolit's Telescope until HR in LCD display reach : "+turn_tele+"'' , then fasten horisontal lock!\n" + "\b Silahkan Putar Teleskop Theodolite anda sapai HR dalam LCD mencapai: "+turn_tele+"'' , kemudian kunci sekerup horisontal!"); btok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog2.dismiss(); } }); ImageView img = (ImageView)dialog2.findViewById(R.id.simple_anim); img.setImageDrawable(null); img.setBackgroundResource(R.drawable.anim); AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground(); frameAnimation.start(); LinearLayout ll = (LinearLayout)dialog2.findViewById(R.id.lL1); ll.setVisibility(View.VISIBLE); TextView lcd= (TextView)dialog2.findViewById(R.id.tvHR); lcd.setText("HR "+turn_tele); dialog2.show(); dialog.dismiss(); } }); Button btcancel=(Button)dialog.findViewById(R.id.btcancel); btcancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.show(); } }); btsr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.sr); dialog.setTitle("Title..."); Button btcancel=(Button)dialog.findViewById(R.id.btcancel); Button btsave=(Button)dialog.findViewById(R.id.btsave); Button btclr=(Button)dialog.findViewById(R.id.btclr); final EditText etVAD=(EditText)dialog.findViewById(R.id.etVAD); etVAD.setText(String.valueOf(pref.getInt("vAD",0))); final EditText etVAM=(EditText)dialog.findViewById(R.id.etVAM); etVAM.setText(String.valueOf(pref.getInt("vAM",0))); final EditText etVAS=(EditText)dialog.findViewById(R.id.etVAS); etVAS.setText(String.valueOf(pref.getInt("vAS",0))); final EditText etUCH=(EditText)dialog.findViewById(R.id.etuch); etUCH.setText(String.valueOf(pref.getInt("ba",0))); final EditText etMCH=(EditText)dialog.findViewById(R.id.etmch); etMCH.setText(String.valueOf(pref.getInt("bt",0))); final EditText etLCH=(EditText)dialog.findViewById(R.id.etlch); etLCH.setText(String.valueOf(pref.getInt("bb",0))); btclr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { etVAD.setText(""); etVAM.setText(""); etVAS.setText(""); etUCH.setText(""); etMCH.setText(""); etLCH.setText(""); } }); btsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int vAD=Integer.parseInt(etVAD.getText().toString()); int vAM=Integer.parseInt(etVAM.getText().toString()); int vAS=Integer.parseInt(etVAS.getText().toString()); int ba=Integer.parseInt(etUCH.getText().toString()); int bt=Integer.parseInt(etMCH.getText().toString()); int bb=Integer.parseInt(etLCH.getText().toString()); editor.putInt("vAD", vAD); editor.putInt("vAM", vAM); editor.putInt("vAS", vAS); editor.putInt("ba", ba); editor.putInt("bt", bt); editor.putInt("bb", bb); editor.commit(); dialog.dismiss(); } }); btcancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.show(); } }); btmsr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Occupy tvclk.setVisibility(View.VISIBLE); String ket = pref.getString("ket", ""); float hi=pref.getFloat("hi", (float) 0.000); float xA=pref.getFloat("xA", (float) 0.000); float yA=pref.getFloat("yA", (float) 0.000); float zA=pref.getFloat("zA", (float) 0.000); //BS Angle int dBS=pref.getInt("dBS",800); int mBS=pref.getInt("mBS", 0); int sBS=pref.getInt("sBS", 0); //BS Coordinate float xBS=pref.getFloat("xBS",0); float yBS=pref.getFloat("yBS", 0); float zBS=pref.getFloat("zBS", 0); //SO Data String kodeSO=pref.getString("kodeSO",""); float xSO=pref.getFloat("xSO",0); float ySO=pref.getFloat("ySO",0); float zSO=pref.getFloat("zSO",0); //SR Data int vAD=pref.getInt("vAD",0); int vAM=pref.getInt("vAM",0); int vAS=pref.getInt("vAS",0); int ba=pref.getInt("ba",0); int bt=pref.getInt("bt",0); int bb=pref.getInt("bb",0); if(dBS==800){ // float az; double azbs=0; double az=0; double tel_dir=0; double xb= xA - xBS; double yb= yA - yBS; double ab = xb / yb; double azimuthbs = Math.toDegrees(Math.atan(ab)); if (xb >0 && yb >0) { azbs = azimuthbs; } else if (xb >0 && yb <0) { azbs = 180 + azimuthbs; } else if (xb <0 && yb <0) { azbs = 180 + azimuthbs; } else if (xb <0 && yb >0) { azbs = 360 + azimuthbs; } else if (xb == 0 && yb >0) { azbs = 0; } else if (xb == 0 && yb <0) { azbs = 180; } else if (xb >0 && yb == 0) { azbs = 90; } else if (xb <0 && yb == 0) { azbs = 270; } double x = xA - xSO; double y = yA - ySO; double a = x / y; double azimuth = Math.toDegrees(Math.atan(a)); double hd = Math.pow(Math.pow((x), 2) + Math.pow((y), 2), 0.5); if (x >0 && y >0) { az = azimuth; } else if (x >0 && y <0) { az = 180 + azimuth; } else if (x <0 && y <0) { az = 180 + azimuth; } else if (x <0 && y >0) { az = 360 + azimuth; } else if (x == 0 && y >0) { az = 0; } else if (x == 0 && y <0) { az = 180; } else if (x >0 && y == 0) { az = 90; } else if (x <0 && y == 0) { az = 270; } if(azbs<az){ tel_dir = az - azbs; }else{ tel_dir=(360-azbs)+ az; } int der_tel=(int)tel_dir; int men_tel=(int)((tel_dir - der_tel)*60); float sec_tel=(float)((tel_dir - der_tel - (men_tel/60))*60); TextView trtele=(TextView)findViewById(R.id.txtTR); TextView trambu=(TextView)findViewById(R.id.txtRbLb); TextView trmove=(TextView)findViewById(R.id.txtRambu); TextView lbUp=(TextView)findViewById(R.id.txtUpLb); TextView txtUp=(TextView)findViewById(R.id.txtUP); TextView txtHD=(TextView)findViewById(R.id.txtHD); trtele.setText(String.valueOf(der_tel)+"º "+String.valueOf(men_tel)+"' "+String.valueOf((int)Math.round(sec_tel))+'"'); double zenit = vAD + (vAM/60) + (vAS/3600); double heling = 90 - zenit; double hdoptis = ((ba-bb)*0.1)* Math.cos(Math.toRadians(heling))*Math.cos(Math.toRadians(heling)); double dist = hd - hdoptis; double dh=(hdoptis*(Math.tan(Math.toRadians(heling))))+hi-(bt/1000); double z = zSO - zA; double cf=dh-z; if(z>dh){ String txtcf="Fill!:"; lbUp.setText(txtcf); }else{ String txtcf="Cut!:"; lbUp.setText(txtcf); } if (hd>hdoptis){ String move="Move Backward!"; trambu.setText(move); }else if(hd==hdoptis){ String move="Stop there!"; trambu.setText(move); }else{ String move="Move Forward!!"; trambu.setText(move); } final String hds=String.format("%.3f",hd); txtHD.setText(hds+" M"); final String jd=String.format("%.3f",dist); trmove.setText(jd+" M"); String cutfill=String.format("%.3f",cf); txtUp.setText(cutfill+" M"); Drawable dr = getResources().getDrawable(R.drawable.ic_fs); Drawable dr2 = getResources().getDrawable(R.drawable.ic_bs); //RotateDrawable rdr = (RotateDrawable) getResources().getDrawable(R.drawable.ic_fs); //rdr.setToDegrees(20); // iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_fsbs1)); ivi.setRotation((float)azbs+180); ivi.setBackground(dr2); iv.setRotation((float)(az+180)); iv.setBackground(dr); iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.kosong); dialog.setTitle("Title..."); Button ok=(Button)dialog.findViewById(R.id.btOK); RelativeLayout cl =(RelativeLayout)dialog.findViewById(R.id.cL1); cl.setVisibility(View.VISIBLE); TextView tvRhd = (TextView)dialog.findViewById(R.id.tvRHD); TextView tvhd = (TextView)dialog.findViewById(R.id.tvHD); tvRhd.setText(jd+" M"); tvhd.setText(hds+" M"); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.show(); } }); }else{ // float az; double azbs=0; double az=0; double tel_dir=0; double azimuthbs = dBS+(mBS/60)+(sBS/3600); if(azimuthbs>180){ azbs = azimuthbs - 180; }else { azbs = azimuthbs + 180; } double x = xA - xSO; double y = yA - ySO; double a = x / y; double azimuth = Math.toDegrees(Math.atan(a)); double hd = Math.pow(Math.pow((x), 2) + Math.pow((y), 2), 0.5); if (x >0 && y >0) { az = azimuth; } else if (x >0 && y <0) { az = 180 + azimuth; } else if (x <0 && y <0) { az = 180 + azimuth; } else if (x <0 && y >0) { az = 360 + azimuth; } else if (x == 0 && y >0) { az = 0; } else if (x == 0 && y <0) { az = 180; } else if (x >0 && y == 0) { az = 90; } else if (x <0 && y == 0) { az = 270; } if(azbs<az){ tel_dir = az - azbs; }else{ tel_dir=(360-azbs)+ az; } int der_tel=(int)tel_dir; int men_tel=(int)((tel_dir - der_tel)*60); float sec_tel=(float)((tel_dir - der_tel - (men_tel/60))*60); TextView trtele=(TextView)findViewById(R.id.txtTR); TextView trambu=(TextView)findViewById(R.id.txtRbLb); TextView trmove=(TextView)findViewById(R.id.txtRambu); TextView lbUp=(TextView)findViewById(R.id.txtUpLb); TextView txtUp=(TextView)findViewById(R.id.txtUP); TextView txtHD=(TextView)findViewById(R.id.txtHD); trtele.setText(String.valueOf(der_tel)+"º "+String.valueOf(men_tel)+"' "+String.valueOf((int)Math.round(sec_tel))+'"'); double zenit = vAD + (vAM/60) + (vAS/3600); double heling = 90 - zenit; double hdoptis = ((ba-bb)*0.1)* Math.cos(Math.toRadians(heling))*Math.cos(Math.toRadians(heling)); double dist = hd - hdoptis; double dh=(hdoptis*(Math.tan(Math.toRadians(heling))))+hi-(bt/1000); double z = zSO - zA; double cf=dh-z; if(z>dh){ String txtcf="Fill!:"; lbUp.setText(txtcf); }else{ String txtcf="Cut!:"; lbUp.setText(txtcf); } if (hd>hdoptis){ String move="Move Backward!"; trambu.setText(move); }else if(hd==hdoptis){ String move="Stop there!"; trambu.setText(move); }else{ String move="Move Forward!!"; trambu.setText(move); } final String hds=String.format("%.3f",hd); txtHD.setText(hds+" M"); final String jd=String.format("%.3f",dist); trmove.setText(jd+" M"); String cutfill=String.format("%.3f",cf); txtUp.setText(cutfill+" M"); Drawable dr = getResources().getDrawable(R.drawable.ic_fs); Drawable dr2 = getResources().getDrawable(R.drawable.ic_bs); //RotateDrawable rdr = (RotateDrawable) getResources().getDrawable(R.drawable.ic_fs); //rdr.setToDegrees(20); // iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_fsbs1)); ivi.setRotation((float)azbs+180); ivi.setBackground(dr2); iv.setRotation((float)(az+180)); iv.setBackground(dr); iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.kosong); dialog.setTitle("Title..."); Button ok=(Button)dialog.findViewById(R.id.btOK); RelativeLayout cl =(RelativeLayout)dialog.findViewById(R.id.cL1); cl.setVisibility(View.VISIBLE); TextView tvRhd = (TextView)dialog.findViewById(R.id.tvRHD); TextView tvhd = (TextView)dialog.findViewById(R.id.tvHD); tvRhd.setText(jd+" M"); tvhd.setText(hds+" M"); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.show(); } }); } } }); btsd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String id_pro=getIntent().getStringExtra("id"); String ket = pref.getString("ket", ""); float hi=pref.getFloat("hi", (float) 0.000); float xA=pref.getFloat("xA", (float) 0.000); float yA=pref.getFloat("yA", (float) 0.000); float zA=pref.getFloat("zA", (float) 0.000); //BS Angle int dBS=pref.getInt("dBS",800); int mBS=pref.getInt("mBS", 0); int sBS=pref.getInt("sBS", 0); //BS Coordinate float xBS=pref.getFloat("xBS",0); float yBS=pref.getFloat("yBS", 0); float zBS=pref.getFloat("zBS", 0); //SO Data String kodeSO=pref.getString("kodeSO",""); float xSO=pref.getFloat("xSO",0); float ySO=pref.getFloat("ySO",0); float zSO=pref.getFloat("zSO",0); //SR Data int vAD=pref.getInt("vAD",0); int vAM=pref.getInt("vAM",0); int vAS=pref.getInt("vAS",0); int ba=pref.getInt("ba",0); int bt=pref.getInt("bt",0); int bb=pref.getInt("bb",0); if(dBS==800){ // float az; double azbs=0; double az=0; double tel_dir=0; double xb= xA - xBS; double yb= yA - yBS; double ab = xb / yb; double azimuthbs = Math.toDegrees(Math.atan(ab)); if (xb >0 && yb >0) { azbs = azimuthbs; } else if (xb >0 && yb <0) { azbs = 180 + azimuthbs; } else if (xb <0 && yb <0) { azbs = 180 + azimuthbs; } else if (xb <0 && yb >0) { azbs = 360 + azimuthbs; } else if (xb == 0 && yb >0) { azbs = 0; } else if (xb == 0 && yb <0) { azbs = 180; } else if (xb >0 && yb == 0) { azbs = 90; } else if (xb <0 && yb == 0) { azbs = 270; } double x = xA - xSO; double y = yA - ySO; double a = x / y; double azimuth = Math.toDegrees(Math.atan(a)); double hd = Math.pow(Math.pow((x), 2) + Math.pow((y), 2), 0.5); if (x >0 && y >0) { az = azimuth; } else if (x >0 && y <0) { az = 180 + azimuth; } else if (x <0 && y <0) { az = 180 + azimuth; } else if (x <0 && y >0) { az = 360 + azimuth; } else if (x == 0 && y >0) { az = 0; } else if (x == 0 && y <0) { az = 180; } else if (x >0 && y == 0) { az = 90; } else if (x <0 && y == 0) { az = 270; } if(azbs<az){ tel_dir = az - azbs; }else{ tel_dir=(360-azbs)+ az; } int der_tel=(int)tel_dir; int men_tel=(int)((tel_dir - der_tel)*60); float sec_tel=(float)((tel_dir - der_tel - (men_tel/60))*60); TextView trtele=(TextView)findViewById(R.id.txtTR); TextView trambu=(TextView)findViewById(R.id.txtRbLb); TextView trmove=(TextView)findViewById(R.id.txtRambu); TextView lbUp=(TextView)findViewById(R.id.txtUpLb); TextView txtUp=(TextView)findViewById(R.id.txtUP); TextView txtHD=(TextView)findViewById(R.id.txtHD); trtele.setText(String.valueOf(der_tel)+"º "+String.valueOf(men_tel)+"' "+String.valueOf((int)Math.round(sec_tel))+'"'); double zenit = vAD + (vAM/60) + (vAS/3600); double heling = 90 - zenit; double hdoptis = ((ba-bb)*0.1)* Math.cos(Math.toRadians(heling))*Math.cos(Math.toRadians(heling)); double dist = hd - hdoptis; double dh=(hdoptis*(Math.tan(Math.toRadians(heling))))+hi-(bt/1000); double z = zSO - zA; double cf=dh-z; if(z>dh){ String txtcf="Fill!:"; lbUp.setText(txtcf); }else{ String txtcf="Cut!:"; lbUp.setText(txtcf); } if (hd>hdoptis){ String move="Move Backward!"; trambu.setText(move); }else if(hd==hdoptis){ String move="Stop there!"; trambu.setText(move); }else{ String move="Move Forward!!"; trambu.setText(move); } String hds=String.format("%.3f",hd); txtHD.setText(hds+" M"); String jd=String.format("%.3f",dist); trmove.setText(jd+" M"); String cutfill=String.format("%.3f",cf); txtUp.setText(cutfill+" M"); final double azbsk; if((azbs-180)<0){ azbsk = azbs - 180 + 360; }else{ azbsk = azbs -180; } SQLiteDatabase db = dbcenter.getWritableDatabase(); // db.execSQL("insert into data( id_pro, code, azbs, xa, ya, za, xso, yso, zso, hi, vd, vm, vs, ba, bt, bb, az, hd, fb, cf ) values('"+id_pro+"', '"+ // ket+"','"+azbs+"','"+xA+"','"+yA+"','"+zA+"','"+xSO+"','"+ySO+"','"+zSO+"','"+hi+"','"+vAD+"','"+vAM+"','"+vAS+"','"+ // ba+"','"+bt+"','"+bb+"', '"+az+"','"+hd+"','"+hd+"','"+cf+"' )"); db.execSQL("insert into data(id_pro, code, azbs, xa, ya, za, xso, yso, zso, hi, vd, vm, vs, ba, bt, bb, az, hd, fb, cf)values" + "('"+id_pro+"','"+ket+"','"+azbsk+"','"+xA+"', '"+yA+"', '"+zA+"', '"+xSO+"', '"+ySO+"', '"+zSO+"', '"+hi+"', '"+vAD+"', '"+vAM+"', '"+vAS+"', '"+ba+"', '"+bt+"', '"+bb+"', '"+tel_dir+"', '"+hd+"', '"+jd+"', '"+cutfill+"')"); Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show(); Project_Activity.ma.RefreshList(); finish(); }else{ // float az; double azbs=0; double az=0; double tel_dir=0; double azimuthbs = dBS+(mBS/60)+(sBS/3600); if(azimuthbs>180){ azbs = azimuthbs - 180; }else { azbs = azimuthbs + 180; } double x = xA - xSO; double y = yA - ySO; double a = x / y; double azimuth = Math.toDegrees(Math.atan(a)); double hd = Math.pow(Math.pow((x), 2) + Math.pow((y), 2), 0.5); if (x >0 && y >0) { az = azimuth; } else if (x >0 && y <0) { az = 180 + azimuth; } else if (x <0 && y <0) { az = 180 + azimuth; } else if (x <0 && y >0) { az = 360 + azimuth; } else if (x == 0 && y >0) { az = 0; } else if (x == 0 && y <0) { az = 180; } else if (x >0 && y == 0) { az = 90; } else if (x <0 && y == 0) { az = 270; } if(azbs<az){ tel_dir = az - azbs; }else{ tel_dir=(360-azbs)+ az; } int der_tel=(int)tel_dir; int men_tel=(int)((tel_dir - der_tel)*60); float sec_tel=(float)((tel_dir - der_tel - (men_tel/60))*60); TextView trtele=(TextView)findViewById(R.id.txtTR); TextView trambu=(TextView)findViewById(R.id.txtRbLb); TextView trmove=(TextView)findViewById(R.id.txtRambu); TextView lbUp=(TextView)findViewById(R.id.txtUpLb); TextView txtUp=(TextView)findViewById(R.id.txtUP); TextView txtHD=(TextView)findViewById(R.id.txtHD); trtele.setText(String.valueOf(der_tel)+"º "+String.valueOf(men_tel)+"' "+String.valueOf((int)Math.round(sec_tel))+'"'); double zenit = vAD + (vAM/60) + (vAS/3600); double heling = 90 - zenit; double hdoptis = ((ba-bb)*0.1)* Math.cos(Math.toRadians(heling))*Math.cos(Math.toRadians(heling)); double dist = hd - hdoptis; double dh=(hdoptis*(Math.tan(Math.toRadians(heling))))+hi-(bt/1000); double z = zSO - zA; double cf=dh-z; if(z>dh){ String txtcf="Fill!:"; lbUp.setText(txtcf); }else{ String txtcf="Cut!:"; lbUp.setText(txtcf); } if (hd>hdoptis){ String move="Move Backward!"; trambu.setText(move); }else if(hd==hdoptis){ String move="Stop there!"; trambu.setText(move); }else{ String move="Move Forward!!"; trambu.setText(move); } String hds=String.format("%.3f",hd); txtHD.setText(hds+" M"); String jd=String.format("%.3f",dist); trmove.setText(jd+" M"); String cutfill=String.format("%.3f",cf); txtUp.setText(cutfill+" M"); SQLiteDatabase db = dbcenter.getWritableDatabase(); // db.execSQL("insert into data( id_pro, code, azbs, xa, ya, za, xso, yso, zso, hi, vd, vm, vs, ba, bt, bb, az, hd, fb, cf ) values('"+id_pro+"', '"+ // ket+"','"+azbs+"','"+xA+"','"+yA+"','"+zA+"','"+xSO+"','"+ySO+"','"+zSO+"','"+hi+"','"+vAD+"','"+vAM+"','"+vAS+"','"+ // ba+"','"+bt+"','"+bb+"', '"+az+"','"+hd+"','"+hd+"','"+cf+"' )"); db.execSQL("insert into data(id_pro, code, azbs, xa, ya, za, xso, yso, zso, hi, vd, vm, vs, ba, bt, bb, az, hd, fb, cf)values" + "('"+id_pro+"','"+ket+"','"+azimuthbs+"','"+xA+"', '"+yA+"', '"+zA+"', '"+xSO+"', '"+ySO+"', '"+zSO+"', '"+hi+"', '"+vAD+"', '"+vAM+"', '"+vAS+"', '"+ba+"', '"+bt+"', '"+bb+"', '"+tel_dir+"', '"+hd+"', '"+jd+"', '"+cutfill+"')"); Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show(); Project_Activity.ma.RefreshList(); finish(); } } }); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); } }
49.045948
278
0.41221
6b388ab12ac66008e1b5fc4af6e967018bc4ae30
202
public void test07() throws Throwable { String[] stringArray0 = new String[9]; stringArray0[1] = "0"; LagoonCLI.main(stringArray0); assertEquals(9, stringArray0.length); }
28.857143
44
0.638614
227785473264dd7cbf270611b16865512c6ddc48
5,352
package org.tron.core.net.messagehandler; import com.googlecode.cqengine.query.simple.In; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; import org.tron.core.exception.P2pException.TypeEnum; import org.tron.core.net.TronNetDelegate; import org.tron.core.net.message.TransactionMessage; import org.tron.core.net.message.TransactionsMessage; import org.tron.core.net.message.TronMessage; import org.tron.core.net.peer.Item; import org.tron.core.net.service.AdvService; import org.tron.core.net.peer.PeerConnection; import org.tron.protos.Protocol.Inventory.InventoryType; import org.tron.protos.Protocol.ReasonCode; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Contract.ContractType; @Slf4j(topic = "net") @Component public class TransactionsMsgHandler implements TronMsgHandler { @Autowired private TronNetDelegate tronNetDelegate; @Autowired private AdvService advService; private static int MAX_TRX_SIZE = 50_000; private static int MAX_SMART_CONTRACT_SUBMIT_SIZE = 100; // private static int TIME_OUT = 10 * 60 * 1000; private BlockingQueue<TrxEvent> smartContractQueue = new LinkedBlockingQueue(MAX_TRX_SIZE); private BlockingQueue<Runnable> queue = new LinkedBlockingQueue(); private int threadNum = Args.getInstance().getValidateSignThreadNum(); private ExecutorService trxHandlePool = new ThreadPoolExecutor(threadNum, threadNum, 0L, TimeUnit.MILLISECONDS, queue); private ScheduledExecutorService smartContractExecutor = Executors .newSingleThreadScheduledExecutor(); class TrxEvent { @Getter private PeerConnection peer; @Getter private TransactionMessage msg; @Getter private long time; public TrxEvent(PeerConnection peer, TransactionMessage msg) { this.peer = peer; this.msg = msg; this.time = System.currentTimeMillis(); } } public void init() { handleSmartContract(); } public void close() { smartContractExecutor.shutdown(); } public boolean isBusy() { return queue.size() + smartContractQueue.size() > MAX_TRX_SIZE; } @Override public void processMessage(PeerConnection peer, TronMessage msg) throws P2pException { TransactionsMessage transactionsMessage = (TransactionsMessage) msg; check(peer, transactionsMessage); for (Transaction trx : transactionsMessage.getTransactions().getTransactionsList()) { int type = trx.getRawData().getContract(0).getType().getNumber(); if (type == ContractType.TriggerSmartContract_VALUE || type == ContractType.CreateSmartContract_VALUE) { if (!smartContractQueue.offer(new TrxEvent(peer, new TransactionMessage(trx)))) { logger.warn("Add smart contract failed, queueSize {}:{}", smartContractQueue.size(), queue.size()); } } else { trxHandlePool.submit(() -> handleTransaction(peer, new TransactionMessage(trx))); } } } private void check(PeerConnection peer, TransactionsMessage msg) throws P2pException { for (Transaction trx : msg.getTransactions().getTransactionsList()) { Item item = new Item(new TransactionMessage(trx).getMessageId(), InventoryType.TRX); if (!peer.getAdvInvRequest().containsKey(item)) { throw new P2pException(TypeEnum.BAD_MESSAGE, "trx: " + msg.getMessageId() + " without request."); } peer.getAdvInvRequest().remove(item); } } private void handleSmartContract() { smartContractExecutor.scheduleWithFixedDelay(() -> { try { while (queue.size() < MAX_SMART_CONTRACT_SUBMIT_SIZE) { TrxEvent event = smartContractQueue.take(); trxHandlePool.submit(() -> handleTransaction(event.getPeer(), event.getMsg())); } } catch (Exception e) { logger.error("Handle smart contract exception.", e); } }, 1000, 20, TimeUnit.MILLISECONDS); } private void handleTransaction(PeerConnection peer, TransactionMessage trx) { if (peer.isDisconnect()) { logger.warn("Drop trx {} from {}, peer is disconnect.", trx.getMessageId(), peer.getInetAddress()); return; } if (advService.getMessage(new Item(trx.getMessageId(), InventoryType.TRX)) != null) { return; } try { tronNetDelegate.pushTransaction(trx.getTransactionCapsule()); advService.broadcast(trx); } catch (P2pException e) { logger.warn("Trx {} from peer {} process failed. type: {}, reason: {}", trx.getMessageId(), peer.getInetAddress(), e.getType(), e.getMessage()); if (e.getType().equals(TypeEnum.BAD_TRX)) { peer.disconnect(ReasonCode.BAD_TX); } } catch (Exception e) { logger.error("Trx {} from peer {} process failed.", trx.getMessageId(), peer.getInetAddress(), e); } } }
35.210526
100
0.718236
0a8f3a9d1f423763d266ba64ea095a686e7b93b8
9,976
package com.deftwun.zombiecopter.box2dJson; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Logger; import com.badlogic.gdx.utils.ObjectMap; /* Manages multiple bodies, joints (..planned), and fixtures. Also able to be serialized and rebuilt from json data (..using PhysicsModel,BodyModel,FixtureModel,etc..) */ public class PhysicsScene{ private Logger logger = new Logger("PhysicsScene",Logger.INFO); private static long uniqueId = 0; private Body primaryBody = null; private World world = null; private ObjectMap<String, Joint> joints = new ObjectMap<String,Joint>(); private ObjectMap<String, Body> bodies = new ObjectMap<String,Body>(); private ObjectMap<String, Fixture> fixtures = new ObjectMap<String,Fixture>(); private PhysicsSceneListener listener = null; public interface PhysicsSceneListener{ void fixtureAdded(Fixture f); void bodyAdded(Body b); void jointAdded(Joint j); void fixtureRemoved(Fixture f); void bodyRemoved(Body b); void jointRemoved(Joint j); } public PhysicsScene(World w){ logger.debug("Creating scene using world"); world = w; } public PhysicsScene(){ logger.debug("Creating scene using new default world"); world = new World(new Vector2(),true); } public void setPhysicsSceneListener(PhysicsSceneListener l){ listener = l; } //Create everything from a PhysicsSceneModel public void createFromModel(PhysicsSceneModel model){ logger.debug("create from model"); this.destroy(); for (BodyModel bm : model.bodyModels){ createBody(bm); } for (JointModel jm : model.jointModels){ createJoint(jm); } primaryBody = bodies.get(model.primaryBody,null); if (primaryBody == null && bodies.size > 0) primaryBody = bodies.values().toArray().get(0); } public void setPrimaryBody(String name){ logger.debug("Set primary body: " + name); primaryBody = bodies.get(name,null); } public Body getPrimaryBody(){ return primaryBody; } //Create Body public Body createBody(BodyModel bm){ logger.debug("create Body from model: " + bm.name); String name = uniqueBodyName(bm.name); Body body = bm.toBody(world); if (primaryBody == null){ primaryBody = body; } bodies.put(name,body); if (listener != null) listener.bodyAdded(body); for (FixtureModel fm : bm.fixtures){ Fixture f = fm.toFixture(body); fm.name = uniqueFixtureName(fm.name); fixtures.put(fm.name,f); if (listener != null) listener.fixtureAdded(f); } return body; } //Add Body public String addBody(Body b){ String name = uniqueBodyName("body"); this.addBody(name, b); return name; } //Add body public String addBody(String name,Body b){ logger.debug("Add body: " + name); if (primaryBody == null){ primaryBody = b; } bodies.put(name,b); if (listener != null) listener.bodyAdded(b); for (Fixture f : b.getFixtureList()){ String fixName = uniqueFixtureName("fixture"); logger.debug("add fixture: " + fixName); fixtures.put(fixName,f); if (listener != null) listener.fixtureAdded(f); } return name; } //Create Joint public Joint createJoint(JointModel jm){ String name = uniqueJointName(jm.name); logger.debug("Creating Joint from model: " + name + " = " + jm.bodyA + "+" + jm.bodyB); Body bodyA = bodies.get(jm.bodyA), bodyB = bodies.get(jm.bodyB); if (bodyA == null) logger.error("Can't create Joint. Body: " + jm.bodyA + " not found in scene."); if (bodyB == null) logger.error("Can't create Joint. Body: " + jm.bodyB + " nof found in scene."); Joint joint = jm.toJoint(world,bodyA,bodyB); joints.put(name,joint); logger.debug("Joint count = " + joints.size); if (listener != null) listener.jointAdded(joint); return joint; } //Add joint public String addJoint(Joint j){ String name = uniqueJointName("joint"); return this.addJoint(name,j); } //Add joint public String addJoint(String name, Joint j){ logger.debug("Joint added: " + name); joints.put(name,j); if (listener != null) listener.jointAdded(j); return name; } //Check if body exists in the scene public boolean hasBody(String name){ return bodies.containsKey(name); } public boolean hasBody(Body b){ return bodies.containsValue(b,true); } //Check if fixture exists in the scene public boolean hasFixture(String name){ return fixtures.containsKey(name); } public boolean hasFixture(Fixture f){ return fixtures.containsValue(f,true); } //Check if joint exists in the scene public boolean hasJoint(String name){ return joints.containsKey(name); } public boolean hasJoint(Joint j){ return joints.containsValue(j,true); } //Get name of body public String getName(Body b){ for (ObjectMap.Entry<String,Body> entry : bodies){ if (entry.value == b) return entry.key; } return ""; } //Get name of fixture public String getName(Fixture f){ for (ObjectMap.Entry<String,Fixture> entry : fixtures){ if (entry.value == f) return entry.key; } return ""; } //Get name of joint public String getName(Joint j){ for (ObjectMap.Entry<String,Joint> entry : joints){ if (entry.value == j) return entry.key; } return ""; } //Get body public Body getBody(String name){ return bodies.get(name); } //Get fixture public Fixture getFixture(String name){ return fixtures.get(name); } //Get joint public Joint getJoint(String name){ return joints.get(name); } //Get all fixtures public Array<Fixture> getFixtures(){ return fixtures.values().toArray(); } //Get all bodies public Array<Body> getBodies(){ return bodies.values().toArray(); } //Get all joints public Array<Joint> getJoints(){ return joints.values().toArray(); } //Destroy everything public void destroy(){ logger.debug(String.format("Destroying: %d fixtures, %d bodies, & %d joints...", fixtures.size,bodies.size,joints.size)); for (Joint j : joints.values()){ world.destroyJoint(j); if (listener != null) listener.jointRemoved(j); logger.debug("Joint Destroyed"); } for (Body b : bodies.values()){ for (Fixture f : b.getFixtureList()){ b.destroyFixture(f); if (listener != null) listener.fixtureRemoved(f); logger.debug("Fixture Destroyed"); } world.destroyBody(b); if (listener != null) listener.bodyRemoved(b); logger.debug("Body Destroyed"); } fixtures.clear(); bodies.clear(); joints.clear(); uniqueId = 0; primaryBody = null; logger.debug("---Destroyed"); } //Destroy body public void destroyBody(String name){ logger.debug("Destroy body: " + name); Body b = bodies.get(name,null); if (b != null){ //Check if its the primary body. If so, then automatically set a new primary if (b == primaryBody){ if (bodies.size > 0) primaryBody = bodies.values().toArray().get(0); else primaryBody = null; } world.destroyBody(b); bodies.remove(name); if (listener != null) listener.bodyRemoved(b); } else logger.debug("Could not destroy body: " + name + " not found"); } //Destroy Fixture public void destroyFixture(String name){ logger.debug("Destroy fixture: " + name); Fixture f = fixtures.get(name); if (f != null){ f.getBody().destroyFixture(f); fixtures.remove(name); if (listener != null) listener.fixtureRemoved(f); } else logger.debug("Could not destroy fixture: " + name + " not found"); } //Destroy joint public void destroyJoint(String name){ logger.debug("Destroy Joint: " + name); Joint j = joints.get(name); if (j != null){ world.destroyJoint(j); joints.remove(name); if (listener != null) listener.jointRemoved(j); } else logger.debug("Could not destroy joint: " + name + " not found"); } //Create Scene model public PhysicsSceneModel toSceneModel(){ logger.debug("Creating Scene Model"); PhysicsSceneModel physicsModel = new PhysicsSceneModel(); //Bodies for (ObjectMap.Entry<String,Body> bodyEntry : bodies.entries()){ BodyModel bodyModel = new BodyModel(bodyEntry.key,bodyEntry.value); //clear un-named fixtures. We'll manually add them with names included bodyModel.fixtures.clear(); //Fixtures for (ObjectMap.Entry<String,Fixture> fixtureEntry : fixtures.entries()){ if (fixtureEntry.value.getBody() == bodyEntry.value){ FixtureModel fixModel = new FixtureModel(fixtureEntry.key,fixtureEntry.value); bodyModel.fixtures.add(fixModel); } } physicsModel.bodyModels.add(bodyModel); } //Joints for (ObjectMap.Entry<String,Joint> jointEntry : joints.entries()){ Joint j = jointEntry.value; JointModel jointModel = new JointModel(jointEntry.key,jointEntry.value,getName(j.getBodyA()), getName(j.getBodyB())); physicsModel.jointModels.add(jointModel); } return physicsModel; } //generates a unique body name using the given prefix private String uniqueBodyName(String prefix){ String s = prefix; while (bodies.containsKey(prefix)) s = prefix + uniqueId++; return s; } //generates a unique fixture name using the given prefix private String uniqueFixtureName(String prefix){ String s = prefix; while (fixtures.containsKey(s)) s = prefix + uniqueId++; return s; } //generates a unique joint name using the given prefix private String uniqueJointName(String prefix){ String s = prefix; while (fixtures.containsKey(s)) s = prefix + uniqueId++; return s; } }
28.101408
121
0.6665
78bbc5fdcbf99d5ac7a9b74ad173bdadbb2dc85d
2,748
/* * Copyright 2000-2010 JetBrains s.r.o. * * 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.intellij.openapi.vcs.actions; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.colors.ColorKey; import com.intellij.openapi.util.Couple; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.annotate.AnnotationSource; import com.intellij.openapi.vcs.annotate.FileAnnotation; import com.intellij.openapi.vcs.annotate.LineAnnotationAspect; import com.intellij.openapi.vcs.annotate.TextAnnotationPresentation; import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.util.Consumer; import java.awt.*; import java.util.Map; /** * shown additionally only when merge * * @author Konstantin Bulenkov */ class CurrentRevisionAnnotationFieldGutter extends AnnotationFieldGutter implements Consumer<AnnotationSource> { // merge source showing is turned on private boolean myTurnedOn; CurrentRevisionAnnotationFieldGutter(FileAnnotation annotation, LineAnnotationAspect aspect, TextAnnotationPresentation highlighting, Couple<Map<VcsRevisionNumber, Color>> colorScheme) { super(annotation, aspect, highlighting, colorScheme); } @Override public ColorKey getColor(int line, Editor editor) { return AnnotationSource.LOCAL.getColor(); } @Override public String getLineText(int line, Editor editor) { final String value = myAspect.getValue(line); if (String.valueOf(myAnnotation.getLineRevisionNumber(line)).equals(value)) { return ""; } // shown in merge sources mode return myTurnedOn ? value : ""; } @Override public String getToolTip(int line, Editor editor) { final String aspectTooltip = myAspect.getTooltipText(line); if (aspectTooltip != null) { return aspectTooltip; } final String text = getLineText(line, editor); return ((text == null) || (text.length() == 0)) ? "" : VcsBundle.message("annotation.original.revision.text", text); } public void consume(final AnnotationSource annotationSource) { myTurnedOn = annotationSource.showMerged(); } }
35.688312
120
0.726346
b83d47e18310c0c235520edf14b4ce41be0705ab
946
package net.obvj.confectory.testdrive; import net.obvj.confectory.Configuration; import net.obvj.confectory.mapper.GsonJsonToObjectMapper; import net.obvj.confectory.testdrive.model.MyBean; public class ConfectoryTestDriveGsonJsonToObject { public static void main(String[] args) { Configuration<MyBean> config = Configuration.<MyBean>builder() .namespace("test") .source("testfiles/agents.json") .mapper(new GsonJsonToObjectMapper<>(MyBean.class)) .build(); MyBean myBean = config.getBean(); System.out.println(myBean); System.out.println(myBean.isEnabled()); System.out.println(myBean.getAgents().get(0).getClazz()); System.out.println(myBean.getAgents().get(0).getInterval()); System.out.println(myBean.getAgents().get(1).getClazz()); System.out.println(myBean.getAgents().get(1).getInterval()); } }
36.384615
70
0.667019
9d743bcc6f5bfaf62b200f6d2f97e2deadca76b4
17,029
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /** * Database class to handle connections and queries * @author Michael Snyder */ public class Database { private Connection dbConnection; private Exception lastError; private List<User> userList; private User currentUser; private Statement queryStatement; private ResultSet queryResult; /** * Constructor to intialize the connection to the database * @param dbAddress Address of the SQL Server * @param dbPort Port of the SQL Server * @param dbUser Username to authenticate with * @param dbPass Password to authenticate with * @throws DatabaseException If the server information is bad or server is offline or wrong credentials */ public Database(String dbAddress, int dbPort, String dbUser, String dbPass) throws DatabaseException { if (dbAddress != null && dbPort > 0 && dbUser != null && dbPass != null) { String connectionStr = String.format("jdbc:mysql://%s:%d", dbAddress, dbPort); try { dbConnection = DriverManager.getConnection(connectionStr, dbUser, dbPass); } catch (SQLException E) { throw new DatabaseException("Invalid database address/port or credentials entered."); } userList = new ArrayList<User>(); } else throw new DatabaseException("Bad database information entered."); } /** * Get the last error the Database class encounterd * @return Last exception, or null if no exception have occurred */ public Exception getLastError() { return lastError; } /** * Close the potentially opened ResultSet or Statement */ private void closeQueries() { try { queryResult.close(); queryStatement.close(); } catch (SQLException | NullPointerException E) { lastError = E; } } /** * Execute the specified query and save results * @param query Valid SQL query string * @return True if the query was executed succcessfully, false otherwise */ private boolean executeQuery(String query) { try { if (!dbConnection.isClosed()) { //System.out.println("***" + query + "***"); queryStatement = dbConnection.createStatement(); queryResult = queryStatement.executeQuery(query); return true; } } catch (SQLException E) { //System.out.println("***" + E.getMessage() + "***"); closeQueries(); return false; } return false; } /** * Execute a command with no result * @param command Valid sql command string * @return True if the command was executed succcessfully, false otherwise */ private boolean executeCommand(String command) { try { if (!dbConnection.isClosed()) { Statement commandStatement = dbConnection.createStatement(); commandStatement.execute(command); commandStatement.close(); return true; } } catch (SQLException E) { //System.out.println(E.getMessage()); closeQueries(); return false; } return false; } /** * Get the specified attribute of the latest query * @param attributeTitle Attribute to get * @return List of attributes from query, empty list if there are no open results */ private List<String> retrieveAttribute(String attributeTitle) { ArrayList<String> attributes = new ArrayList<String>(); try { while (queryResult.next()){ attributes.add(queryResult.getString(attributeTitle)); } closeQueries(); } catch (SQLException E) { closeQueries(); lastError = E; } return attributes; } /** * Get multiple attributes from the latest query * @param attributeTitles Attributes to get * @return List of attributes from query, empty list if there are no open results */ private List<String> retrieveAttributes(String... attributeTitles) { List<String> attributeList = new ArrayList<String>(); try { while (queryResult.next()) { StringBuilder sb = new StringBuilder(); for (String title : attributeTitles) sb.append(queryResult.getString(title) + ":"); String attributes = sb.toString(); attributeList.add(attributes.substring(0, attributes.length() - 1)); } closeQueries(); } catch (SQLException E) { lastError = E; closeQueries(); } return attributeList; } /** * Select a specified database * @param database Database to switch to * @return True if success, false otherwise */ public boolean selectDatabase(String database) { if (database == null || database.length() < 1) return false; try { dbConnection.setCatalog(database); return true; } catch (SQLException E) { return false; } } /** * Close the SQL connection */ public void close() { try { closeQueries(); dbConnection.close(); } catch (SQLException E) { return; } } /** * Add user to this database instance * @param user Username * @param pass Password * @param pos User's Position * @return True if success, false otherwise */ public boolean addUser(String user, String pass, UserPermission.Position pos) { try { User newUser = new User(user, pass, pos); userList.add(newUser); if (pos == UserPermission.Position.Student) return addStudent(newUser); return true; } catch (UserException E) { return false; } } /** * Basic 'authentication' of a user with the internal userlist * @return True if valid user, false otherwise */ public boolean authUser(String username, String password) { try { for (User U : userList) { if (U.equals(new User(username, password))) { this.currentUser = U; return true; } } } catch (UserException E) { return false; } return false; } /** * Retrieve the currently logged in user * @return The current user */ public User getCurrentUser() { return currentUser; } /** * Return a list of 'tuples' containing attributes corresponding to the table attribute titles requested * @param tableName Name of table to retrieve from * @param optArgs Optional arguments such as (order/sort) appended to the end of query * @param tableFields Title(s) of the desired attributes * @return */ private List<String> getTableInformation(String tableName, String optArgs, String... tableFields) { ArrayList<String> result = new ArrayList<String>(); if (optArgs == null || optArgs.length() == 0) optArgs = ""; if (executeQuery(String.format("select * from `%s` %s", tableName, optArgs))) { try { while (queryResult.next()){ String line = ""; for (String field : tableFields) { line += queryResult.getString(field) + ", "; } result.add(line.substring(0,line.length()-2)); } closeQueries(); } catch (SQLException E) { closeQueries(); lastError = E; } } return result; } /** * Update a specified table in the current database * @param tableName Table to update * @param primaryKeys Primary key(s) of the tuple to update * @param attributes Attribute title(s) and value(s) that are being updated * @return True if update succeeds, false otherwise */ public boolean updateTable(String tableName, HashMap<String, String> primaryKeys, HashMap<String, String> attributes) { if (tableName == null || tableName.length() == 0) return false; StringBuilder sb = new StringBuilder(); // format our new updated values for the query for (String key : attributes.keySet()) sb.append(String.format("`%s`='%s', ", cleanInput(key), cleanInput(attributes.get(key)))); String attributeValues = sb.toString(); sb = new StringBuilder(); // format our primary keys for the query for (String pKey : primaryKeys.keySet()) sb.append(String.format("`%s`='%s' and ", cleanInput(pKey), cleanInput(primaryKeys.get(pKey)))); String primaryKeyValues = sb.toString(); // make sure that primary keys and attributes have at least one element // if not, will get a IOOB exception and this is easier than try/catch if (attributeValues.length() < 2 || primaryKeyValues.length() < 5) return false; attributeValues = attributeValues.substring(0, attributeValues.length() - 2); primaryKeyValues = primaryKeyValues.substring(0, primaryKeyValues.length() - 5); // need to clean input String updateCommand = String.format("update `%s` set %s where %s", tableName, attributeValues, primaryKeyValues); //System.out.println(updateCommand); return executeCommand(updateCommand); } /** * Add a new tuple to the requested table * @param tableName Name of the table to add to * @param tupleValues Values of the tuple attributes * @return True if succeeds, false otherwise */ public boolean insertTuple(String tableName, String... tupleValues) { tupleValues = cleanInput(tupleValues); for (String value : tupleValues) if (value == null || value.length() == 0) return false; String insertCommand = String.format("insert into `%s` values %s", tableName, asSQLArray(tupleValues)); //System.out.println(insertCommand); return executeCommand(insertCommand); } /** * Remove a tuple from the database * @param tableName Table to delete from * @param primaryKeys Primary key titles and values * @return True if the tuple was deleted, false otherwise */ public boolean deleteTuple(String tableName, HashMap<String, String> primaryKeys) { StringBuilder sb = new StringBuilder(); for (String pKey : primaryKeys.keySet()) sb.append(String.format("`%s`='%s' and ", cleanInput(pKey), cleanInput(primaryKeys.get(pKey)))); String primaryKeyValues = sb.toString(); // make sure we have at least one primary key if (primaryKeyValues.length() < 10) return false; primaryKeyValues = primaryKeyValues.substring(0, primaryKeyValues.length() - 4); String deleteCommand = String.format("delete from `%s` where %s", tableName, primaryKeyValues); return executeCommand(deleteCommand); } /* MISC */ /** * Create a SQL formatted 'value array' from individual values * @param array List of values * @return "one", "two", "three" -> ('one', 'two', 'three') */ public String asSQLArray(String... array) { array = cleanInput(array); StringBuilder sb = new StringBuilder(); sb.append("("); for (String S : array) { // NULL can't be in encapulated with quotes if (!S.equals("null")) sb.append(String.format("'%s',", S)); else sb.append("NULL ,"); } String arr = sb.toString(); // remove the last comma arr = arr.substring(0, arr.length() - 1); return arr + ")"; } /** * Clean the input of special charaters */ private String[] cleanInput(String... inputs) { for (int i = 0; i < inputs.length; i++) inputs[i] = inputs[i].replaceAll("`|'|\"|;", ""); return inputs; } private String cleanInput(String input) { if (input != null) return input.replaceAll("`|'|\"|;", ""); return input; } /* PROJECT SPECIFIC METHODS */ /** * Add a student to the database if they don't exist * @param student The student to be added @return Truee if added or already exists, false otherwise */ private boolean addStudent(User student) { if (executeQuery(String.format("select `ID` from `student` where `ID` = %d", student.getID()))) { if (!retrieveAttribute("ID").contains(student.getID().toString())) if (executeCommand(String.format("insert into student values(%d, '%s', 'Biology', '0')", student.getID(), student.getName()))) return true; return true; } return false; } /** * Get the information on all departments in the department relation ( minus budget attribute ) * @return Department Information */ public List<String> getDepartmentInfo() { return getTableInformation("department", null, "dept_name", "building"); } /** * Get the course id, title, department name, and credits for all courses in the course relation * @return See above */ public List<String> getCourseInfo() { return getTableInformation("course", null, "course_id", "title", "dept_name", "credits"); } /** * Get the course id, section id, semester, year, building, room number, and time slot id from all sections in the section relation * @return See above */ public List<String> getSectionInfo() { return getTableInformation("section", null, "course_id", "sec_id", "semester", "year", "building", "room_number", "time_slot_id"); } /** * Get all attributes of sections offered this year * @return See above */ public List<String> getCurrentSections() { return getTableInformation("section", "where `year` = 2016", "course_id", "sec_id", "semester", "year", "building", "room_number", "time_slot_id"); } /** * Get the classes that the current user is enrolled for * @return See above */ public List<String> getCurrrentlyEnrolledSections() { return getTableInformation("takes", String.format("where `ID` = %d and `grade` is NULL", currentUser.getID()), "course_id", "sec_id", "semester", "year"); } /** * Register the current user for the given section * @param course_id ID of the course to register for * @param sec_id Section of the course to register * @return True if the student successfully registered for the section, false otherwise. */ public boolean registerForSection(String course_id, String sec_id) { if (currentUser.getPermissions().getPosition() == UserPermission.Position.Student) return insertTuple("takes", currentUser.getID().toString(), course_id, sec_id, "Spring", "2016", "null"); return false; } /** * Drop the current user's section enrollment matching the given course id * @param course_id ID of the course to drop * @return See above */ public boolean dropSection(String course_id) { if (currentUser.getPermissions().getPosition() == UserPermission.Position.Student) return executeCommand(String.format("delete from `takes` where `course_id` = '%s' and ID = %d and `grade` is NULL", course_id, currentUser.getID())); return false; } /** * Get the GPA and courses taken of the current user if they are a student * @return see above */ public List<String> getTranscript() { if (currentUser.getPermissions().getPosition() == UserPermission.Position.Student) { List<String> transcript = new ArrayList<String>(); if (executeQuery(String.format("select * from `takes` natural join `course` where ID = %d and `grade` is not NULL order by year desc, case semester when 'Spring' then 1 when 'Summer' then 2 when 'Fall' then 3 end desc", currentUser.getID()))) { List<String> takenCourses = retrieveAttributes("title", "course_id", "semester", "year", "grade", "credits"); double studentGPA = 0; double qualityPoints = 0; int totalCreditHours = 0; for (String classTaken : takenCourses) { String[] separate = classTaken.split(":"); String formatted = String.format("Took %s (%s) in %s of %s and received grade of '%s' | %s credits", separate[0], separate[1], separate[2], separate[3], separate[4], separate[5]); transcript.add(formatted); int creditHours = Integer.parseInt(separate[5]); totalCreditHours += creditHours; switch (separate[4]) { case "A": case "A+": case "A-": qualityPoints += 4.0 * creditHours; break; case "B": case "B+": case "B-": qualityPoints += 3.0 * creditHours; break; case "C": case "C+": case "C-": qualityPoints += 2.0 * creditHours; break; case "D": case "D+": case "D-": qualityPoints += 1.0 * creditHours; break; default: // withdrawn or failed! qualityPoints += 0.0; } } if (totalCreditHours > 0) // we don't want to divide by zero! studentGPA = qualityPoints / totalCreditHours; transcript.add(0, "***Transcript for: " + currentUser.getName() + "***"); transcript.add(1, String.format("GPA: %.2f", studentGPA)); } return transcript; } // not a student return new ArrayList<String>(); } }
32.560229
250
0.638147
0505045af42139b35aa2d3b2d663206e51e7e056
10,242
/** * Copyright 2015-2016 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package zipkin.cassandra; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.twitter.zipkin.storage.cassandra.Repository; import zipkin.Codec; import zipkin.DependencyLink; import zipkin.QueryRequest; import zipkin.Span; import zipkin.internal.CorrectForClockSkew; import zipkin.internal.Dependencies; import zipkin.internal.MergeById; import zipkin.internal.Nullable; import zipkin.internal.Pair; import zipkin.spanstore.guava.GuavaSpanStore; import zipkin.spanstore.guava.GuavaToAsyncSpanStoreAdapter; import static com.google.common.util.concurrent.Futures.allAsList; import static com.google.common.util.concurrent.Futures.transform; import static com.google.common.util.concurrent.Futures.transformAsync; import static java.lang.String.format; import static zipkin.cassandra.CassandraUtil.annotationKeys; import static zipkin.cassandra.CassandraUtil.intersectKeySets; import static zipkin.cassandra.CassandraUtil.keyset; import static zipkin.cassandra.CassandraUtil.toSortedList; import static zipkin.internal.Util.midnightUTC; /** * CQL3 implementation of a span store. * * <p>This uses zipkin-cassandra-core which packages "/cassandra-schema-cql3.txt" */ public final class CassandraSpanStore extends GuavaToAsyncSpanStoreAdapter implements GuavaSpanStore, AutoCloseable { private final String keyspace; private final int indexTtl; private final int maxTraceCols; private final Cluster cluster; private final CassandraSpanConsumer spanConsumer; @VisibleForTesting final Repository repository; public CassandraSpanStore(CassandraConfig config) { this.keyspace = config.keyspace; this.indexTtl = config.indexTtl; this.maxTraceCols = config.maxTraceCols; this.cluster = config.toCluster(); this.repository = new Repository(config.keyspace, cluster, config.ensureSchema); this.spanConsumer = new CassandraSpanConsumer(repository, config.spanTtl, config.indexTtl); } @Override protected GuavaSpanStore delegate() { return this; } @Override public ListenableFuture<Void> accept(List<Span> spans) { return spanConsumer.accept(spans); } @Override public ListenableFuture<List<List<Span>>> getTraces(QueryRequest request) { String spanName = request.spanName != null ? request.spanName : ""; final ListenableFuture<Map<Long, Long>> traceIdToTimestamp; if (request.minDuration != null || request.maxDuration != null) { traceIdToTimestamp = repository.getTraceIdsByDuration(request.serviceName, spanName, request.minDuration, request.maxDuration != null ? request.maxDuration : Long.MAX_VALUE, request.endTs * 1000, (request.endTs - request.lookback) * 1000, request.limit, indexTtl); } else if (!spanName.isEmpty()) { traceIdToTimestamp = repository.getTraceIdsBySpanName(request.serviceName, spanName, request.endTs * 1000, request.lookback * 1000, request.limit); } else { traceIdToTimestamp = repository.getTraceIdsByServiceName(request.serviceName, request.endTs * 1000, request.lookback * 1000, request.limit); } List<ByteBuffer> annotationKeys = annotationKeys(request); ListenableFuture<Set<Long>> traceIds; if (annotationKeys.isEmpty()) { // Simplest case is when there is no annotation query. Limit is valid since there's no AND // query that could reduce the results returned to less than the limit. traceIds = transform(traceIdToTimestamp, keyset()); } else { // While a valid port of the scala cassandra span store (from zipkin 1.35), there is a fault. // each annotation key is an intersection, which means we are likely to return < limit. List<ListenableFuture<Map<Long, Long>>> futureKeySetsToIntersect = new ArrayList<>(); futureKeySetsToIntersect.add(traceIdToTimestamp); for (ByteBuffer annotationKey : annotationKeys) { futureKeySetsToIntersect.add(repository.getTraceIdsByAnnotation(annotationKey, request.endTs * 1000, request.lookback * 1000, request.limit)); } // We achieve the AND goal, by intersecting each of the key sets. traceIds = transform(allAsList(futureKeySetsToIntersect), intersectKeySets()); } return transformAsync(traceIds, new AsyncFunction<Set<Long>, List<List<Span>>>() { @Override public ListenableFuture<List<List<Span>>> apply(Set<Long> traceIds) { return transform(repository.getSpansByTraceIds(traceIds.toArray(new Long[traceIds.size()]), maxTraceCols), ConvertTracesResponse.INSTANCE); } @Override public String toString() { return "getSpansByTraceIds"; } }); } enum ConvertTracesResponse implements Function<Map<Long, List<ByteBuffer>>, List<List<Span>>> { INSTANCE; @Override public List<List<Span>> apply(Map<Long, List<ByteBuffer>> input) { Collection<List<ByteBuffer>> encodedTraces = input.values(); List<List<Span>> result = new ArrayList<>(encodedTraces.size()); for (List<ByteBuffer> encodedTrace : encodedTraces) { List<Span> spans = new ArrayList<>(encodedTrace.size()); for (ByteBuffer encodedSpan : encodedTrace) { spans.add(Codec.THRIFT.readSpan(encodedSpan)); } result.add(CorrectForClockSkew.apply(MergeById.apply(spans))); } return TRACE_DESCENDING.immutableSortedCopy(result); } } @Override public ListenableFuture<List<Span>> getRawTrace(long traceId) { return transform(repository.getSpansByTraceIds(new Long[] {traceId}, maxTraceCols), new Function<Map<Long, List<ByteBuffer>>, List<Span>>() { @Override public List<Span> apply(Map<Long, List<ByteBuffer>> encodedTraces) { if (encodedTraces.isEmpty()) return null; List<ByteBuffer> encodedTrace = encodedTraces.values().iterator().next(); ImmutableList.Builder<Span> result = ImmutableList.builder(); for (ByteBuffer encodedSpan : encodedTrace) { result.add(Codec.THRIFT.readSpan(encodedSpan)); } return result.build(); } }); } @Override public ListenableFuture<List<Span>> getTrace(long traceId) { return transform(getRawTrace(traceId), new Function<List<Span>, List<Span>>() { @Override public List<Span> apply(List<Span> input) { if (input == null || input.isEmpty()) return null; return ImmutableList.copyOf(CorrectForClockSkew.apply(MergeById.apply(input))); } }); } @Override public ListenableFuture<List<String>> getServiceNames() { return transform(repository.getServiceNames(), toSortedList()); } @Override public ListenableFuture<List<String>> getSpanNames(String service) { if (service == null) return EMPTY_LIST; // service names are always lowercase! return transform(repository.getSpanNames(service.toLowerCase()), toSortedList()); } @Override public ListenableFuture<List<DependencyLink>> getDependencies(long endTs, @Nullable Long lookback) { long endEpochDayMillis = midnightUTC(endTs); long startEpochDayMillis = midnightUTC(endTs - (lookback != null ? lookback : endTs)); return transform(repository.getDependencies(startEpochDayMillis, endEpochDayMillis), ConvertDependenciesResponse.INSTANCE); } enum ConvertDependenciesResponse implements Function<List<ByteBuffer>, List<DependencyLink>> { INSTANCE; @Override public List<DependencyLink> apply(List<ByteBuffer> encodedDailyDependencies) { // Combine the dependency links from startEpochDayMillis until endEpochDayMillis Map<Pair<String>, Long> links = new LinkedHashMap<>(encodedDailyDependencies.size()); for (ByteBuffer encodedDayOfDependencies : encodedDailyDependencies) { for (DependencyLink link : Dependencies.fromThrift(encodedDayOfDependencies).links) { Pair<String> parentChild = Pair.create(link.parent, link.child); long callCount = links.containsKey(parentChild) ? links.get(parentChild) : 0L; callCount += link.callCount; links.put(parentChild, callCount); } } List<DependencyLink> result = new ArrayList<>(links.size()); for (Map.Entry<Pair<String>, Long> link : links.entrySet()) { result.add(DependencyLink.create(link.getKey()._1, link.getKey()._2, link.getValue())); } return result; } } /** Used for testing */ void clear() { try (Session session = cluster.connect()) { List<ListenableFuture<?>> futures = new LinkedList<>(); for (String cf : ImmutableList.of( "traces", "dependencies", "service_names", "span_names", "service_name_index", "service_span_name_index", "annotations_index", "span_duration_index" )) { futures.add(session.executeAsync(format("TRUNCATE %s.%s", keyspace, cf))); } Futures.getUnchecked(Futures.allAsList(futures)); } } @Override public void close() { repository.close(); cluster.close(); } }
40.482213
100
0.719781
297a8e3fb45bbae2cba6866638d539e950d49b8e
4,453
package test.api; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import de.aservo.ldap.adapter.api.database.Row; import de.aservo.ldap.adapter.api.database.exception.UnknownColumnException; import de.aservo.ldap.adapter.api.entity.ColumnNames; import de.aservo.ldap.adapter.api.entity.EntityType; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.LinkedList; import java.util.List; public interface QueryTestPlan { interface Element { boolean isIgnored(); String getDescription(); String getBase(); String getFilter(); String getScope(); Iterable<Row> getExpectations(); } static List<Element> createQueryTestPlan(File testPlanFile) throws Exception { Gson gson = new Gson(); List<Element> testPlanElements = new LinkedList<>(); JsonObject objectNode = gson.fromJson( new InputStreamReader(new FileInputStream(testPlanFile), StandardCharsets.UTF_8), JsonObject.class); JsonArray tests = objectNode.getAsJsonArray("query_tests"); for (JsonElement test : tests) { final boolean ignored = test.getAsJsonObject().get("ignored").getAsBoolean(); final String description = test.getAsJsonObject().get("description").getAsString(); final String base = test.getAsJsonObject().get("base").getAsString(); final String filter = test.getAsJsonObject().get("filter").getAsString(); final String scope = test.getAsJsonObject().get("scope").getAsString(); final HashSet<Row> expectations = new HashSet<>(); testPlanElements.add(new Element() { public boolean isIgnored() { return ignored; } public String getDescription() { return description; } public String getBase() { return base; } public String getFilter() { return filter; } public String getScope() { return scope; } public Iterable<Row> getExpectations() { return expectations; } }); JsonArray expectationsNode = test.getAsJsonObject().getAsJsonArray("expectations"); for (JsonElement element : expectationsNode) { EntityType entityType = EntityType.fromString(element.getAsJsonObject().get("type").getAsString()); List<String> names = new LinkedList<>(); JsonElement idElement = element.getAsJsonObject().get("id"); JsonElement idsElement = element.getAsJsonObject().get("ids"); if (idElement != null && idsElement == null) names.add(idElement.getAsString()); else if (idElement == null && idsElement != null) idsElement.getAsJsonArray().forEach(x -> names.add(x.getAsString())); else throw new IllegalArgumentException("Expect exclusively the key 'id' or 'ids' for expectations."); for (String name : names) { expectations.add(new Row() { public <T> T apply(String columnName, Class<T> clazz) { if (columnName.equals(ColumnNames.TYPE)) return (T) entityType.toString(); if (columnName.equals(ColumnNames.ID)) return (T) name.toLowerCase(); if (columnName.equals(ColumnNames.NAME) && entityType == EntityType.GROUP) return (T) name; if (columnName.equals(ColumnNames.USERNAME) && entityType == EntityType.USER) return (T) name; throw new UnknownColumnException("Cannot find column " + columnName + " for entity."); } }); } } } return testPlanElements; } }
32.268116
117
0.556254
942c296347fdcb329e908beb79052ffb22169f64
661
package uav.navigation.aco; import network.InspectableEdge; import network.Node; import network.UAVNetwork; /** * An ACO implementation that takes the neighbours of the edges into account. * * The heuristic of an edge is calculated based on its last inspection time: (time - edge.getLIT())^beta * The pheromone is calculated through following formula: [1 + (1/(pheromones+1))^2]^alpha * * @author Wietse Buseyne * */ public class LNIACOImpl implements ACOImpl { public double computeHeuristicValue(UAVNetwork network, Node node, InspectableEdge edge, long currentStep, double beta) { return Math.pow((currentStep - edge.getLIT()), beta); } }
30.045455
122
0.747352
177f48e7b9f78c069594b69913ce7c7b917003be
2,307
/* * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. * * 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. */ /** * @author Hugo Beilis * @author Osvaldo Demo * @author Jorge Rafael * @version 1.0 */ package ar.org.fitc.test.crypto.spec; import ar.org.fitc.test.util.TestSuiteAcumulable; import junit.framework.Test; import junit.framework.TestSuite; public class TestSuiteCryptoSpec { public static void main(String[] args) { junit.textui.TestRunner.run(TestSuiteCryptoSpec.suite()); } public static Test suite() { TestSuite suite = new TestSuite("Test for ar.org.fitc.test.crypto.spec"); //$JUnit-BEGIN$ suite.addTest(new TestSuiteAcumulable(TestPBEParameterSpec.class)); suite.addTest(new TestSuiteAcumulable(TestDESKeySpec.class)); suite.addTest(new TestSuiteAcumulable(TestDHPublicKeySpec.class)); suite.addTest(new TestSuiteAcumulable(TestDESedeKeySpec.class)); suite.addTest(new TestSuiteAcumulable(TestSecretKeySpec.class)); suite.addTest(new TestSuiteAcumulable(TestDHPrivateKeySpec.class)); suite.addTest(new TestSuiteAcumulable(TestRC2ParameterSpec.class)); suite.addTest(new TestSuiteAcumulable(TestDHGenParameterSpec.class)); suite.addTest(new TestSuiteAcumulable(TestDHParameterSpec.class)); suite.addTest(new TestSuiteAcumulable(TestOAEPParameterSpec.class)); suite.addTest(new TestSuiteAcumulable(TestRC5ParameterSpec.class)); suite.addTest(new TestSuiteAcumulable(TestIvParameterSpec.class)); suite.addTest(new TestSuiteAcumulable(TestPSourcePSpecified.class)); suite.addTest(new TestSuiteAcumulable(TestPBEKeySpec.class)); //$JUnit-END$ return suite; } }
39.775862
82
0.73212
b22bcfef488755d74eceaaf1f25cbe495488c289
2,565
package net.andreho.dyn.classpath.impl; import net.andreho.dyn.classpath.Entry; import java.net.URL; import java.util.Collections; import java.util.Set; import java.util.WeakHashMap; import static java.util.Objects.requireNonNull; /** * <br/>Created by a.hofmann on 18.07.2017 at 12:07. */ public abstract class AbstractEntry implements Entry { private final String id; private final URL classPathUrl; private final Set<ClassLoader> classLoaderSet; public AbstractEntry(final String id, final ClassLoader classLoader, final URL classPathUrl) { this.id = requireNonNull(id); this.classPathUrl = requireNonNull(classPathUrl); this.classLoaderSet = Collections.newSetFromMap(new WeakHashMap<>()); this.classLoaderSet.add(classLoader); } @Override public String getId() { return id; } @Override public Set<ClassLoader> getClassLoaders() { return Collections.unmodifiableSet(classLoaderSet); } @Override public URL getClassPathUrl() { return classPathUrl; } @Override public Entry merge(final Entry other) { if(other != null && other != this) { verifyIds(other); verifyClassPaths(other); addClassLoadersSafely(other); } return this; } private void addClassLoadersSafely(final Entry other) { final Set<ClassLoader> classLoaderSet = this.classLoaderSet; synchronized (classLoaderSet) { classLoaderSet.addAll(other.getClassLoaders()); } } private void verifyClassPaths(final Entry other) { if(!getClassPathUrl().equals(other.getClassPathUrl())) { throw new IllegalArgumentException( "Only entries with equal ClassPaths may be merged: "+getClassPathUrl()+" <> "+other.getClassPathUrl()); } } private void verifyIds(final Entry other) { if(!other.getId().equals(other.getId())) { throw new IllegalArgumentException( "Only entries with equal IDs can be merged: "+getId()+" <> "+other.getId()); } } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Entry)) { return false; } final Entry that = (Entry) o; if (!id.equals(that.getId())) { return false; } return classPathUrl.equals(that.getClassPathUrl()); } @Override public int hashCode() { int result = id.hashCode(); result = 31 * result + classPathUrl.hashCode(); return result; } @Override public String toString() { return "Entry(" + id + ")"; } }
24.428571
111
0.663548
9764f939cf6dc523f5d8e216eda89d2582c74ac1
821
package br.com.alura; import java.util.stream.Collectors; import javax.validation.ConstraintViolationException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import br.com.alura.dto.MensagemErroDTO; @Provider public class ConstraintValidationMapper implements ExceptionMapper<ConstraintViolationException> { @Override public Response toResponse(ConstraintViolationException e) { return Response .status(Response.Status.BAD_REQUEST) .entity( MensagemErroDTO.build( e.getConstraintViolations() .stream() .map(constraintViolation -> constraintViolation.getMessage()) .collect(Collectors.toList()))) .build(); } }
29.321429
98
0.676005
3de5ec67e2f6ce7a0699b38d3af800a43ade7187
1,151
package com.mmall.controller; import com.mmall.beans.PageQuery; import com.mmall.common.JsonData; import com.mmall.param.SearchLogParam; import com.mmall.service.SysLogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * @author liliang * @date 2017/11/30. */ @RequestMapping("/sys/log") @Controller public class SysLogController { @Autowired private SysLogService sysLogService; @RequestMapping("/log.page") public String page() { return "log"; } @RequestMapping("/recover.json") @ResponseBody public JsonData recover(@RequestParam("id") int id) { sysLogService.recover(id); return JsonData.success(); } @RequestMapping("/page.json") @ResponseBody public JsonData searchPage(SearchLogParam param, PageQuery pageQuery) { return JsonData.success(sysLogService.searchPageList(param, pageQuery)); } }
27.404762
80
0.742832
0f31937d4b5e7c5a69e3ddc928afa61778086680
14,249
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jingkastudio.android.hippocampus; import android.app.AlertDialog; import android.app.LoaderManager; import android.content.ContentValues; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.jingkastudio.android.hippocampus.data.EntryContract.DailyEntry; /** * Allows user to create a new entry or edit an existing one. */ public class EditorActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { /** Identifier for the entry data loader */ private static final int EXISTING_ENTRY_LOADER = 0; /** Content URI for the existing entry (null if it's a new entry) */ private Uri mCurrentEntryUri; /** EditText field to enter the entry's name */ private EditText mTitleEditText; /** EditText field to enter the entry's breed */ private EditText mBodyEditText; /** Boolean flag that keeps track of whether the entry has been edited */ private boolean mEntryHasChanged = false; /** * OnTouchListener that listens for any user touches on a View, implying that they are modifying * the view, and we change the mEntryHasChanged boolean to true. */ private View.OnTouchListener mTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mEntryHasChanged = true; return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editor); // Examine the intent to determine to create a new entry or edit an existing one Intent intent = getIntent(); mCurrentEntryUri = intent.getData(); // If the intent DOES NOT contain a entry content URI, create a new entry if (mCurrentEntryUri == null) { } else { // Initialize a loader to rad the entry data from the database getLoaderManager().initLoader(EXISTING_ENTRY_LOADER, null, this); } // Find all relevant views that we will need to read user input from mTitleEditText = (EditText) findViewById(R.id.edit_entry_title); mBodyEditText = (EditText) findViewById(R.id.edit_entry_body); // Setup OnTouchListeners on all the input fields, so we can determine if the user // has touched or modified them. mTitleEditText.setOnTouchListener(mTouchListener); mBodyEditText.setOnTouchListener(mTouchListener); } /** * Get user input from editor and save new entry into database */ private void saveEntry() { // Read from input fields // Use trim to eliminate leading or trailing white space String titleString = mTitleEditText.getText().toString().trim(); String bodyString = mBodyEditText.getText().toString().trim(); if (mCurrentEntryUri == null && TextUtils.isEmpty(titleString) && TextUtils.isEmpty(bodyString)) { // No change, return early return; } // Create a ContentValues object where column names are the keys ContentValues values = new ContentValues(); values.put(DailyEntry.COLUMN_TITLE, titleString); values.put(DailyEntry.COLUMN_BODY, bodyString); // Determine if this is a new or existing entry if(mCurrentEntryUri == null) { // This is a new entry Uri newUri = getContentResolver().insert(DailyEntry.CONTENT_URI, values); if(newUri == null) { Toast.makeText(this, getString(R.string.editor_insert_entry_failed), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.editor_insert_entry_successful), Toast.LENGTH_SHORT).show(); } } else { // This is an existing entry int rowsAffected = getContentResolver().update(mCurrentEntryUri, values, null, null); if(rowsAffected == 0) { Toast.makeText(this, getString(R.string.editor_update_entry_failed), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.editor_update_entry_successful), Toast.LENGTH_SHORT).show(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu options from the res/menu/menu_editor.xml file. // This adds menu items to the app bar. getMenuInflater().inflate(R.menu.menu_editor, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Save" menu option case R.id.action_save: // Save entry to database saveEntry(); // Exit activity finish(); return true; // Respond to a click on the "Delete" menu option case R.id.action_delete: // Pop up confirmation dialog for deletion showDeleteConfirmationDialog(); return true; // Respond to a click on the "Up" arrow button in the app bar case android.R.id.home: // If the entry hasn't changed, return back if( !mEntryHasChanged) { // Navigate back to parent activity (CatalogActivity) NavUtils.navigateUpFromSameTask(this); return true; } // Otherwise if there are unsaved changes, setup a dialog to warn the user. DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // User clicked "Discard" button, navigate to parent activity. NavUtils.navigateUpFromSameTask(EditorActivity.this); } }; // Show a dialog that notifies the user they have unsaved changes showUnsavedChangesDialog(discardButtonClickListener); return true; } return super.onOptionsItemSelected(item); } /** * This method is called when the back button is pressed. */ @Override public void onBackPressed() { // If the entry hasn't changed, continue with handling back button press if (!mEntryHasChanged) { super.onBackPressed(); return; } // Otherwise if there are unsaved changes, setup a dialog to warn the user. // Create a click listener to handle the user confirming that changes should be discarded. DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // User clicked "Discard" button, close the current activity. finish(); } }; // Show dialog that there are unsaved changes showUnsavedChangesDialog(discardButtonClickListener); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String[] projection = { DailyEntry._ID, DailyEntry.COLUMN_TITLE, DailyEntry.COLUMN_BODY, DailyEntry.COLUMN_TAG }; // Execute the ContentProvider's query method on a background thread return new CursorLoader(this, mCurrentEntryUri, projection, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Bail early if the cursor is null or there is less than 1 row in the cursor if(cursor == null || cursor.getCount() < 1) { return; } // Proceed with moving to the first row of the cursor and reading data from it if(cursor.moveToFirst()) { int titleColumnIndex = cursor.getColumnIndex(DailyEntry.COLUMN_TITLE); int bodyColumnIndex = cursor.getColumnIndex(DailyEntry.COLUMN_BODY); int tagColumnIndex = cursor.getColumnIndex(DailyEntry.COLUMN_TAG); // Extract out the value from the Cursor for the given column index String title = cursor.getString(titleColumnIndex); String body = cursor.getString(bodyColumnIndex); String tag = cursor.getString(tagColumnIndex); // TODO to be used later // Update the views on the screen with the values from the database mTitleEditText.setText(title); mBodyEditText.setText(body); } } @Override public void onLoaderReset(Loader<Cursor> loader) { // If the loader is invalidated, clear out all the data from the input fields mTitleEditText.setText(""); mBodyEditText.setText(""); } /** * Show a dialog that warns the user there are unsaved changes that will be lost * if they continue leaving the editor. * * @param discardButtonClickListener is the click listener for what to do when * the user confirms they want to discard their changes */ private void showUnsavedChangesDialog( DialogInterface.OnClickListener discardButtonClickListener) { // Create an AlertDialog.Builder and set the message, and click listeners // for the postivie and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.unsaved_changes_dialog_msg); builder.setPositiveButton(R.string.discard, discardButtonClickListener); builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Keep editing" button, so dismiss the dialog // and continue editing the entry. if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } /** * Prompt the user to confirm that they want to delete this entry. */ private void showDeleteConfirmationDialog() { // Create an AlertDialog.Builder and set the message, and click listeners // for the postivie and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.delete_dialog_msg); builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Delete" button, so delete the entry. deleteEntry(); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Cancel" button, so dismiss the dialog // and continue editing the entry. if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } /** * Perform the deletion of the entry in the database. */ private void deleteEntry() { // Only perform the delete if this is an existing entry. if (mCurrentEntryUri != null) { // Call the ContentResolver to delete the entry at the given content URI. // Pass in null for the selection and selection args because the mCurrentEntryUri // content URI already identifies the entry that we want. int rowsDeleted = getContentResolver().delete(mCurrentEntryUri, null, null); // Show a toast message depending on whether or not the delete was successful. if (rowsDeleted == 0) { // If no rows were deleted, then there was an error with the delete. Toast.makeText(this, getString(R.string.editor_delete_entry_failed), Toast.LENGTH_SHORT).show(); } else { // Otherwise, the delete was successful and we can display a toast. Toast.makeText(this, getString(R.string.editor_delete_entry_successful), Toast.LENGTH_SHORT).show(); } } // Close the activity finish(); } }
40.480114
116
0.62629
233a6da4ce8428244d7e6b92002cf6848ec128f4
9,176
package com.jonalmeida.project420; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link ComposeSmsFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link ComposeSmsFragment#newInstance} factory method to * create an instance of this fragment. */ public class ComposeSmsFragment extends Fragment { private static final String TAG = "ComposeSmsFragment"; /** * For Contact picking */ private static final int CONTACT_PICKER_RESULT = 1001; private EditText contactSearch; /** * For checking if we're in a master-details view */ public static final String ARG_IS_TWO_PANE = "two_pane"; private boolean mIsTwoPane = false; private OnFragmentInteractionListener mListener; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param twoPane Parameter 1. * @return A new instance of fragment ComposeSmsFragment. */ // TODO: Rename and change types and number of parameters public static ComposeSmsFragment newInstance(boolean twoPane) { ComposeSmsFragment fragment = new ComposeSmsFragment(); Bundle args = new Bundle(); args.putBoolean(ARG_IS_TWO_PANE, twoPane); fragment.setArguments(args); return fragment; } public ComposeSmsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mIsTwoPane = getArguments().getBoolean(ARG_IS_TWO_PANE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_compose_sms, container, false); contactSearch = (EditText) v.findViewById(R.id.compose_contact_search_edit_text); contactSearchEditText(v); return v; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } private void contactSearchEditText(View v) { contactSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (b) { Intent pickContactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); startActivityForResult(pickContactIntent, CONTACT_PICKER_RESULT); } else { // use spinner } } }); contactSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { Log.d(TAG, "Just typed: " + editable.toString()); // TODO: Interact with spinner here } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { String phoneNumber; Uri uri = data.getData(); Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER); phoneNumber = cursor.getString(phoneIndex); Log.d(TAG, "We got this number: " + phoneNumber); if (phoneNumber != null) { // TODO: Check if the number exists in thread ContactItem contactItem = existingThreadFromNumber(phoneNumber); // If true, open the new activity/fragment with that number if (contactItem != null) { if (mIsTwoPane) { // Treat as fragment Bundle arguments = new Bundle(); arguments.putString(ContactDetailFragment.ARG_DISPLAY_NAME, contactItem.getAddress()); arguments.putInt(ContactDetailFragment.ARG_THREAD_ID, contactItem.getThreadId()); arguments.putString(ContactDetailFragment.ARG_ADDRESS, contactItem.getAddress()); ContactDetailFragment fragment = new ContactDetailFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.contact_detail_container, fragment) .commit(); } else { // Treat as activity Intent detailIntent = new Intent(getActivity(), ContactDetailActivity.class); detailIntent.putExtra(ContactDetailFragment.ARG_DISPLAY_NAME, contactItem.getAddress()); detailIntent.putExtra(ContactDetailFragment.ARG_THREAD_ID, contactItem.getThreadId()); detailIntent.putExtra(ContactDetailFragment.ARG_ADDRESS, contactItem.getAddress()); startActivity(detailIntent); getActivity().finish(); getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); } } else { // Else, new conversation with number in it. contactSearch.append(phoneNumber); } } cursor.close(); } } public ContactItem existingThreadFromNumber(String phoneNumber) { ContentResolver contentResolver = getActivity().getContentResolver(); Uri uri = Uri.parse("content://mms-sms/conversations"); Cursor cursor = contentResolver.query( uri, new String[]{"body", "person", "address", "normalized_date", "thread_id"}, null, null, "normalized_date" ); if (cursor.moveToFirst()) { do { final int addressType = cursor.getType(cursor.getColumnIndex("address")); if (addressType == Cursor.FIELD_TYPE_NULL) { continue; } String convoAddress = cursor.getString(cursor.getColumnIndex("address")); if (convoAddress.equals(phoneNumber)) { ContactItem contact = new ContactItem( cursor.getString(cursor.getColumnIndex("address")), cursor.getInt(cursor.getColumnIndex("thread_id")) ); Log.d(TAG, "We got an existing thread: " + contact); cursor.close(); return contact; } } while (cursor.moveToNext()); } cursor.close(); return null; } }
39.046809
117
0.612685
884c490f735f476792565a574ddab1cdb675684c
16,569
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.client.statistics; import com.hazelcast.cache.ICache; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.impl.ClientEngineImpl; import com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl; import com.hazelcast.client.impl.connection.tcp.TcpClientConnection; import com.hazelcast.client.impl.statistics.ClientStatistics; import com.hazelcast.client.impl.statistics.ClientStatisticsService; import com.hazelcast.client.test.ClientTestSupport; import com.hazelcast.client.test.TestHazelcastFactory; import com.hazelcast.config.CacheConfig; import com.hazelcast.config.InMemoryFormat; import com.hazelcast.config.NearCacheConfig; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ICacheManager; import com.hazelcast.instance.BuildInfoProvider; import com.hazelcast.map.IMap; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.After; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import javax.cache.CacheManager; import javax.cache.spi.CachingProvider; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import static com.hazelcast.cache.CacheTestSupport.createServerCachingProvider; import static com.hazelcast.client.impl.statistics.ClientStatisticsService.split; import static com.hazelcast.client.impl.statistics.ClientStatisticsService.unescapeSpecialCharacters; import static com.hazelcast.test.Accessors.getClientEngineImpl; import static java.lang.String.format; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class ClientStatisticsTest extends ClientTestSupport { private static final int STATS_PERIOD_SECONDS = 1; private static final long STATS_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(STATS_PERIOD_SECONDS); private static final String MAP_NAME = "StatTestMapFirst.First"; private static final String CACHE_NAME = "StatTestICache.First"; private static final String MAP_HITS_KEY = "nc." + MAP_NAME + ".hits"; private static final String CACHE_HITS_KEY = "nc.hz/" + CACHE_NAME + ".hits"; private final TestHazelcastFactory hazelcastFactory = new TestHazelcastFactory(); @After public void cleanup() { hazelcastFactory.terminateAll(); } @Test public void testStatisticsCollectionNonDefaultPeriod() { HazelcastInstance hazelcastInstance = hazelcastFactory.newHazelcastInstance(); final HazelcastClientInstanceImpl client = createHazelcastClient(); final ClientEngineImpl clientEngine = getClientEngineImpl(hazelcastInstance); long clientConnectionTime = System.currentTimeMillis(); // wait enough time for statistics collection waitForFirstStatisticsCollection(client, clientEngine); Map<String, String> stats = getStats(client, clientEngine); String connStat = stats.get("clusterConnectionTimestamp"); assertNotNull(format("clusterConnectionTimestamp should not be null (%s)", stats), connStat); Long connectionTimeStat = Long.valueOf(connStat); assertNotNull(format("connectionTimeStat should not be null (%s)", stats), connStat); TcpClientConnection aConnection = (TcpClientConnection) client.getConnectionManager().getActiveConnections().iterator().next(); String expectedClientAddress = aConnection.getLocalSocketAddress().getAddress().getHostAddress(); assertEquals(expectedClientAddress, stats.get("clientAddress")); assertEquals(BuildInfoProvider.getBuildInfo().getVersion(), stats.get("clientVersion")); assertEquals(client.getName(), stats.get("clientName")); // time measured by us after client connection should be greater than the connection time reported by the statistics assertTrue(format("connectionTimeStat was %d, clientConnectionTime was %d (%s)", connectionTimeStat, clientConnectionTime, stats), clientConnectionTime >= connectionTimeStat); String mapHits = stats.get(MAP_HITS_KEY); assertNull(format("%s should be null (%s)", MAP_HITS_KEY, stats), mapHits); String cacheHits = stats.get(CACHE_HITS_KEY); assertNull(format("%s should be null (%s)", CACHE_HITS_KEY, stats), cacheHits); String lastStatisticsCollectionTimeString = stats.get("lastStatisticsCollectionTime"); final long lastCollectionTime = Long.parseLong(lastStatisticsCollectionTimeString); // this creates empty map statistics client.getMap(MAP_NAME); // wait enough time for statistics collection waitForNextStatsCollection(client, clientEngine, lastStatisticsCollectionTimeString); assertTrueEventually(() -> { Map<String, String> stats12 = getStats(client, clientEngine); String mapHits12 = stats12.get(MAP_HITS_KEY); assertNotNull(format("%s should not be null (%s)", MAP_HITS_KEY, stats12), mapHits12); assertEquals(format("Expected 0 map hits (%s)", stats12), "0", mapHits12); String cacheHits12 = stats12.get(CACHE_HITS_KEY); assertNull(format("%s should be null (%s)", CACHE_HITS_KEY, stats12), cacheHits12); // verify that collection is periodic verifyThatCollectionIsPeriodic(stats12, lastCollectionTime); }); // produce map and cache stat produceSomeStats(hazelcastInstance, client); assertTrueEventually(() -> { Map<String, String> stats1 = getStats(client, clientEngine); String mapHits1 = stats1.get(MAP_HITS_KEY); assertNotNull(format("%s should not be null (%s)", MAP_HITS_KEY, stats1), mapHits1); assertEquals(format("Expected 1 map hits (%s)", stats1), "1", mapHits1); String cacheHits1 = stats1.get(CACHE_HITS_KEY); assertNotNull(format("%s should not be null (%s)", CACHE_HITS_KEY, stats1), cacheHits1); assertEquals(format("Expected 1 cache hits (%s)", stats1), "1", cacheHits1); }); } @Test public void testStatisticsPeriod() { HazelcastInstance hazelcastInstance = hazelcastFactory.newHazelcastInstance(); HazelcastClientInstanceImpl client = createHazelcastClient(); ClientEngineImpl clientEngine = getClientEngineImpl(hazelcastInstance); // wait enough time for statistics collection waitForFirstStatisticsCollection(client, clientEngine); Map<String, String> initialStats = getStats(client, clientEngine); // produce map and cache stat produceSomeStats(hazelcastInstance, client); // wait enough time for statistics collection waitForNextStatsCollection(client, clientEngine, initialStats.get("lastStatisticsCollectionTime")); assertNotEquals("initial statistics should not be the same as current stats", initialStats, getStats(client, clientEngine)); } @Test public void testStatisticsClusterReconnect() { HazelcastInstance hazelcastInstance = hazelcastFactory.newHazelcastInstance(); HazelcastClientInstanceImpl client = createHazelcastClient(); ReconnectListener reconnectListener = new ReconnectListener(); client.getLifecycleService().addLifecycleListener(reconnectListener); hazelcastInstance.getLifecycleService().terminate(); hazelcastInstance = hazelcastFactory.newHazelcastInstance(); ClientEngineImpl clientEngine = getClientEngineImpl(hazelcastInstance); assertOpenEventually(reconnectListener.reconnectedLatch); // wait enough time for statistics collection waitForFirstStatisticsCollection(client, clientEngine); getStats(client, clientEngine); } @Test public void testStatisticsTwoClients() { HazelcastInstance hazelcastInstance = hazelcastFactory.newHazelcastInstance(); final HazelcastClientInstanceImpl client1 = createHazelcastClient(); final HazelcastClientInstanceImpl client2 = createHazelcastClient(); final ClientEngineImpl clientEngine = getClientEngineImpl(hazelcastInstance); assertTrueEventually(() -> { Map<UUID, ClientStatistics> clientStatistics = clientEngine.getClientStatistics(); assertNotNull(clientStatistics); assertEquals(2, clientStatistics.size()); List<UUID> expectedUUIDs = new ArrayList<>(2); expectedUUIDs.add(client1.getClientClusterService().getLocalClient().getUuid()); expectedUUIDs.add(client2.getClientClusterService().getLocalClient().getUuid()); for (Map.Entry<UUID, ClientStatistics> clientEntry : clientStatistics.entrySet()) { assertTrue(expectedUUIDs.contains(clientEntry.getKey())); String clientAttributes = clientEntry.getValue().clientAttributes(); assertNotNull(clientAttributes); } }); } @Test public void testNoUpdateWhenDisabled() { HazelcastInstance hazelcastInstance = hazelcastFactory.newHazelcastInstance(); final ClientEngineImpl clientEngine = getClientEngineImpl(hazelcastInstance); ClientConfig clientConfig = new ClientConfig(); clientConfig.getMetricsConfig() .setEnabled(false) .setCollectionFrequencySeconds(STATS_PERIOD_SECONDS); hazelcastFactory.newHazelcastClient(clientConfig); assertTrueAllTheTime(() -> { Map<UUID, ClientStatistics> statistics = clientEngine.getClientStatistics(); assertEquals(0, statistics.size()); }, STATS_PERIOD_SECONDS * 3); } @Test public void testEscapeSpecialCharacter() { String originalString = "stat1=value1.lastName,stat2=value2\\hello=="; String escapedString = "stat1\\=value1\\.lastName\\,stat2\\=value2\\\\hello\\=\\="; StringBuilder buffer = new StringBuilder(originalString); ClientStatisticsService.escapeSpecialCharacters(buffer); assertEquals(escapedString, buffer.toString()); assertEquals(originalString, unescapeSpecialCharacters(escapedString)); } @Test public void testSplit() { String escapedString = "stat1=value1.lastName,stat2=full\\name==hazel\\,ali,"; String[] expectedStrings = {"stat1=value1.lastName", "stat2=full\\name==hazel\\,ali"}; List<String> strings = split(escapedString); assertArrayEquals(expectedStrings, strings.toArray()); } private HazelcastClientInstanceImpl createHazelcastClient() { ClientConfig clientConfig = new ClientConfig() // add IMap and ICache with Near Cache config .addNearCacheConfig(new NearCacheConfig(MAP_NAME)) .addNearCacheConfig(new NearCacheConfig(CACHE_NAME)); clientConfig.getConnectionStrategyConfig().getConnectionRetryConfig().setClusterConnectTimeoutMillis(Long.MAX_VALUE); clientConfig.getMetricsConfig() .setCollectionFrequencySeconds(STATS_PERIOD_SECONDS); HazelcastInstance clientInstance = hazelcastFactory.newHazelcastClient(clientConfig); return getHazelcastClientInstanceImpl(clientInstance); } private static void produceSomeStats(HazelcastInstance hazelcastInstance, HazelcastClientInstanceImpl client) { IMap<Integer, Integer> map = client.getMap(MAP_NAME); map.put(5, 10); assertEquals(10, map.get(5).intValue()); assertEquals(10, map.get(5).intValue()); ICache<Integer, Integer> cache = createCache(hazelcastInstance, CACHE_NAME, client); cache.put(9, 20); assertEquals(20, cache.get(9).intValue()); assertEquals(20, cache.get(9).intValue()); } private static ICache<Integer, Integer> createCache(HazelcastInstance hazelcastInstance, String testCacheName, HazelcastInstance clientInstance) { CachingProvider cachingProvider = getCachingProvider(hazelcastInstance); CacheManager cacheManager = cachingProvider.getCacheManager(); cacheManager.createCache(testCacheName, createCacheConfig()); ICacheManager clientCacheManager = clientInstance.getCacheManager(); return clientCacheManager.getCache(testCacheName); } private static CachingProvider getCachingProvider(HazelcastInstance instance) { return createServerCachingProvider(instance); } private static <K, V> CacheConfig<K, V> createCacheConfig() { return new CacheConfig<K, V>() .setInMemoryFormat(InMemoryFormat.BINARY); } private static Map<String, String> getStats(HazelcastClientInstanceImpl client, ClientEngineImpl clientEngine) { Map<UUID, ClientStatistics> clientStatistics = clientEngine.getClientStatistics(); assertNotNull("clientStatistics should not be null", clientStatistics); assertEquals("clientStatistics.size() should be 1", 1, clientStatistics.size()); Set<Map.Entry<UUID, ClientStatistics>> entries = clientStatistics.entrySet(); Map.Entry<UUID, ClientStatistics> statEntry = entries.iterator().next(); assertEquals(client.getClientClusterService().getLocalClient().getUuid(), statEntry.getKey()); return parseClientAttributeValue(statEntry.getValue().clientAttributes()); } private static Map<String, String> parseClientAttributeValue(String value) { Map<String, String> result = new HashMap<>(); for (String stat : split(value)) { List<String> keyValue = split(stat, 0, '='); assertNotNull(format("keyValue should not be null (%s)", stat), keyValue); result.put(unescapeSpecialCharacters(keyValue.get(0)), unescapeSpecialCharacters(keyValue.get(1))); } return result; } private static void waitForFirstStatisticsCollection(final HazelcastClientInstanceImpl client, final ClientEngineImpl clientEngine) { assertTrueEventually(() -> getStats(client, clientEngine)); } private static void waitForNextStatsCollection(final HazelcastClientInstanceImpl client, final ClientEngineImpl clientEngine, final String lastStatisticsCollectionTime) { assertTrueEventually(() -> { Map<String, String> stats = getStats(client, clientEngine); assertNotEquals(lastStatisticsCollectionTime, stats.get("lastStatisticsCollectionTime")); }); } private static void verifyThatCollectionIsPeriodic(Map<String, String> stats, long lastCollectionTime) { String lastStatisticsCollectionTime = stats.get("lastStatisticsCollectionTime"); long newCollectionTime = Long.parseLong(lastStatisticsCollectionTime); long timeDifferenceMillis = newCollectionTime - lastCollectionTime; // it's seen during the tests that the collection time may be much larger (up to 9 seconds), // hence we will keep the upperThreshold a lot higher double lowerThreshold = STATS_PERIOD_MILLIS * 0.9; assertTrue("Time difference between two collections is " + timeDifferenceMillis + " ms but, but it should be greater than " + lowerThreshold + " ms", timeDifferenceMillis >= lowerThreshold); } }
48.447368
135
0.7202
e09038a15c4843c61ecc79159f7133904d0d4074
57,308
package com.ziroom.ziroomcustomer.newmovehouse.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.content.LocalBroadcastManager; import android.text.Editable; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.Window; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.search.core.SearchResult.ERRORNO; import com.baidu.mapapi.search.geocode.GeoCodeOption; import com.baidu.mapapi.search.geocode.GeoCodeResult; import com.baidu.mapapi.search.geocode.GeoCoder; import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener; import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult; import com.baidu.mapapi.search.route.BikingRouteResult; import com.baidu.mapapi.search.route.DrivingRouteLine; import com.baidu.mapapi.search.route.DrivingRoutePlanOption; import com.baidu.mapapi.search.route.DrivingRoutePlanOption.DrivingPolicy; import com.baidu.mapapi.search.route.DrivingRouteResult; import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener; import com.baidu.mapapi.search.route.PlanNode; import com.baidu.mapapi.search.route.RoutePlanSearch; import com.baidu.mapapi.search.route.TransitRouteResult; import com.baidu.mapapi.search.route.WalkingRouteResult; import com.growingio.android.sdk.agent.VdsAgent; import com.growingio.android.sdk.instrumentation.Instrumented; import com.ziroom.commonlibrary.widget.unifiedziroom.d.a; import com.ziroom.commonlibrary.widget.unifiedziroom.d.b; import com.ziroom.ziroomcustomer.base.ApplicationEx; import com.ziroom.ziroomcustomer.base.BaseActivity; import com.ziroom.ziroomcustomer.base.b; import com.ziroom.ziroomcustomer.dialog.g.a; import com.ziroom.ziroomcustomer.e.c.f; import com.ziroom.ziroomcustomer.e.c.m; import com.ziroom.ziroomcustomer.e.n; import com.ziroom.ziroomcustomer.e.o; import com.ziroom.ziroomcustomer.model.Contract; import com.ziroom.ziroomcustomer.model.UserInfo; import com.ziroom.ziroomcustomer.newServiceList.activity.ServiceLoginActivity; import com.ziroom.ziroomcustomer.newServiceList.utils.j; import com.ziroom.ziroomcustomer.newchat.chatcenter.activity.ChatWebViewActivity; import com.ziroom.ziroomcustomer.newclean.d.al; import com.ziroom.ziroomcustomer.newclean.d.ba; import com.ziroom.ziroomcustomer.newmovehouse.model.IsHaveGoingOrderModel; import com.ziroom.ziroomcustomer.newmovehouse.model.MHCapacity; import com.ziroom.ziroomcustomer.newmovehouse.model.MHCommitInfo; import com.ziroom.ziroomcustomer.newmovehouse.model.MHCostEstimateInfo; import com.ziroom.ziroomcustomer.newmovehouse.model.MHCostEstimates; import com.ziroom.ziroomcustomer.newmovehouse.model.MHCreateOrderResult; import com.ziroom.ziroomcustomer.newmovehouse.model.MHFloorsFee; import com.ziroom.ziroomcustomer.newmovehouse.model.MHTool; import com.ziroom.ziroomcustomer.newmovehouse.model.SmallMoveAddressBean; import com.ziroom.ziroomcustomer.newmovehouse.model.SmallMoveGoodSNum; import com.ziroom.ziroomcustomer.newmovehouse.mvp.OrderDetailActivity; import com.ziroom.ziroomcustomer.util.ad; import com.ziroom.ziroomcustomer.util.af; import com.ziroom.ziroomcustomer.util.ah; import com.ziroom.ziroomcustomer.util.u; import com.ziroom.ziroomcustomer.util.w; import com.ziroom.ziroomcustomer.widget.LabeledEditText; import com.ziroom.ziroomcustomer.widget.LabeledEditText.a; import java.io.Serializable; import java.lang.ref.WeakReference; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class RefactorMHMainActivity extends BaseActivity implements View.OnClickListener, OnGetGeoCoderResultListener, OnGetRoutePlanResultListener { private static String B; private ImageView A; private boolean C; private GeoCoder D = null; private int E = 0; private String F; private String G; private String H; private View I; private View J; private View K; private View L; private TextView M; private TextView N; private TextView O; private TextView P; private TextView Q; private TextView R; private RoutePlanSearch S; private boolean T = false; private boolean U = false; private boolean V = false; private boolean W = false; private boolean X = false; private boolean Y = false; private MHCommitInfo Z; private Context a; private long aA = 0L; private boolean aB = false; private boolean aC = false; private BroadcastReceiver aD = new BroadcastReceiver() { public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) { int i = paramAnonymousIntent.getIntExtra("type", 0); if ((i != 17) || (ApplicationEx.c.getUser() == null) || (TextUtils.isEmpty(RefactorMHMainActivity.a(RefactorMHMainActivity.this).getText()))) {} for (;;) { if (i == 7) {} return; paramAnonymousContext = new SimpleDateFormat("yyyy-MM-dd HH:mm"); RefactorMHMainActivity.this.getModeCoupon(paramAnonymousContext.format(Long.valueOf(RefactorMHMainActivity.b(RefactorMHMainActivity.this).getMoveDate()))); } } }; private MHCostEstimateInfo aa; private c ab; private MHCostEstimates ac; private List<MHTool> ad; private a ae; private TextView af; private TextView ag; private TextView ah; private RelativeLayout ai; private TextView aj; private ImageView ak; private ImageView al; private ImageView am; private LabeledEditText an; private LabeledEditText ao; private View ap; private View aq; private View ar; private ImageView as; private int at; private List<MHFloorsFee> au = new ArrayList(); private List<String> av = new ArrayList(); private String aw; private String ax; private SmallMoveAddressBean ay; private SmallMoveAddressBean az; private BaiduMap b; private MapView c; private View d; private TextView e; private TextView f; private LabeledEditText g; private LabeledEditText r; private LabeledEditText s; private LabeledEditText t; private LabeledEditText u; private LabeledEditText v; private LabeledEditText w; private View x; private View y; private Button z; private void a(boolean paramBoolean1, boolean paramBoolean2) { if ((paramBoolean1 == true) && (!paramBoolean2)) { this.an.setVisibility(8); this.ap.setVisibility(8); this.ao.setVisibility(8); this.aq.setVisibility(8); this.ak.setVisibility(4); this.al.setVisibility(0); this.am.setVisibility(8); } for (;;) { this.an.setOnClickListener(new View.OnClickListener() { @Instrumented public void onClick(View paramAnonymousView) { VdsAgent.onClick(this, paramAnonymousView); RefactorMHMainActivity.a(RefactorMHMainActivity.this, 1); } }); this.ao.setOnClickListener(new View.OnClickListener() { @Instrumented public void onClick(View paramAnonymousView) { VdsAgent.onClick(this, paramAnonymousView); RefactorMHMainActivity.a(RefactorMHMainActivity.this, 2); } }); return; if ((!paramBoolean1) && (paramBoolean2 == true)) { this.an.setVisibility(8); this.ap.setVisibility(8); this.ao.setVisibility(8); this.aq.setVisibility(8); this.ak.setVisibility(4); this.al.setVisibility(4); this.am.setVisibility(0); } else { this.an.setVisibility(8); this.ap.setVisibility(8); this.ao.setVisibility(8); this.aq.setVisibility(8); this.ak.setVisibility(0); this.al.setVisibility(0); this.am.setVisibility(8); } } } private void b() { this.aw = getIntent().getStringExtra("recommendCode"); this.ax = getIntent().getStringExtra("channelCode"); this.aB = false; this.aC = false; a(this.aB, this.aC); this.av.clear(); this.ab = new c(this.a); this.Z = new MHCommitInfo(); this.Z.setMoveInElevator(-1); this.Z.setMoveOutElevator(-1); this.Z.setMoveInFloors(-1); this.Z.setMoveOutFloors(-1); this.aa = new MHCostEstimateInfo(); this.ae = new a(null); B = getIntent().getStringExtra("serviceInfoId"); Object localObject1; if ("8a908eb161d66afc0161fa59fd210009".equals(B)) { this.e.setText("自如小搬"); this.Z.setServiceInfoId(B); this.aa.setServiceInfoId(B); this.Z.setCityCode(b.d); this.aa.setCityCode(b.d); this.C = ApplicationEx.c.isLoginState(); this.D = GeoCoder.newInstance(); this.D.setOnGetGeoCodeResultListener(this); if (this.C) { localObject1 = ApplicationEx.c.getUser(); if ((localObject1 != null) && (((UserInfo)localObject1).getLogin_name_mobile() != null)) { this.w.setText(((UserInfo)localObject1).getLogin_name_mobile()); this.w.setSelection(this.w.getText().length()); this.W = true; this.Z.setConnectPhone(((UserInfo)localObject1).getLogin_name_mobile()); i(); } } if (!"8a908eb161d66afc0161fa59fd210009".equals(B)) { break label397; } this.ay = ad.getSmallMoveStartAddressData(this.a, "service_small_move_start_address"); this.az = ad.getSmallMoveStartAddressData(this.a, "service_small_move_end_address"); } for (;;) { if ((this.ay != null) || (this.az != null)) { break label440; } return; if (!"2c9085f248ba3f3a0148bb156f6e0004".equals(B)) { break; } this.e.setText("自如中搬"); break; label397: if ("2c9085f248ba3f3a0148bb156f6e0004".equals(B)) { this.ay = ad.getMiddleMoveStartAddressData(this.a, "service_middle_move_start_address"); this.az = ad.getMiddleMoveStartAddressData(this.a, "service_middle_move_end_address"); } } label440: if (!TextUtils.isEmpty(this.ay.getAddress_location())) { localObject1 = this.ay.getStart_latlng(); this.Z.setStartCoordinate((String)localObject1); this.aa.setOrderStartArea((String)localObject1); } try { localObject1 = new LatLng(Double.parseDouble(this.ay.getLatlng_map_lat()), Double.parseDouble(this.ay.getLatlng_map_lng())); this.ae.d = ((LatLng)localObject1); localObject1 = this.ay.getAddress_location(); localObject2 = this.ay.getAddress_detail(); this.Z.setStartArea((String)localObject1); this.Z.setStartAreaPoint((String)localObject2); this.r.setText((String)localObject1 + (String)localObject2); i = this.ay.getElevator(); j = this.ay.getFloors(); } catch (Exception localException4) { try { d1 = Double.parseDouble(this.ay.getFloorsFee()); this.aa.setMoveOutFloorsFee(d1); this.Z.setMoveOutFloorsFee(d1); this.Z.setMoveOutFloors(j); this.Z.setMoveOutElevator(i); this.X = true; this.U = true; if (this.aB == true) { this.aB = false; a(this.aB, this.aC); } j(); i(); if (!TextUtils.isEmpty(this.az.getAddress_location())) { localObject1 = this.az.getStart_latlng(); this.Z.setEndCoordinate((String)localObject1); this.aa.setOrderEndArea((String)localObject1); } } catch (Exception localException4) { try { localObject1 = new LatLng(Double.parseDouble(this.az.getLatlng_map_lat()), Double.parseDouble(this.az.getLatlng_map_lng())); this.ae.e = ((LatLng)localObject1); localObject1 = this.az.getAddress_location(); localObject2 = this.az.getAddress_detail(); this.Z.setEndArea((String)localObject1); this.Z.setEndAreaPoint((String)localObject2); this.s.setText((String)localObject1 + (String)localObject2); i = this.az.getElevator(); j = this.az.getFloors(); } catch (Exception localException4) { try { int j; double d1 = Double.parseDouble(this.az.getFloorsFee()); this.aa.setMoveInFloorsFee(d1); this.Z.setMoveInFloorsFee(d1); this.Z.setMoveInFloors(j); this.Z.setMoveInElevator(i); this.Y = true; this.V = true; if (this.aC == true) { this.aC = false; a(this.aB, this.aC); } j(); i(); localObject1 = ApplicationEx.c.getContracts(); u.d("sdjgsd", "===== " + com.alibaba.fastjson.a.toJSONString(localObject1)); if (localObject1 != null) { i = 0; if (i >= ((List)localObject1).size()) { break label1417; } if ((TextUtils.isEmpty(((Contract)((List)localObject1).get(i)).getCity_code())) || (!b.d.equals(((Contract)((List)localObject1).get(i)).getCity_code()))) { break label1304; } if (i > -1) { localObject1 = (Contract)((List)localObject1).get(i); localObject2 = ((Contract)localObject1).getEffect_date(); localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (!TextUtils.isEmpty(((Contract)localObject1).getAddress())) { this.F = ""; } } } } catch (Exception localException4) { for (;;) { try { SimpleDateFormat localSimpleDateFormat; Object localObject2 = localSimpleDateFormat.parse((String)localObject2); if (new Date().compareTo(new Date(((Date)localObject2).getTime() + 2592000000L)) <= 0) { if (TextUtils.isEmpty(this.az.getAddress_location())) { this.E = 2; this.D.geocode(new GeoCodeOption().city(b.c).address(((Contract)localObject1).getAddress())); this.aC = true; a(this.aB, this.aC); } this.S = RoutePlanSearch.newInstance(); this.S.setOnGetRoutePlanResultListener(this); if (!TextUtils.isEmpty(this.w.getText().toString())) { w.onEvent(this.a, "movebook_phone"); } i(); e(); localObject1 = new IntentFilter("com.ziroom.commonlibrary.login.broadcast"); LocalBroadcastManager.getInstance(this.a).registerReceiver(this.aD, (IntentFilter)localObject1); return; localException1 = localException1; localException1.printStackTrace(); continue; localException2 = localException2; localException2.printStackTrace(); continue; localException3 = localException3; localException3.printStackTrace(); continue; localException4 = localException4; localException4.printStackTrace(); continue; label1304: i += 1; continue; } if (!TextUtils.isEmpty(this.ay.getAddress_location())) { continue; } this.E = 1; this.D.geocode(new GeoCodeOption().city(b.c).address(localException4.getAddress())); this.aB = true; a(this.aB, this.aC); continue; } catch (ParseException localParseException) { this.E = 2; this.D.geocode(new GeoCodeOption().city(b.c).address(localException4.getAddress())); continue; } label1417: int i = -1; } } } } } } private void b(int paramInt) { this.at = paramInt; if ((this.av != null) && (this.av.size() > 0)) { m(); return; } n.getMHFloorsFeeList(this, B, new com.freelxl.baselibrary.d.c.a(new com.ziroom.ziroomcustomer.e.c.l(MHFloorsFee.class, new com.ziroom.ziroomcustomer.e.c.a.a())) { public void onFailure(Throwable paramAnonymousThrowable) {} public void onSuccess(int paramAnonymousInt, List<MHFloorsFee> paramAnonymousList) { if ((paramAnonymousList != null) && (paramAnonymousList.size() > 0)) { RefactorMHMainActivity.a(RefactorMHMainActivity.this, paramAnonymousList); paramAnonymousInt = 0; while (paramAnonymousInt < RefactorMHMainActivity.t(RefactorMHMainActivity.this).size()) { RefactorMHMainActivity.u(RefactorMHMainActivity.this).add(((MHFloorsFee)RefactorMHMainActivity.t(RefactorMHMainActivity.this).get(paramAnonymousInt)).getFloorsFeeDescribe()); paramAnonymousInt += 1; } RefactorMHMainActivity.v(RefactorMHMainActivity.this); } } }); } private void e() { UserInfo localUserInfo = ApplicationEx.c.getUser(); String str = ""; if (localUserInfo != null) { str = localUserInfo.getUid(); } n.getSmallMoveGoodsNum(this, B, str, new com.freelxl.baselibrary.d.c.a(new m(SmallMoveGoodSNum.class, new com.ziroom.ziroomcustomer.e.c.a.a())) { public void onFailure(Throwable paramAnonymousThrowable) {} public void onSuccess(int paramAnonymousInt, SmallMoveGoodSNum paramAnonymousSmallMoveGoodSNum) { if (paramAnonymousSmallMoveGoodSNum != null) { if (paramAnonymousSmallMoveGoodSNum.getGoodsCount() > 0) { RefactorMHMainActivity.c(RefactorMHMainActivity.this).setVisibility(0); RefactorMHMainActivity.d(RefactorMHMainActivity.this).setVisibility(0); } } else { return; } RefactorMHMainActivity.c(RefactorMHMainActivity.this).setVisibility(8); RefactorMHMainActivity.d(RefactorMHMainActivity.this).setVisibility(8); } }); } private void f() { this.d = findViewById(2131691493); this.e = ((TextView)findViewById(2131689541)); this.g = ((LabeledEditText)findViewById(2131691722)); this.r = ((LabeledEditText)findViewById(2131691727)); this.s = ((LabeledEditText)findViewById(2131691730)); this.t = ((LabeledEditText)findViewById(2131691734)); this.u = ((LabeledEditText)findViewById(2131691735)); this.v = ((LabeledEditText)findViewById(2131691737)); this.w = ((LabeledEditText)findViewById(2131691733)); this.x = findViewById(2131691741); this.f = ((TextView)findViewById(2131691740)); this.y = findViewById(2131691739); this.z = ((Button)findViewById(2131691742)); this.I = findViewById(2131691743); this.M = ((TextView)findViewById(2131691744)); this.N = ((TextView)findViewById(2131691746)); this.O = ((TextView)findViewById(2131691751)); this.P = ((TextView)findViewById(2131691753)); this.Q = ((TextView)findViewById(2131689994)); this.R = ((TextView)findViewById(2131689996)); this.J = findViewById(2131691750); this.K = findViewById(2131691752); this.L = findViewById(2131691754); this.af = ((TextView)findViewById(2131691749)); this.aj = ((TextView)findViewById(2131691756)); this.ak = ((ImageView)findViewById(2131691723)); this.al = ((ImageView)findViewById(2131691725)); this.am = ((ImageView)findViewById(2131691726)); this.an = ((LabeledEditText)findViewById(2131691728)); this.ap = findViewById(2131691729); this.ao = ((LabeledEditText)findViewById(2131691732)); this.aq = findViewById(2131691731); this.ar = findViewById(2131691736); this.ag = ((TextView)findViewById(2131691745)); this.ai = ((RelativeLayout)findViewById(2131691747)); this.ah = ((TextView)findViewById(2131691748)); this.A = ((ImageView)findViewById(2131690588)); this.as = ((ImageView)findViewById(2131690023)); this.c = ((MapView)findViewById(2131690823)); this.b = this.c.getMap(); this.c.showScaleControl(false); this.c.showZoomControls(false); this.c.removeViewAt(1); this.c.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { int i = RefactorMHMainActivity.e(RefactorMHMainActivity.this).getWidth(); ViewGroup.LayoutParams localLayoutParams = RefactorMHMainActivity.e(RefactorMHMainActivity.this).getLayoutParams(); localLayoutParams.height = (i / 2); RefactorMHMainActivity.e(RefactorMHMainActivity.this).setLayoutParams(localLayoutParams); } }); } private void g() { this.d.setOnClickListener(this); this.g.setOnClickListener(this); this.r.setOnClickListener(this); this.s.setOnClickListener(this); this.t.setOnClickListener(this); this.u.setOnClickListener(this); this.v.setOnClickListener(this); this.y.setOnClickListener(this); this.z.setOnClickListener(this); this.I.setOnClickListener(this); this.A.setOnClickListener(this); this.as.setOnClickListener(this); this.w.addTextChangedListener(new LabeledEditText.a() { public void afterTextChanged(Editable paramAnonymousEditable) { if (paramAnonymousEditable.length() > 11) { RefactorMHMainActivity.f(RefactorMHMainActivity.this).setText(paramAnonymousEditable.toString().substring(0, 11)); RefactorMHMainActivity.f(RefactorMHMainActivity.this).setSelection(RefactorMHMainActivity.f(RefactorMHMainActivity.this).getText().length()); } } public void beforeTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {} public void onTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) { if (paramAnonymousCharSequence.length() == 11) { RefactorMHMainActivity.a(RefactorMHMainActivity.this, true); RefactorMHMainActivity.b(RefactorMHMainActivity.this).setConnectPhone(paramAnonymousCharSequence.toString()); } for (;;) { RefactorMHMainActivity.g(RefactorMHMainActivity.this); return; RefactorMHMainActivity.a(RefactorMHMainActivity.this, false); } } }); } private void h() { if (checkNet(this.a)) { Intent localIntent = new Intent(this.a, MHServiceTimeActivity.class); localIntent.putExtra("serviceTypeCode", B); localIntent.putExtra("moveTime", this.Z.getMoveDateTime()); localIntent.putExtra("selectDate", this.aA); startActivityForResult(localIntent, 3846); return; } com.freelxl.baselibrary.f.g.textToast(this, "请求失败,请检查网络连接"); } private void i() { if ((this.U) && (this.V) && (this.T) && (this.W)) { this.z.setOnClickListener(this); this.z.setBackgroundColor(Color.parseColor("#ffa000")); } for (;;) { this.f.setText((int)this.ae.c + ""); if ((!this.U) || (!this.V) || (!this.T)) { break; } this.y.setOnClickListener(this); this.x.setVisibility(0); return; this.z.setOnClickListener(new View.OnClickListener() { @Instrumented public void onClick(View paramAnonymousView) { VdsAgent.onClick(this, paramAnonymousView); if (!RefactorMHMainActivity.l(RefactorMHMainActivity.this)) { com.freelxl.baselibrary.f.g.textToast(RefactorMHMainActivity.m(RefactorMHMainActivity.this), "请选择服务时间!"); } do { return; if (!RefactorMHMainActivity.n(RefactorMHMainActivity.this)) { com.freelxl.baselibrary.f.g.textToast(RefactorMHMainActivity.m(RefactorMHMainActivity.this), "请选择搬家起点地址!"); return; } if (!RefactorMHMainActivity.o(RefactorMHMainActivity.this)) { com.freelxl.baselibrary.f.g.textToast(RefactorMHMainActivity.m(RefactorMHMainActivity.this), "请选择搬家终点地址!"); return; } } while (RefactorMHMainActivity.p(RefactorMHMainActivity.this)); com.freelxl.baselibrary.f.g.textToast(RefactorMHMainActivity.m(RefactorMHMainActivity.this), "请输入联系电话!"); } }); this.z.setBackgroundColor(Color.parseColor("#d1d1d1")); } this.y.setOnClickListener(new View.OnClickListener() { @Instrumented public void onClick(View paramAnonymousView) { VdsAgent.onClick(this, paramAnonymousView); if (!RefactorMHMainActivity.l(RefactorMHMainActivity.this)) { com.freelxl.baselibrary.f.g.textToast(RefactorMHMainActivity.m(RefactorMHMainActivity.this), "请选择服务时间!"); } do { return; if (!RefactorMHMainActivity.n(RefactorMHMainActivity.this)) { com.freelxl.baselibrary.f.g.textToast(RefactorMHMainActivity.m(RefactorMHMainActivity.this), "请选择搬家起点地址!"); return; } } while (RefactorMHMainActivity.o(RefactorMHMainActivity.this)); com.freelxl.baselibrary.f.g.textToast(RefactorMHMainActivity.m(RefactorMHMainActivity.this), "请选择搬家终点地址!"); } }); this.x.setVisibility(8); } private void j() { if ((this.T) && (this.U) && (this.V)) { this.b.clear(); PlanNode localPlanNode1 = PlanNode.withLocation(this.ae.d); PlanNode localPlanNode2 = PlanNode.withLocation(this.ae.e); if ((this.S != null) && (!isFinishing())) { this.S.drivingSearch(new DrivingRoutePlanOption().policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_DIS_FIRST).from(localPlanNode1).to(localPlanNode2)); } } } private void k() { if (this.ac != null) { l(); this.I.setVisibility(0); return; } af.showToast(this.a, "正在获取费用估计,请稍后"); } private void l() { if (this.ac.getMoveFloorsFee() > 0) { this.J.setVisibility(0); this.O.setText(this.ac.getMoveFloorsFee() + " 元"); if (this.ac.getGoodsPrice() <= 0) { break label442; } this.K.setVisibility(0); this.P.setText(this.ac.getGoodsPrice() + " 元"); label102: if (this.ac.getPromoPrice() <= 0) { break label454; } this.L.setVisibility(0); this.Q.setText("-" + this.ac.getPromoPrice() + " 元"); label159: this.M.setText((int)this.aa.getDistance() + " 公里"); this.R.setText(this.ac.getTotalPrice() + " "); this.ag.setText("基础价格(含" + this.ac.getDefaultDistance() + "公里)"); this.N.setText((int)this.ac.getDefaultPrice() + " 元"); if (this.ac.getOverstepDistance() <= 0) { break label466; } this.ai.setVisibility(0); this.ah.setText("超出里程费(" + this.ac.getOverstepDistance() + "公里)"); this.af.setText((int)this.ac.getOverstepPrice() + "元"); } for (;;) { this.aj.setText("预估里程根据以下路线进行计算(共计" + this.ac.getDistance() + "公里)"); return; this.J.setVisibility(8); break; label442: this.K.setVisibility(8); break label102; label454: this.L.setVisibility(8); break label159; label466: this.ai.setVisibility(8); } } private void m() { com.ziroom.ziroomcustomer.dialog.g localg = new com.ziroom.ziroomcustomer.dialog.g(this, new b(), this.av, null); localg.setCanceledOnTouchOutside(true); Window localWindow = localg.getWindow(); localWindow.getDecorView().setPadding(0, 0, 0, 0); WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes(); localLayoutParams.width = -1; localLayoutParams.height = -2; localWindow.setAttributes(localLayoutParams); localWindow.getDecorView().setBackgroundColor(-1); localWindow.setGravity(80); localg.show(); localg.getTv_choose().setText("请选择楼层"); } private void n() { this.C = ApplicationEx.c.isLoginState(); if (this.C) { if (ApplicationEx.c.getUser() == null) {} for (String str = "";; str = ApplicationEx.c.getUser().getUid()) { n.requestIsHaveGoingOrder(this, str, new com.ziroom.ziroomcustomer.e.a.d(this, new f(IsHaveGoingOrderModel.class)) { public void onFailure(Throwable paramAnonymousThrowable) { super.onFailure(paramAnonymousThrowable); RefactorMHMainActivity.z(RefactorMHMainActivity.this); } public void onSuccess(int paramAnonymousInt, final IsHaveGoingOrderModel paramAnonymousIsHaveGoingOrderModel) { super.onSuccess(paramAnonymousInt, paramAnonymousIsHaveGoingOrderModel); if ((paramAnonymousIsHaveGoingOrderModel == null) || ("0".equals(paramAnonymousIsHaveGoingOrderModel.isHave))) { RefactorMHMainActivity.z(RefactorMHMainActivity.this); return; } com.ziroom.commonlibrary.widget.unifiedziroom.d.newBuilder(RefactorMHMainActivity.this).setContent(paramAnonymousIsHaveGoingOrderModel.content).setTitle("提示").setButtonText("查看订单", "继续下单").setOnConfirmClickListener(new d.b() { public void onLeftClick(View paramAnonymous2View) { paramAnonymous2View = new Intent(RefactorMHMainActivity.this, OrderDetailActivity.class); paramAnonymous2View.putExtra("orderId", paramAnonymousIsHaveGoingOrderModel.logicCode); if ("8a908eb161d66afc0161fa59fd210009".equals(paramAnonymousIsHaveGoingOrderModel.productCode)) { paramAnonymous2View.putExtra("moveOrderType", "move_xiaomian"); } for (;;) { RefactorMHMainActivity.this.startActivity(paramAnonymous2View); return; if ("2c9085f248ba3f3a0148bb156f6e0004".equals(paramAnonymousIsHaveGoingOrderModel.productCode)) { paramAnonymous2View.putExtra("moveOrderType", "move_small"); } else if ("8a90a5f8593e65b501593e65b5200000".equals(paramAnonymousIsHaveGoingOrderModel.productCode)) { paramAnonymous2View.putExtra("moveOrderType", "move_van"); } } } public void onRightClick(View paramAnonymous2View) { RefactorMHMainActivity.z(RefactorMHMainActivity.this); } }).show(); } }); return; } } startActivity(new Intent(this.a, ServiceLoginActivity.class)); } private void o() { this.C = ApplicationEx.c.isLoginState(); if (this.C) { int i = this.Z.getConnectPhone().charAt(0); int j = this.Z.getConnectPhone().charAt(1); if ((i != 49) || (j == 48) || (j == 49) || (j == 50)) { com.freelxl.baselibrary.f.g.textToast(this, "手机号非法,请重新输入"); } do { return; if ((this.aB == true) && (TextUtils.isEmpty(this.an.getText()))) { com.freelxl.baselibrary.f.g.textToast(getApplicationContext(), "请先选择楼层"); return; } if ((this.aC == true) && (TextUtils.isEmpty(this.ao.getText()))) { com.freelxl.baselibrary.f.g.textToast(getApplicationContext(), "请先选择楼层"); return; } } while (this.Z == null); this.Z.setUuid(ApplicationEx.c.getUser().getUid()); showProgress(""); if (TextUtils.isEmpty(this.ax)) { this.ax = ""; } if (TextUtils.isEmpty(this.aw)) { this.aw = ""; } String str = ah.getVersion(this.a); o.MHCreateOrder(this.a, this.ab, this.Z, this.ax, this.aw, str); w.onEvent(this.a, "movesubmit_submit"); return; } startActivity(new Intent(this.a, ServiceLoginActivity.class)); } public void getModeCoupon(String paramString) { UserInfo localUserInfo = ApplicationEx.c.getUser(); if (localUserInfo != null) { n.getMateCoupon(this.a, 1, "", B, B, paramString, localUserInfo.getUid(), new com.freelxl.baselibrary.d.c.a(new m(ba.class, new com.ziroom.ziroomcustomer.e.c.a.a())) { public void onFailure(Throwable paramAnonymousThrowable) {} public void onSuccess(int paramAnonymousInt, ba paramAnonymousba) { if (paramAnonymousba != null) { String str = paramAnonymousba.getPromoId(); RefactorMHMainActivity.h(RefactorMHMainActivity.this).setPromoCodeId(str); RefactorMHMainActivity.b(RefactorMHMainActivity.this).setPromoCodeId(str); RefactorMHMainActivity.i(RefactorMHMainActivity.this).b = ((float)paramAnonymousba.getPromoPrice()); RefactorMHMainActivity.j(RefactorMHMainActivity.this).setText("优惠" + (int)RefactorMHMainActivity.i(RefactorMHMainActivity.this).b + "元"); RefactorMHMainActivity.k(RefactorMHMainActivity.this); RefactorMHMainActivity.g(RefactorMHMainActivity.this); return; } RefactorMHMainActivity.h(RefactorMHMainActivity.this).setPromoCodeId(""); RefactorMHMainActivity.b(RefactorMHMainActivity.this).setPromoCodeId(""); RefactorMHMainActivity.j(RefactorMHMainActivity.this).setText(""); RefactorMHMainActivity.k(RefactorMHMainActivity.this); RefactorMHMainActivity.g(RefactorMHMainActivity.this); } }); } } protected void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent) { super.onActivityResult(paramInt1, paramInt2, paramIntent); if (paramInt2 == 1111) { switch (paramInt1) { } } for (;;) { if (paramInt2 == -1) {} switch (paramInt1) { default: return; this.aa.setPromoCodeId(""); this.Z.setPromoCodeId(""); this.ae.b = 0.0F; this.t.setText(""); j(); i(); } } this.ae.a = paramIntent.getExtras().getFloat("totalPrice"); this.ad = ((List)paramIntent.getExtras().getSerializable("shoppingCart")); paramIntent = new StringBuilder(); if ((this.ad != null) && (this.ad.size() > 0)) { localObject1 = new StringBuilder(); paramInt1 = 0; while (paramInt1 < this.ad.size()) { ((StringBuilder)localObject1).append(((MHTool)this.ad.get(paramInt1)).getGoodsId()).append(":").append(((MHTool)this.ad.get(paramInt1)).getNum()); paramIntent.append(((MHTool)this.ad.get(paramInt1)).getName()).append("×").append(((MHTool)this.ad.get(paramInt1)).getNum()); if (paramInt1 != this.ad.size() - 1) { ((StringBuilder)localObject1).append(","); paramIntent.append(" "); } paramInt1 += 1; } this.Z.setChooseGoods(((StringBuilder)localObject1).toString()); this.aa.setChooseGoods(((StringBuilder)localObject1).toString()); } for (;;) { this.u.setText(paramIntent.toString()); j(); i(); return; this.Z.setChooseGoods(""); this.aa.setChooseGoods(""); } paramIntent = (al)paramIntent.getExtras().getSerializable("couponItem"); Object localObject1 = paramIntent.getPromoId(); this.aa.setPromoCodeId((String)localObject1); this.Z.setPromoCodeId((String)localObject1); this.ae.b = paramIntent.getPromoPrice(); this.t.setText("优惠" + (int)this.ae.b + "元"); j(); i(); return; localObject1 = paramIntent.getExtras().getString("NeedTagId", ""); this.Z.setCharacterIds((String)localObject1); localObject1 = paramIntent.getExtras().getString("Remark", ""); this.Z.setRemark((String)localObject1); this.H = paramIntent.getExtras().getString("TagStr", ""); paramIntent = new StringBuilder(); if (!TextUtils.isEmpty(this.H)) { localObject2 = this.H.split(","); paramInt1 = 0; while (paramInt1 < localObject2.length) { paramIntent.append(localObject2[paramInt1]).append(" "); paramInt1 += 1; } } paramIntent.append((String)localObject1); this.v.setText(paramIntent.toString()); return; localObject1 = paramIntent.getExtras().getString("latlng_str", "0.0 - 0.0"); this.Z.setStartCoordinate((String)localObject1); this.aa.setOrderStartArea((String)localObject1); Object localObject2 = new LatLng(paramIntent.getExtras().getDouble("latlng_map_lat", 0.0D), paramIntent.getExtras().getDouble("latlng_map_lng", 0.0D)); this.ae.d = ((LatLng)localObject2); localObject2 = paramIntent.getExtras().getString("address_location", ""); String str = paramIntent.getExtras().getString("address_detail", ""); this.Z.setStartArea((String)localObject2); this.Z.setStartAreaPoint(str); this.r.setText((String)localObject2 + str); if ("8a908eb161d66afc0161fa59fd210009".equals(B)) { ad.saveSmallMoveStartAddressData(this.a, (String)localObject1, paramIntent.getExtras().getDouble("latlng_map_lat", 0.0D), paramIntent.getExtras().getDouble("latlng_map_lng", 0.0D), (String)localObject2, str, paramIntent.getExtras().getInt("elevator", 0), paramIntent.getExtras().getInt("floors", 0), paramIntent.getExtras().getDouble("floorsFee", 0.0D)); } double d1; for (;;) { paramInt1 = paramIntent.getExtras().getInt("elevator", 0); paramInt2 = paramIntent.getExtras().getInt("floors", 0); d1 = paramIntent.getExtras().getDouble("floorsFee", 0.0D); this.aa.setMoveOutFloorsFee(d1); this.Z.setMoveOutFloorsFee(d1); this.Z.setMoveOutFloors(paramInt2); this.Z.setMoveOutElevator(paramInt1); this.X = true; this.U = true; if (this.aB == true) { this.aB = false; a(this.aB, this.aC); } j(); i(); return; if ("2c9085f248ba3f3a0148bb156f6e0004".equals(B)) { ad.saveMiddleMoveStartAddressData(this.a, (String)localObject1, paramIntent.getExtras().getDouble("latlng_map_lat", 0.0D), paramIntent.getExtras().getDouble("latlng_map_lng", 0.0D), (String)localObject2, str, paramIntent.getExtras().getInt("elevator", 0), paramIntent.getExtras().getInt("floors", 0), paramIntent.getExtras().getDouble("floorsFee", 0.0D)); } } localObject1 = paramIntent.getExtras().getString("latlng_str", "0.0 - 0.0"); this.Z.setEndCoordinate((String)localObject1); this.aa.setOrderEndArea((String)localObject1); localObject2 = new LatLng(paramIntent.getExtras().getDouble("latlng_map_lat", 0.0D), paramIntent.getExtras().getDouble("latlng_map_lng", 0.0D)); this.ae.e = ((LatLng)localObject2); localObject2 = paramIntent.getExtras().getString("address_location", ""); str = paramIntent.getExtras().getString("address_detail", ""); this.Z.setEndArea((String)localObject2); this.Z.setEndAreaPoint(str); this.s.setText((String)localObject2 + str); if ("8a908eb161d66afc0161fa59fd210009".equals(B)) { ad.saveSmallMoveEndAddressData(this.a, (String)localObject1, paramIntent.getExtras().getDouble("latlng_map_lat", 0.0D), paramIntent.getExtras().getDouble("latlng_map_lng", 0.0D), (String)localObject2, str, paramIntent.getExtras().getInt("elevator", 0), paramIntent.getExtras().getInt("floors", 0), paramIntent.getExtras().getDouble("floorsFee", 0.0D)); } for (;;) { paramInt1 = paramIntent.getExtras().getInt("elevator", 0); paramInt2 = paramIntent.getExtras().getInt("floors", 0); d1 = paramIntent.getExtras().getDouble("floorsFee", 0.0D); this.aa.setMoveInFloorsFee(d1); this.Z.setMoveInFloorsFee(d1); this.Z.setMoveInFloors(paramInt2); this.Z.setMoveInElevator(paramInt1); this.Y = true; this.V = true; if (this.aC == true) { this.aC = false; a(this.aB, this.aC); } j(); i(); return; if ("2c9085f248ba3f3a0148bb156f6e0004".equals(B)) { ad.saveMidleMoveEndAddressData(this.a, (String)localObject1, paramIntent.getExtras().getDouble("latlng_map_lat", 0.0D), paramIntent.getExtras().getDouble("latlng_map_lng", 0.0D), (String)localObject2, str, paramIntent.getExtras().getInt("elevator", 0), paramIntent.getExtras().getInt("floors", 0), paramIntent.getExtras().getDouble("floorsFee", 0.0D)); } } long l = paramIntent.getExtras().getLong("moveTime"); this.aA = paramIntent.getExtras().getLong("selectDate"); this.Z.setMoveDate(l); this.Z.setMoveDateTime(l); this.aa.setMoveDate(l); if ((l == 0L) || (this.aA == 0L)) { this.T = false; this.g.setText(""); } for (;;) { j(); i(); getModeCoupon(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Long.valueOf(l))); return; this.T = true; paramIntent = new SimpleDateFormat("MM月dd日(E) HH:mm"); this.g.setText(paramIntent.format(Long.valueOf(l))); } } public void onBackPressed() { if (this.I != null) { if (this.I.getVisibility() == 0) { this.I.setVisibility(8); return; } j.setFinishDialog(this); return; } super.onBackPressed(); } @Instrumented public void onClick(View paramView) { VdsAgent.onClick(this, paramView); if (paramView != null) {} switch (paramView.getId()) { case 2131691743: default: return; case 2131691493: j.setFinishDialog(this); return; case 2131691722: h(); w.onEvent(this.a, "movebook_time"); return; case 2131691727: paramView = new Intent(this.a, MHEnterAddressActivity.class); paramView.putExtra("type", "start"); paramView.putExtra("serviceInfoId", B); paramView.putExtra("isStartFloor", this.aB); if ((!TextUtils.isEmpty(this.r.getText())) && (this.X)) { paramView.putExtra("latlng_str", this.Z.getStartCoordinate()); paramView.putExtra("latlng_map_lat", this.ae.d.latitude); paramView.putExtra("latlng_map_lng", this.ae.d.longitude); paramView.putExtra("address_location", this.Z.getStartArea()); paramView.putExtra("address_detail", this.Z.getStartAreaPoint()); paramView.putExtra("elevator", this.Z.getMoveOutElevator()); paramView.putExtra("floorsFee", this.Z.getMoveOutFloorsFee()); paramView.putExtra("floors", this.Z.getMoveOutFloors()); } startActivityForResult(paramView, 3844); return; case 2131691730: paramView = new Intent(this.a, MHEnterAddressActivity.class); paramView.putExtra("type", "end"); paramView.putExtra("serviceInfoId", B); if ((!TextUtils.isEmpty(this.s.getText())) && (this.Y)) { paramView.putExtra("latlng_str", this.Z.getEndCoordinate()); paramView.putExtra("latlng_map_lat", this.ae.e.latitude); paramView.putExtra("latlng_map_lng", this.ae.e.longitude); paramView.putExtra("address_location", this.Z.getEndArea()); paramView.putExtra("address_detail", this.Z.getEndAreaPoint()); paramView.putExtra("elevator", this.Z.getMoveInElevator()); paramView.putExtra("floorsFee", this.Z.getMoveInFloorsFee()); paramView.putExtra("floors", this.Z.getMoveInFloors()); } startActivityForResult(paramView, 3845); return; case 2131691734: this.C = ApplicationEx.c.isLoginState(); if (this.C) { if (TextUtils.isEmpty(this.g.getText())) { com.freelxl.baselibrary.f.g.textToast(this, "请先选择服务时间"); return; } paramView = new Intent(this.a, MHPrivilegeActivity.class); paramView.putExtra("serviceInfoId", B); SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); paramView.putExtra("startTime", localSimpleDateFormat.format(Long.valueOf(this.Z.getMoveDate()))); u.d(":jsdkjgkldjgklkg", "======= " + localSimpleDateFormat.format(Long.valueOf(this.Z.getMoveDate())) + " " + this.Z.getMoveDate()); startActivityForResult(paramView, 3843); } for (;;) { w.onEvent(this.a, "movebook_coupon"); return; com.ziroom.commonlibrary.login.a.startLoginActivity(this.a); } case 2131691735: paramView = new Intent(this.a, MHChangeToolActivity.class); paramView.putExtra("serviceInfoId", B); if (this.ad != null) { paramView.putExtra("shoppingCart", (Serializable)this.ad); } startActivityForResult(paramView, 3841); return; case 2131691737: paramView = new Intent(this, SmallMoveSpecialActivity.class); paramView.putExtra("cityCode", b.d); paramView.putExtra("lastInput", this.Z.getRemark()); paramView.putExtra("lastTag", this.H); paramView.putExtra("serviceInfoId", B); startActivityForResult(paramView, 3842); w.onEvent(this.a, "movebook_requirements"); return; case 2131691739: k(); return; case 2131691742: n(); return; case 2131690588: this.I.setVisibility(8); return; } startActivity(new Intent(this, ChatWebViewActivity.class)); } protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(2130903347); getWindow().setSoftInputMode(32); this.a = this; f(); g(); b(); w.onEventToZiroomAndUmeng("move_appointment_uv"); } protected void onDestroy() { if (this.D != null) { this.D.destroy(); } if (this.c != null) { this.c.onDestroy(); } if (this.b != null) { this.b.clear(); } if (this.S != null) { this.S.destroy(); } super.onDestroy(); } public void onGetBikingRouteResult(BikingRouteResult paramBikingRouteResult) {} public void onGetDrivingRouteResult(DrivingRouteResult paramDrivingRouteResult) { if ((paramDrivingRouteResult == null) || (paramDrivingRouteResult.error != SearchResult.ERRORNO.NO_ERROR)) { localObject = Toast.makeText(this.a, "抱歉,未找到结果", 0); if (!(localObject instanceof Toast)) { ((Toast)localObject).show(); } } else { if (paramDrivingRouteResult.error != SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) { break label58; } } label58: while (paramDrivingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) { return; VdsAgent.showToast((Toast)localObject); break; } Object localObject = new d(this.b); this.b.setOnMarkerClickListener((BaiduMap.OnMarkerClickListener)localObject); paramDrivingRouteResult = (DrivingRouteLine)paramDrivingRouteResult.getRouteLines().get(0); ((com.ziroom.ziroomcustomer.util.b.a)localObject).setData(paramDrivingRouteResult); ((com.ziroom.ziroomcustomer.util.b.a)localObject).addToMap(); ((com.ziroom.ziroomcustomer.util.b.a)localObject).zoomToSpan(); int i = paramDrivingRouteResult.getDistance() / 1000; this.Z.setDistance(i); this.aa.setDistance(i); o.MHCostEstimates(this.a, this.ab, this.aa.getChooseGoods(), b.d, this.aa.getDistance(), this.aa.getMoveDate(), this.Z.getStartArea(), this.Z.getEndArea(), this.aa.getPromoCodeId(), this.aa.getServiceInfoId(), System.currentTimeMillis(), this.aa.getMoveOutFloorsFee(), this.aa.getMoveInFloorsFee(), this.ae.d.latitude, this.ae.d.longitude, this.ae.e.latitude, this.ae.e.longitude); } public void onGetGeoCodeResult(GeoCodeResult paramGeoCodeResult) { if (((!this.X) && (this.E == 1)) || ((this.Y) || (this.E != 2) || (paramGeoCodeResult == null) || (paramGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR))) { return; } if (this.E == 1) { this.r.setText(this.F); this.Z.setStartCoordinate(paramGeoCodeResult.getLocation().latitude + "-" + paramGeoCodeResult.getLocation().longitude); this.Z.setStartArea(this.F); this.aa.setOrderStartArea(paramGeoCodeResult.getLocation().latitude + "-" + paramGeoCodeResult.getLocation().longitude); this.ae.d = paramGeoCodeResult.getLocation(); this.U = true; } for (;;) { i(); return; if (this.E == 2) { this.s.setText(this.F); this.Z.setEndCoordinate(paramGeoCodeResult.getLocation().latitude + "-" + paramGeoCodeResult.getLocation().longitude); this.Z.setEndArea(this.F); this.aa.setOrderEndArea(paramGeoCodeResult.getLocation().latitude + "-" + paramGeoCodeResult.getLocation().longitude); this.ae.e = paramGeoCodeResult.getLocation(); this.V = true; } } } public void onGetReverseGeoCodeResult(ReverseGeoCodeResult paramReverseGeoCodeResult) {} public void onGetTransitRouteResult(TransitRouteResult paramTransitRouteResult) {} public void onGetWalkingRouteResult(WalkingRouteResult paramWalkingRouteResult) {} protected void onPause() { super.onPause(); this.c.onPause(); } protected void onResume() { this.c.onResume(); super.onResume(); this.w.disposeFocus(this.e); } private class a { float a; float b; float c; LatLng d; LatLng e; private a() {} } class b implements g.a { b() {} public void showHour(String paramString, int paramInt) { if (RefactorMHMainActivity.w(RefactorMHMainActivity.this) == 1) { RefactorMHMainActivity.x(RefactorMHMainActivity.this).setText((String)RefactorMHMainActivity.u(RefactorMHMainActivity.this).get(paramInt)); RefactorMHMainActivity.b(RefactorMHMainActivity.this).setMoveOutElevator(((MHFloorsFee)RefactorMHMainActivity.t(RefactorMHMainActivity.this).get(paramInt)).getElevator()); RefactorMHMainActivity.b(RefactorMHMainActivity.this).setMoveOutFloors(((MHFloorsFee)RefactorMHMainActivity.t(RefactorMHMainActivity.this).get(paramInt)).getFloors()); RefactorMHMainActivity.b(RefactorMHMainActivity.this).setMoveOutFloorsFee(((MHFloorsFee)RefactorMHMainActivity.t(RefactorMHMainActivity.this).get(paramInt)).getFloorsFee()); RefactorMHMainActivity.h(RefactorMHMainActivity.this).setMoveOutFloorsFee(((MHFloorsFee)RefactorMHMainActivity.t(RefactorMHMainActivity.this).get(paramInt)).getFloorsFee()); } for (;;) { RefactorMHMainActivity.k(RefactorMHMainActivity.this); return; if (RefactorMHMainActivity.w(RefactorMHMainActivity.this) == 2) { RefactorMHMainActivity.b(RefactorMHMainActivity.this).setMoveInElevator(((MHFloorsFee)RefactorMHMainActivity.t(RefactorMHMainActivity.this).get(paramInt)).getElevator()); RefactorMHMainActivity.b(RefactorMHMainActivity.this).setMoveInFloors(((MHFloorsFee)RefactorMHMainActivity.t(RefactorMHMainActivity.this).get(paramInt)).getFloors()); RefactorMHMainActivity.b(RefactorMHMainActivity.this).setMoveInFloorsFee(((MHFloorsFee)RefactorMHMainActivity.t(RefactorMHMainActivity.this).get(paramInt)).getFloorsFee()); RefactorMHMainActivity.h(RefactorMHMainActivity.this).setMoveInFloorsFee(((MHFloorsFee)RefactorMHMainActivity.t(RefactorMHMainActivity.this).get(paramInt)).getFloorsFee()); RefactorMHMainActivity.y(RefactorMHMainActivity.this).setText((String)RefactorMHMainActivity.u(RefactorMHMainActivity.this).get(paramInt)); } } } } private static class c extends Handler { private WeakReference<Context> a; public c(Context paramContext) { this.a = new WeakReference(paramContext); } public void handleMessage(Message paramMessage) { RefactorMHMainActivity localRefactorMHMainActivity = (RefactorMHMainActivity)this.a.get(); Object localObject; if (localRefactorMHMainActivity != null) { localObject = (com.ziroom.ziroomcustomer.e.l)paramMessage.obj; switch (paramMessage.what) { } } for (;;) { localRefactorMHMainActivity.dismissProgress(); return; if (((com.ziroom.ziroomcustomer.e.l)localObject).getSuccess().booleanValue()) { RefactorMHMainActivity.a(localRefactorMHMainActivity, (MHCostEstimates)((com.ziroom.ziroomcustomer.e.l)localObject).getObject()); RefactorMHMainActivity.i(localRefactorMHMainActivity).c = RefactorMHMainActivity.q(localRefactorMHMainActivity).getTotalPrice(); RefactorMHMainActivity.r(localRefactorMHMainActivity); RefactorMHMainActivity.g(localRefactorMHMainActivity); } else { localRefactorMHMainActivity.showToast(((com.ziroom.ziroomcustomer.e.l)localObject).getMessage()); continue; localRefactorMHMainActivity.dismissProgress(); if (((com.ziroom.ziroomcustomer.e.l)localObject).getSuccess().booleanValue()) { paramMessage = (MHCreateOrderResult)((com.ziroom.ziroomcustomer.e.l)localObject).getObject(); if (paramMessage != null) { localObject = new Intent(localRefactorMHMainActivity, MovingVanSuccessActivity.class); if (!"8a908eb161d66afc0161fa59fd210009".equals(RefactorMHMainActivity.a())) { break label208; } ((Intent)localObject).putExtra("move_from", "move_xiaomian"); } for (;;) { ((Intent)localObject).putExtra("orderId", paramMessage.getWorkOrderId()); localRefactorMHMainActivity.startActivity((Intent)localObject); localRefactorMHMainActivity.finish(); break; label208: if ("2c9085f248ba3f3a0148bb156f6e0004".equals(RefactorMHMainActivity.a())) { ((Intent)localObject).putExtra("move_from", "small_move"); } } } com.freelxl.baselibrary.f.g.textToast(localRefactorMHMainActivity, ((com.ziroom.ziroomcustomer.e.l)localObject).getMessage()); continue; if (((com.ziroom.ziroomcustomer.e.l)localObject).getSuccess().booleanValue()) { paramMessage = (MHCapacity)((com.ziroom.ziroomcustomer.e.l)localObject).getObject(); if (paramMessage != null) { if (paramMessage.getSpareCapacityNum() > 0) { RefactorMHMainActivity.a(localRefactorMHMainActivity).setText(RefactorMHMainActivity.s(localRefactorMHMainActivity)); RefactorMHMainActivity.b(localRefactorMHMainActivity, true); RefactorMHMainActivity.k(localRefactorMHMainActivity); RefactorMHMainActivity.g(localRefactorMHMainActivity); } else { RefactorMHMainActivity.a(localRefactorMHMainActivity).setText(""); RefactorMHMainActivity.b(localRefactorMHMainActivity, false); RefactorMHMainActivity.g(localRefactorMHMainActivity); if (paramMessage.getRemark() != null) { localRefactorMHMainActivity.showToast(paramMessage.getRemark()); } else { localRefactorMHMainActivity.showToast("该时间段已约满,请选择其他时段!"); } } } } else { localRefactorMHMainActivity.showToast(((com.ziroom.ziroomcustomer.e.l)localObject).getMessage()); } } } } } private class d extends com.ziroom.ziroomcustomer.util.b.a { public d(BaiduMap paramBaiduMap) { super(); } public BitmapDescriptor getStartMarker() { return BitmapDescriptorFactory.fromResource(2130838844); } public BitmapDescriptor getTerminalMarker() { return BitmapDescriptorFactory.fromResource(2130838784); } } } /* Location: /Users/gaoht/Downloads/zirom/classes3-dex2jar.jar!/com/ziroom/ziroomcustomer/newmovehouse/activity/RefactorMHMainActivity.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
38.281897
385
0.649473
38d20c6b5de6c0d97486dc4558b2ee9717f26dd1
3,119
package us.ihmc.commonWalkingControlModules.controlModules.foot.partialFoothold; import us.ihmc.mecano.frames.MovingReferenceFrame; import us.ihmc.mecano.spatial.interfaces.TwistReadOnly; import us.ihmc.robotics.math.filters.AlphaFilteredYoVariable; import us.ihmc.robotics.robotSide.RobotSide; import us.ihmc.yoVariables.providers.DoubleProvider; import us.ihmc.yoVariables.registry.YoRegistry; import us.ihmc.yoVariables.variable.YoBoolean; import us.ihmc.yoVariables.variable.YoDouble; /** * This class aims at detecting whether or not the foot is rotating. It uses that by integrating up the angular velocity of the foot in order to compute * the total angle of rotation. */ public class VelocityFootRotationDetector implements FootRotationDetector { private final double dt; private final MovingReferenceFrame soleFrame; private final YoDouble integratedRotationAngle; private final YoDouble absoluteFootOmega; private final YoBoolean isRotating; private final DoubleProvider omegaThresholdForEstimation; private final DoubleProvider decayBreakFrequency; private final DoubleProvider rotationThreshold; public VelocityFootRotationDetector(RobotSide side, MovingReferenceFrame soleFrame, FootholdRotationParameters parameters, double dt, YoRegistry parentRegistry) { this.soleFrame = soleFrame; this.dt = dt; String namePrefix = side.getLowerCaseName() + "Velocity"; YoRegistry registry = new YoRegistry(getClass().getSimpleName() + side.getPascalCaseName()); parentRegistry.addChild(registry); omegaThresholdForEstimation = parameters.getOmegaMagnitudeThresholdForEstimation(); decayBreakFrequency = parameters.getVelocityRotationAngleDecayBreakFrequency(); rotationThreshold = parameters.getVelocityRotationAngleThreshold(); integratedRotationAngle = new YoDouble(namePrefix + "IntegratedRotationAngle", registry); absoluteFootOmega = new YoDouble(namePrefix + "AbsoluteFootOmega", registry); isRotating = new YoBoolean(namePrefix + "IsRotating", registry); reset(); } public void reset() { integratedRotationAngle.set(0.0); absoluteFootOmega.set(0.0); isRotating.set(false); } public boolean compute() { // Using the twist of the foot TwistReadOnly soleFrameTwist = soleFrame.getTwistOfFrame(); absoluteFootOmega.set(soleFrameTwist.getAngularPart().length()); if (absoluteFootOmega.getValue() > omegaThresholdForEstimation.getValue()) { integratedRotationAngle.add(dt * absoluteFootOmega.getValue()); } isRotating.set(integratedRotationAngle.getValue() > rotationThreshold.getValue()); integratedRotationAngle.mul(AlphaFilteredYoVariable.computeAlphaGivenBreakFrequencyProperly(decayBreakFrequency.getValue(), dt)); return isRotating.getValue(); } public boolean isRotating() { return isRotating.getBooleanValue(); } }
38.036585
152
0.731004
3dea8ee6154a051e3f5900f1994c2516e1c25f3f
28,117
/** * Copyright (c) 2014, 2018 ControlsFX * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of ControlsFX, any associated website, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CONTROLSFX BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.controlsfx.dialog; import static impl.org.controlsfx.i18n.Localization.asKey; import static impl.org.controlsfx.i18n.Localization.localize; import impl.org.controlsfx.ImplUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.Stack; import java.util.function.BooleanSupplier; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Rectangle2D; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.DialogPane; import javafx.scene.layout.Pane; import javafx.stage.Screen; import javafx.stage.Window; import org.controlsfx.tools.ValueExtractor; import org.controlsfx.validation.ValidationSupport; /** * <p>The API for creating multi-page Wizards, based on JavaFX {@link Dialog} API.<br> * Wizard can be setup in following few steps:</p> * <ul> * <li>Design wizard pages by inheriting them from {@link WizardPane}</li> * <li>Define wizard flow by implementing {@link Wizard.Flow}</li> * <li>Create and instance of the Wizard and assign flow to it</li> * <li>Execute the wizard using showAndWait method</li> * <li>Values can be extracted from settings map by calling getSettings * </ul> * <p>For simple, linear wizards, the {@link LinearFlow} can be used. * It is a flow based on a collection of wizard pages. Here is the example:</p> * * <pre>{@code // Create pages. Here for simplicity we just create and instance of WizardPane. * WizardPane page1 = new WizardPane(); * WizardPane page2 = new WizardPane(); * WizardPane page3 = new WizardPane(); * * // create wizard * Wizard wizard = new Wizard(); * * // create and assign the flow * wizard.setFlow(new LinearFlow(page1, page2, page3)); * * // show wizard and wait for response * wizard.showAndWait().ifPresent(result -> { * if (result == ButtonType.FINISH) { * System.out.println("Wizard finished, settings: " + wizard.getSettings()); * } * });}</pre> * * <p>For more complex wizard flows we suggest to create a custom ones, describing page traversal logic. * Here is a simplified example: </p> * * <pre>{@code Wizard.Flow branchingFlow = new Wizard.Flow() { * public Optional<WizardPane> advance(WizardPane currentPage) { * return Optional.of(getNext(currentPage)); * } * * public boolean canAdvance(WizardPane currentPage) { * return currentPage != page3; * } * * private WizardPane getNext(WizardPane currentPage) { * if ( currentPage == null ) { * return page1; * } else if ( currentPage == page1) { * // skipNextPage() does not exist - this just represents that you * // can add a conditional statement here to change the page. * return page1.skipNextPage()? page3: page2; * } else { * return page3; * } * } * };}</pre> */ public class Wizard { /************************************************************************** * * Private fields * **************************************************************************/ private Dialog<ButtonType> dialog; private final ObservableMap<String, Object> settings = FXCollections.observableHashMap(); private final Stack<WizardPane> pageHistory = new Stack<>(); private Optional<WizardPane> currentPage = Optional.empty(); private final BooleanProperty invalidProperty = new SimpleBooleanProperty(false); // Read settings activated by default for backward compatibility private final BooleanProperty readSettingsProperty = new SimpleBooleanProperty(true); private final ButtonType BUTTON_PREVIOUS = new ButtonType(localize(asKey("wizard.previous.button")), ButtonData.BACK_PREVIOUS); //$NON-NLS-1$ private final EventHandler<ActionEvent> BUTTON_PREVIOUS_ACTION_HANDLER = actionEvent -> { actionEvent.consume(); Optional<WizardPane> nextPage = Optional.ofNullable( pageHistory.isEmpty()? null: pageHistory.pop() ); updatePage(dialog, nextPage, false); }; private final ButtonType BUTTON_NEXT = new ButtonType(localize(asKey("wizard.next.button")), ButtonData.NEXT_FORWARD); //$NON-NLS-1$ private final EventHandler<ActionEvent> BUTTON_NEXT_ACTION_HANDLER = actionEvent -> { actionEvent.consume(); currentPage.ifPresent(page->pageHistory.push(page)); Optional<WizardPane> nextPage = getFlow().advance(currentPage.orElse(null)); updatePage(dialog, nextPage, true); }; private final EventHandler<ActionEvent> BUTTON_FINISH_ACTION_HANDLER = actionEvent -> { updatePage(dialog, Optional.empty(), true); }; private final EventHandler<ActionEvent> BUTTON_CANCEL_ACTION_HANDLER = actionEvent -> { updatePage(dialog, Optional.empty(), false); }; private final StringProperty titleProperty = new SimpleStringProperty(); /************************************************************************** * * Constructors * **************************************************************************/ /** * Creates an instance of the wizard without an owner. */ public Wizard() { this(null); } /** * Creates an instance of the wizard with the given owner. * @param owner The object from which the owner window is deduced (typically * this is a Node, but it may also be a Scene or a Stage). */ public Wizard(Object owner) { this(owner, ""); //$NON-NLS-1$ } /** * Creates an instance of the wizard with the given owner and title. * * @param owner The object from which the owner window is deduced (typically * this is a Node, but it may also be a Scene or a Stage). * @param title The wizard title. */ public Wizard(Object owner, String title) { invalidProperty.addListener( (o, ov, nv) -> validateActionState()); dialog = new Dialog<>(); dialog.titleProperty().bind(this.titleProperty); setTitle(title); Window window = null; if ( owner instanceof Window) { window = (Window)owner; } else if ( owner instanceof Node ) { window = ((Node)owner).getScene().getWindow(); } dialog.initOwner(window); } /************************************************************************** * * Public API * **************************************************************************/ // /** // * Shows the wizard but does not wait for a user response (in other words, // * this brings up a non-blocking dialog). Users of this API must either // * poll the {@link #resultProperty() result property}, or else add a listener // * to the result property to be informed of when it is set. // */ // public final void show() { // dialog.show(); // } /** * Shows the wizard and waits for the user response (in other words, brings * up a blocking dialog, with the returned value the users input). * * @return An {@link Optional} that contains the result. */ public final Optional<ButtonType> showAndWait() { return dialog.showAndWait(); } /** * @return {@link Dialog#resultProperty()} of the {@link Dialog} representing this {@link Wizard}. */ public final ObjectProperty<ButtonType> resultProperty() { return dialog.resultProperty(); } /** * The settings map is the place where all data from pages is kept once the * user moves on from the page, assuming there is a {@link ValueExtractor} * that is capable of extracting a value out of the various fields on the page. */ public final ObservableMap<String, Object> getSettings() { return settings; } /************************************************************************** * * Properties * **************************************************************************/ // --- title /** * Return the titleProperty of the wizard. */ public final StringProperty titleProperty() { return titleProperty; } /** * Return the title of the wizard. */ public final String getTitle() { return titleProperty.get(); } /** * Change the Title of the wizard. * @param title */ public final void setTitle( String title ) { titleProperty.set(title); } // --- flow /** * The {@link Flow} property represents the flow of pages in the wizard. */ private ObjectProperty<Flow> flow = new SimpleObjectProperty<Flow>(new LinearFlow()) { @Override protected void invalidated() { updatePage(dialog, Optional.empty(), false); } @Override public void set(Flow flow) { super.set(flow); pageHistory.clear(); if ( flow != null ) { Optional<WizardPane> nextPage = flow.advance(currentPage.orElse(null)); updatePage(dialog, nextPage, true); } }; }; public final ObjectProperty<Flow> flowProperty() { return flow; } /** * Returns the currently set {@link Flow}, which represents the flow of * pages in the wizard. */ public final Flow getFlow() { return flow.get(); } /** * Sets the {@link Flow}, which represents the flow of pages in the wizard. */ public final void setFlow(Flow flow) { this.flow.set(flow); } // --- Properties private static final Object USER_DATA_KEY = new Object(); // A map containing a set of properties for this Wizard private ObservableMap<Object, Object> properties; /** * Returns an observable map of properties on this Wizard for use primarily * by application developers - not to be confused with the * {@link #getSettings()} map that represents the values entered by the user * into the wizard. * * @return an observable map of properties on this Wizard for use primarily * by application developers */ public final ObservableMap<Object, Object> getProperties() { if (properties == null) { properties = FXCollections.observableMap(new HashMap<>()); } return properties; } /** * Tests if this Wizard has properties. * @return true if this Wizard has properties. */ public boolean hasProperties() { return properties != null && !properties.isEmpty(); } // --- UserData /** * Convenience method for setting a single Object property that can be * retrieved at a later date. This is functionally equivalent to calling * the getProperties().put(Object key, Object value) method. This can later * be retrieved by calling {@link #getUserData()}. * * @param value The value to be stored - this can later be retrieved by calling * {@link #getUserData()}. */ public void setUserData(Object value) { getProperties().put(USER_DATA_KEY, value); } /** * Returns a previously set Object property, or null if no such property * has been set using the {@link #setUserData(Object)} method. * * @return The Object that was previously set, or null if no property * has been set or if null was set. */ public Object getUserData() { return getProperties().get(USER_DATA_KEY); } /** * Sets the value of the property {@code invalid}. * * @param invalid The new validation state * {@link #invalidProperty() } */ public final void setInvalid(boolean invalid) { invalidProperty.set(invalid); } /** * Gets the value of the property {@code invalid}. * * @return The validation state * @see #invalidProperty() */ public final boolean isInvalid() { return invalidProperty.get(); } /** * Property for overriding the individual validation state of this {@link Wizard}. * Setting {@code invalid} to true will disable the next/finish Button and the user * will not be able to advance to the next page of the {@link Wizard}. Setting * {@code invalid} to false will enable the next/finish Button. <br> * <br> * For example you can use the {@link ValidationSupport#invalidProperty()} of a * page and bind it to the {@code invalid} property: <br> * {@code * wizard.invalidProperty().bind(page.validationSupport.invalidProperty()); * } * * @return The validation state property */ public final BooleanProperty invalidProperty() { return invalidProperty; } /** * Sets the value of the property {@code readSettings}. * * @param readSettings The new read-settings state * @see #readSettingsProperty() */ public final void setReadSettings(boolean readSettings) { readSettingsProperty.set(readSettings); } /** * Gets the value of the property {@code readSettings}. * * @return The read-settings state * @see #readSettingsProperty() */ public final boolean isReadSettings() { return readSettingsProperty.get(); } /** * Property for overriding the individual read-settings state of this {@link Wizard}. * Setting {@code readSettings} to true will enable the value extraction for this * {@link Wizard}. Setting {@code readSettings} to false will disable the value * extraction for this {@link Wizard}. * * @return The readSettings state property */ public final BooleanProperty readSettingsProperty() { return readSettingsProperty; } /************************************************************************** * * Private implementation * **************************************************************************/ private void updatePage(Dialog<ButtonType> dialog, Optional<WizardPane> nextPage, boolean advancing) { Flow flow = getFlow(); if (flow == null) { return; } Optional<WizardPane> prevPage = currentPage; prevPage.ifPresent( page -> { // if we are going forward in the wizard, we read in the settings // from the page and store them in the settings map. // If we are going backwards, we do nothing // This is only performed if readSettings is true. if (advancing && isReadSettings()) { readSettings(page); } // give the previous wizard page a chance to update the pages list // based on the settings it has received page.onExitingPage(this); }); currentPage = nextPage; currentPage.ifPresent(currentPage -> { // put in default actions addButtonIfMissing(currentPage, BUTTON_PREVIOUS, BUTTON_PREVIOUS_ACTION_HANDLER); addButtonIfMissing(currentPage, BUTTON_NEXT, BUTTON_NEXT_ACTION_HANDLER); addButtonIfMissing(currentPage, ButtonType.FINISH, BUTTON_FINISH_ACTION_HANDLER); addButtonIfMissing(currentPage, ButtonType.CANCEL, BUTTON_CANCEL_ACTION_HANDLER); // then give user a chance to modify the default actions currentPage.onEnteringPage(this); // Remove from DecorationPane which has been created by e.g. validation if (currentPage.getParent() != null && currentPage.getParent() instanceof Pane) { Pane parentOfCurrentPage = (Pane) currentPage.getParent(); parentOfCurrentPage.getChildren().remove(currentPage); } // Get current position and size double previousX = dialog.getX(); double previousY = dialog.getY(); double previousWidth = dialog.getWidth(); double previousHeight = dialog.getHeight(); // and then switch to the new pane dialog.setDialogPane(currentPage); // Resize Wizard to new page Window wizard = currentPage.getScene().getWindow(); wizard.sizeToScene(); // Center resized Wizard to previous position if (!Double.isNaN(previousX) && !Double.isNaN(previousY)) { double newWidth = dialog.getWidth(); double newHeight = dialog.getHeight(); int newX = (int) (previousX + (previousWidth / 2.0) - (newWidth / 2.0)); int newY = (int) (previousY + (previousHeight / 2.0) - (newHeight / 2.0)); ObservableList<Screen> screens = Screen.getScreensForRectangle(previousX, previousY, 1, 1); Screen screen = screens.isEmpty() ? Screen.getPrimary() : screens.get(0); Rectangle2D scrBounds = screen.getBounds(); int minX = (int)Math.round(scrBounds.getMinX()); int maxX = (int)Math.round(scrBounds.getMaxX()); int minY = (int)Math.round(scrBounds.getMinY()); int maxY = (int)Math.round(scrBounds.getMaxY()); if(newX + newWidth > maxX) { newX = maxX - (int)Math.round(newWidth); } if(newY + newHeight > maxY) { newY = maxY - (int)Math.round(newHeight); } if(newX < minX) { newX = minX; } if(newY < minY) { newY = minY; } dialog.setX(newX); dialog.setY(newY); } }); validateActionState(); } private static void addButtonIfMissing(WizardPane page, ButtonType buttonType, EventHandler<ActionEvent> actionHandler) { List<ButtonType> buttons = page.getButtonTypes(); if (! buttons.contains(buttonType)) { buttons.add(buttonType); Button button = (Button)page.lookupButton(buttonType); button.addEventFilter(ActionEvent.ACTION, actionHandler); } } private void validateActionState() { final List<ButtonType> currentPaneButtons = dialog.getDialogPane().getButtonTypes(); if (getFlow().canAdvance(currentPage.orElse(null))) { currentPaneButtons.remove(ButtonType.FINISH); } else { currentPaneButtons.remove(BUTTON_NEXT); } validateButton( BUTTON_PREVIOUS, () -> pageHistory.isEmpty()); validateButton( BUTTON_NEXT, () -> invalidProperty.get()); validateButton( ButtonType.FINISH, () -> invalidProperty.get()); } // Functional design allows to delay condition evaluation until it is actually needed private void validateButton( ButtonType buttonType, BooleanSupplier condition) { Button btn = (Button)dialog.getDialogPane().lookupButton(buttonType); if ( btn != null ) { Node focusOwner = (btn.getScene() != null) ? btn.getScene().getFocusOwner() : null; btn.setDisable(condition.getAsBoolean()); if(focusOwner != null) { focusOwner.requestFocus(); } } } private int settingCounter; private void readSettings(WizardPane page) { // for now we cannot know the structure of the page, so we just drill down // through the entire scenegraph (from page.content down) until we get // to the leaf nodes. We stop only if we find a node that is a // ValueContainer (either by implementing the interface), or being // listed in the internal valueContainers map. settingCounter = 0; checkNode(page.getContent()); } private boolean checkNode(Node n) { boolean success = readSetting(n); if (success) { // we've added the setting to the settings map and we should stop drilling deeper return true; } else { /** * go into children of this node (if possible) and see if we can get * a value from them (recursively) We use reflection to fix * https://bitbucket.org/controlsfx/controlsfx/issue/412 . */ List<Node> children = ImplUtils.getChildren(n, true); // we're doing a depth-first search, where we stop drilling down // once we hit a successful read boolean childSuccess = false; for (Node child : children) { childSuccess |= checkNode(child); } return childSuccess; } } private boolean readSetting(Node n) { if (n == null) { return false; } Object setting = ValueExtractor.getValue(n); if (setting != null) { // save it into the settings map. // if the node has an id set, we will use that as the setting name String settingName = n.getId(); // but if the id is not set, we will use a generic naming scheme if (settingName == null || settingName.isEmpty()) { settingName = "page_" /*+ previousPageIndex*/ + ".setting_" + settingCounter; //$NON-NLS-1$ //$NON-NLS-2$ } getSettings().put(settingName, setting); settingCounter++; } return setting != null; } /************************************************************************** * * Support classes * **************************************************************************/ /** * Represents the page flow of the wizard. It defines only methods required * to move forward in the wizard logic, as backward movement is automatically * handled by wizard itself, using internal page history. */ public interface Flow { /** * Advances the wizard to the next page if possible. * * @param currentPage The current wizard page * @return {@link Optional} value containing the next wizard page. */ Optional<WizardPane> advance(WizardPane currentPage); /** * Check if advancing to the next page is possible * * @param currentPage The current wizard page * @return true if it is possible to advance to the next page, false otherwise. */ boolean canAdvance(WizardPane currentPage); } /** * LinearFlow is an implementation of the {@link Wizard.Flow} interface, * designed to support the most common type of wizard flow - namely, a linear * wizard page flow (i.e. through all pages in the order that they are specified). * Therefore, this {@link Flow} implementation simply traverses a collections of * {@link WizardPane WizardPanes}. * * <p>For example of how to use this API, please refer to the {@link Wizard} * documentation</p> * * @see Wizard * @see WizardPane */ public static class LinearFlow implements Wizard.Flow { private final List<WizardPane> pages; /** * Creates a new LinearFlow instance that will allow for stepping through * the given collection of {@link WizardPane} instances. */ public LinearFlow( Collection<WizardPane> pages ) { this.pages = new ArrayList<>(pages); } /** * Creates a new LinearFlow instance that will allow for stepping through * the given varargs array of {@link WizardPane} instances. */ public LinearFlow( WizardPane... pages ) { this( Arrays.asList(pages)); } /** {@inheritDoc} */ @Override public Optional<WizardPane> advance(WizardPane currentPage) { int pageIndex = pages.indexOf(currentPage); return Optional.ofNullable( pages.get(++pageIndex) ); } /** {@inheritDoc} */ @Override public boolean canAdvance(WizardPane currentPage) { int pageIndex = pages.indexOf(currentPage); return pages.size()-1 > pageIndex; } } /************************************************************************** * * Methods for the sake of unit tests * **************************************************************************/ /** * @return The {@link Dialog} representing this {@link Wizard}. <br> * This is actually for {@link Dialog} reading-purposes, e.g. * unit testing the {@link DialogPane} content. */ Dialog<ButtonType> getDialog() { return dialog; } }
37.639893
146
0.579756