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
945e70ff4ea362296c3acef7943919adc0d67b4f
1,660
package com.cyberlink.cosmetic.modules.post.service.impl; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.cyberlink.cosmetic.modules.post.service.LanguageDetectService; import com.optimaize.langdetect.DetectedLanguage; import com.optimaize.langdetect.LanguageDetector; import com.optimaize.langdetect.LanguageDetectorBuilder; import com.optimaize.langdetect.ngram.NgramExtractors; import com.optimaize.langdetect.profiles.LanguageProfileReader; import com.optimaize.langdetect.text.CommonTextObjectFactories; import com.optimaize.langdetect.text.TextObject; import com.optimaize.langdetect.text.TextObjectFactory; public class LanguageDetectServiceImpl implements LanguageDetectService { LanguageProfileReader profileReader; LanguageDetector languageDetector; TextObjectFactory textObjectFactory; public LanguageProfileReader getProfileReader() { return profileReader; } public void setProfileReader(LanguageProfileReader profileReader) { this.profileReader = profileReader; try { languageDetector = LanguageDetectorBuilder.create(NgramExtractors.standard()) .withProfiles(new LanguageProfileReader().readAll()) .build(); textObjectFactory = CommonTextObjectFactories.forDetectingShortCleanText(); } catch (IOException e) { e.printStackTrace(); } } @Override public List<DetectedLanguage> getProbabilities(String text) { if (textObjectFactory == null || languageDetector == null) return new ArrayList<DetectedLanguage>(); TextObject textObject = textObjectFactory.forText(text); return languageDetector.getProbabilities(textObject); } }
35.319149
80
0.808434
01675d989ba6566b1bfa86ac8e6c3e18fc115000
1,006
package com.massandy.mydaterangepicker; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.squareup.timessquare.CalendarPickerView; import java.util.Calendar; import java.util.Date; /** * Created by massandy on 22/06/17. * from lib : https://github.com/square/android-times-square */ public class TimeSquareFragment extends AppCompatActivity { private CalendarPickerView calendar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.time_square); Calendar nextYear = Calendar.getInstance(); nextYear.add(Calendar.YEAR, 1); calendar = (CalendarPickerView) findViewById(R.id.calendar_view); Date today = new Date(); calendar.init(today, nextYear.getTime()) .withSelectedDate(today) .inMode(CalendarPickerView.SelectionMode.RANGE); // calendar.highlightDates(getHolidays()); } }
27.189189
73
0.708748
2a623f8260949ac3376fc9a86362746bec84b9d5
1,519
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.htmlInspections; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.lang.html.HTMLLanguage; import com.intellij.openapi.util.TextRange; import com.intellij.psi.html.HtmlTag; import com.intellij.psi.xml.XmlTag; import com.intellij.xml.analysis.XmlAnalysisBundle; import com.intellij.xml.util.HtmlUtil; import com.intellij.xml.util.XmlTagUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; /** * @author spleaner */ public class HtmlExtraClosingTagInspection extends HtmlLocalInspectionTool { @Override @NonNls @NotNull public String getShortName() { return "HtmlExtraClosingTag"; } @Override protected void checkTag(@NotNull final XmlTag tag, @NotNull final ProblemsHolder holder, final boolean isOnTheFly) { final TextRange range = XmlTagUtil.getEndTagRange(tag); if (range != null && tag instanceof HtmlTag && HtmlUtil.isSingleHtmlTag(tag, true) && tag.getLanguage().isKindOf(HTMLLanguage.INSTANCE)) { holder.registerProblem(tag, XmlAnalysisBundle.message("extra.closing.tag.for.empty.element"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, range.shiftRight(-tag.getTextRange().getStartOffset()), new RemoveExtraClosingTagIntentionAction()); } } }
37.975
170
0.772219
b633f16518081da80f5a8aa13d1025e03637df06
9,694
/***************************************************************** * 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.cayenne.modeler.util; import java.awt.Color; import java.awt.Font; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Collection; import javax.swing.DefaultCellEditor; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.table.TableCellEditor; import org.apache.cayenne.modeler.ModelerPreferences; import org.apache.cayenne.modeler.undo.JComboBoxUndoListener; import org.apache.cayenne.modeler.util.combo.AutoCompletion; import org.apache.cayenne.modeler.util.combo.ComboBoxCellEditor; import org.apache.cayenne.swing.components.textpane.JCayenneTextPane; import org.apache.cayenne.swing.components.textpane.syntax.EJBQLSyntaxConstant; import org.syntax.jedit.DefaultInputHandler; import org.syntax.jedit.JEditTextArea; /** * Utility class to create standard Swing widgets following default look-and-feel of * CayenneModeler. * */ // TODO: (Andrus) investigate performance impact of substituting // constructors for all new widgets with cloning the prototype public class CayenneWidgetFactory { /** * Not intended for instantiation. */ protected CayenneWidgetFactory() { super(); } /** * Creates a new JComboBox with a collection of model objects. */ public static JComboBox createComboBox(Collection<String> model, boolean sort) { return createComboBox(model.toArray(), sort); } /** * Creates a new JComboBox with an array of model objects. */ public static JComboBox createComboBox(Object[] model, boolean sort) { JComboBox comboBox = CayenneWidgetFactory.createComboBox(); if (sort) { Arrays.sort(model); } comboBox.setModel(new DefaultComboBoxModel(model)); return comboBox; } /** * Creates a new JComboBox. */ public static JComboBox createComboBox() { JComboBox comboBox = new JComboBox(); initFormWidget(comboBox); comboBox.setBackground(Color.WHITE); comboBox.setMaximumRowCount(ModelerPreferences.COMBOBOX_MAX_VISIBLE_SIZE); return comboBox; } /** * Creates undoable JComboBox. * */ public static JComboBox createUndoableComboBox() { JComboBox comboBox = new JComboBox(); initFormWidget(comboBox); comboBox.addItemListener(new JComboBoxUndoListener()); comboBox.setBackground(Color.WHITE); comboBox.setMaximumRowCount(ModelerPreferences.COMBOBOX_MAX_VISIBLE_SIZE); return comboBox; } /** * Creates undoable JTextField. * */ public static JTextField createUndoableTextField() { return new JTextFieldUndoable(); } /** * Creates undoable JTextField. * */ public static JTextField createUndoableTextField(int size) { return new JTextFieldUndoable(size); } /** * Creates cell editor for text field */ public static DefaultCellEditor createCellEditor(JTextField textField) { return new CayenneCellEditor(textField); } /** * Creates cell editor for a table with combo as editor component. Type of this editor * depends on auto-completion behavior of JComboBox * * @param combo JComboBox to be used as editor component */ public static TableCellEditor createCellEditor(JComboBox combo) { if (Boolean.TRUE.equals(combo .getClientProperty(AutoCompletion.AUTOCOMPLETION_PROPERTY))) { return new ComboBoxCellEditor(combo); } DefaultCellEditor editor = new DefaultCellEditor(combo); editor.setClickCountToStart(1); return editor; } /** * Creates a new JTextField with a default columns count of 20. */ public static JTextField createTextField() { return createTextField(20); } /** * Creates a new JTextField with a specified columns count. */ public static JTextField createTextField(int columns) { final JTextField textField = new JTextField(columns); initFormWidget(textField); initTextField(textField); return textField; } protected static void initTextField(final JTextField textField) { // config focus textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // transfer focus textField.transferFocus(); } }); } /** * Initializes a "form" element with a standard font and height. */ protected static void initFormWidget(JComponent component) { component.setFont(component.getFont().deriveFont(Font.PLAIN, 12)); /* * Dimension size = component.getPreferredSize(); if (size == null) { size = new * Dimension(); } size.setSize(size.getWidth(), 20); * component.setPreferredSize(size); */ } /** * Creates a borderless button that can be used as a clickable label. */ public static JButton createLabelButton(String text) { JButton but = createButton(text); but.setBorderPainted(false); but.setHorizontalAlignment(SwingConstants.LEFT); but.setFocusPainted(false); but.setMargin(new Insets(0, 0, 0, 0)); but.setBorder(null); return but; } /** * Creates a normal button. */ public static JButton createButton(String text) { return new JButton(text); } /** * Creates and returns a JEdit text component with syntax highlighing */ public static JEditTextArea createJEditTextArea() { JEditTextArea area = new JEditTextAreaUndoable(); if (OperatingSystem.getOS() == OperatingSystem.MAC_OS_X) { area.setInputHandler(new MacInputHandler()); } return area; } // public static JSQLTextPane createJSQLTextPane() { // JSQLTextPane area = new JSQLTextPane(); // return area; // } public static JCayenneTextPane createJEJBQLTextPane() { JCayenneTextPane area = new JCayenneTextPaneUndoable(new EJBQLSyntaxConstant()); return area; } /** * Class for enabling Mac OS X keys */ private static class MacInputHandler extends DefaultInputHandler { MacInputHandler() { addDefaultKeyBindings(); } /** * Sets up the default key bindings. */ public void addDefaultKeyBindings() { addKeyBinding("BACK_SPACE", BACKSPACE); addKeyBinding("M+BACK_SPACE", BACKSPACE_WORD); addKeyBinding("DELETE", DELETE); addKeyBinding("M+DELETE", DELETE_WORD); addKeyBinding("ENTER", INSERT_BREAK); addKeyBinding("TAB", INSERT_TAB); addKeyBinding("INSERT", OVERWRITE); addKeyBinding("M+\\", TOGGLE_RECT); addKeyBinding("HOME", HOME); addKeyBinding("END", END); addKeyBinding("M+A", SELECT_ALL); addKeyBinding("S+HOME", SELECT_HOME); addKeyBinding("S+END", SELECT_END); addKeyBinding("M+HOME", DOCUMENT_HOME); addKeyBinding("M+END", DOCUMENT_END); addKeyBinding("MS+HOME", SELECT_DOC_HOME); addKeyBinding("MS+END", SELECT_DOC_END); addKeyBinding("PAGE_UP", PREV_PAGE); addKeyBinding("PAGE_DOWN", NEXT_PAGE); addKeyBinding("S+PAGE_UP", SELECT_PREV_PAGE); addKeyBinding("S+PAGE_DOWN", SELECT_NEXT_PAGE); addKeyBinding("LEFT", PREV_CHAR); addKeyBinding("S+LEFT", SELECT_PREV_CHAR); addKeyBinding("A+LEFT", PREV_WORD); // option + left addKeyBinding("AS+LEFT", SELECT_PREV_WORD); // option + shift + left addKeyBinding("RIGHT", NEXT_CHAR); addKeyBinding("S+RIGHT", SELECT_NEXT_CHAR); addKeyBinding("A+RIGHT", NEXT_WORD); // option + right addKeyBinding("AS+RIGHT", SELECT_NEXT_WORD); // option + shift + right addKeyBinding("UP", PREV_LINE); addKeyBinding("S+UP", SELECT_PREV_LINE); addKeyBinding("DOWN", NEXT_LINE); addKeyBinding("S+DOWN", SELECT_NEXT_LINE); addKeyBinding("M+ENTER", REPEAT); // Clipboard addKeyBinding("M+C", CLIP_COPY); // command + c addKeyBinding("M+V", CLIP_PASTE); // command + v addKeyBinding("M+X", CLIP_CUT); // command + x } } }
32.861017
90
0.64411
97ee512c7ff342a166d6741cbba55d5c93cb4c4e
4,257
package org.apdoer.push.service.event.impl; import lombok.extern.slf4j.Slf4j; import org.apdoer.push.service.event.EventBusChannel; import org.apdoer.push.service.event.EventBusManager; import org.apdoer.push.service.event.SourceEvent; import org.apdoer.push.service.event.SourceEventListener; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * 内部数据通道管理器 * * @author apdoer * @version 1.0 * @date 2020/5/9 15:06 */ @Slf4j public class GuavaEventBusManager implements EventBusManager { private ReentrantLock lock = new ReentrantLock(); private Map<String, EventBusChannel> eventBusChannelMap = new ConcurrentHashMap<>(); private GuavaEventBusManager() { } private static class InnerGuavaEventBusManager { private static final GuavaEventBusManager INSTANCE = new GuavaEventBusManager(); } public static final GuavaEventBusManager getInstance() { return InnerGuavaEventBusManager.INSTANCE; } @Override public void subscribe(SourceEventListener listener) { for (Map.Entry<String, EventBusChannel> eventBusChannelEntry : eventBusChannelMap.entrySet()) { eventBusChannelEntry.getValue().subscribe(listener); } } @Override public void subscribe(SourceEventListener listener, String systemChannel) { if (eventBusChannelMap.containsKey(systemChannel)) { eventBusChannelMap.get(systemChannel).subscribe(listener); } } @Override public void unSubscribe(SourceEventListener listener) { for (Map.Entry<String, EventBusChannel> eventBusChannelEntry : eventBusChannelMap.entrySet()) { eventBusChannelEntry.getValue().unSubscribe(listener); } } @Override public void unSubscribe(SourceEventListener listener, String systemChannel) { try { if (eventBusChannelMap.containsKey(systemChannel)) { eventBusChannelMap.get(systemChannel).unSubscribe(listener); } } catch (Exception e) { log.error("unsubscribe error,systemChannel:{},", systemChannel); } } @Override public void publish(String systemChannel, SourceEvent event) { if (eventBusChannelMap.containsKey(systemChannel)) { eventBusChannelMap.get(systemChannel).publish(event); } } @Override public void buildEventBusChannel(String systemChannel) { try { lock.lock(); if (!eventBusChannelMap.containsKey(systemChannel)) { new EventBusChannelImpl(systemChannel); } } catch (Exception e) { log.error("build eventbusChannel error", e); } finally { lock.unlock(); } } @Override public void buildEventBusChannel(String systemChannel, int backPressureSize) { try { lock.lock(); if (!eventBusChannelMap.containsKey(systemChannel)) { EventBusChannel channel = new EventBusChannelImpl(backPressureSize, systemChannel); eventBusChannelMap.put(systemChannel, channel); } } catch (Exception e) { log.error("", e); } finally { lock.unlock(); } } @Override public EventBusChannel getEventBusChannel(String systemChannel) { if (eventBusChannelMap.containsKey(systemChannel)) { return eventBusChannelMap.get(systemChannel); } return null; } @Override public boolean containsChannel(String systemChannel) { return eventBusChannelMap.containsKey(systemChannel); } @Override public Map<String, Integer> getChannelWaitSize() { Map<String, Integer> map = new HashMap<>(eventBusChannelMap.size()); for (Map.Entry<String, EventBusChannel> entry : eventBusChannelMap.entrySet()) { map.put(entry.getKey(), entry.getValue().getQueueSize()); } return map; } @Override public void shutdown() { for (Map.Entry<String, EventBusChannel> entry : eventBusChannelMap.entrySet()) { entry.getValue().shutdown(); } } }
31.072993
103
0.660089
0fc65172f19655898396791a549e628d82e60a74
1,759
package top.fosin.anan.cloudresource.service.inter; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import top.fosin.anan.cloudresource.constant.RequestPath; import top.fosin.anan.cloudresource.constant.ServiceConstant; import top.fosin.anan.cloudresource.constant.UrlPrefixConstant; import top.fosin.anan.cloudresource.dto.res.PermissionRespDto; import top.fosin.anan.cloudresource.service.PermissionFeignFallbackServiceImpl; import top.fosin.anan.model.result.MultResult; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import java.util.List; /** * 远程调用权限服务 * * @author fosin * @date 2019-3-26 */ @FeignClient(value = ServiceConstant.ANAN_PLATFORMSERVER, path = UrlPrefixConstant.PERMISSION, fallback = PermissionFeignFallbackServiceImpl.class, contextId = "permissionFeignService") public interface PermissionFeignService { /** * 远程查询应用权限 * * @param serviceCode 服务标识 * @return 应用权限列表 */ @PostMapping(RequestPath.SERVICE_CODE) MultResult<PermissionRespDto> findByServiceCode(@NotBlank @PathVariable("serviceCode") String serviceCode); /** * 远程查询应用权限 * * @param serviceCodes 服务标识清单 * @return 应用权限列表 */ @PostMapping(value = RequestPath.SERVICE_CODES, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) MultResult<PermissionRespDto> findByServiceCodes(@NotEmpty @RequestBody List<String> serviceCodes); }
36.645833
141
0.79079
263560866c2d5d1e09558189b03f30487e1d0dac
608
package engine.racedetectionengine.hb; import java.util.HashSet; import engine.racedetectionengine.RaceDetectionEngine; import event.Thread; import parse.ParserType; public class HBEngine extends RaceDetectionEngine<HBState, HBEvent> { public HBEngine(ParserType pType, String trace_folder) { super(pType); this.threadSet = new HashSet<Thread> (); initializeReader(trace_folder); this.state = new HBState(this.threadSet); this.handlerEvent = new HBEvent(); } protected boolean skipEvent(HBEvent handlerEvent){ return false; } protected void postHandleEvent(HBEvent handlerEvent){} }
24.32
69
0.782895
74e8c92dce69eef69189d96acafa5de1b0515b73
4,392
package com.cladonia.xml.schematron; import java.io.OutputStream; import java.io.PrintStream; import javax.swing.SwingUtilities; import javax.xml.transform.SourceLocator; import com.cladonia.xngreditor.ExchangerEditor; import net.sf.saxon.Controller; import net.sf.saxon.lib.Logger; import net.sf.saxon.serialize.MessageEmitter; import net.sf.saxon.expr.XPathContext; import net.sf.saxon.om.Item; import net.sf.saxon.s9api.MessageListener; import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.tree.tiny.TinyNodeImpl; import net.sf.saxon.tree.tiny.TinyTextImpl; import net.sf.saxon.tree.tiny.TinyTree; import net.sf.saxon.trace.InstructionInfo; import net.sf.saxon.lib.TraceListener; import net.sf.saxon.type.Type; import net.sf.saxon.type.TypeHierarchy; import sun.reflect.generics.reflectiveObjects.NotImplementedException; public class SchematronTraceListener implements TraceListener { public MessageEmitter me = null; public int curPos; public OutputStream mos = null; private ExchangerEditor editor = null; private int currentLineNumber = -1; private int currentColumn = -1; private int errorCounter = 0; public SchematronTraceListener(ExchangerEditor editor) { this.editor = editor; } @Override public void close() { //System.out.println("close"); /*SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if(errorCounter == 0) { editor.getOutputPanel().endCheck("SCHEMATRON", "Finished"); } else if(errorCounter == 1){ editor.getOutputPanel().endCheck("SCHEMATRON", "1 Error"); } else { editor.getOutputPanel().endCheck("SCHEMATRON", errorCounter+ " Errors"); } } });*/ } @Override public void endCurrentItem(Item item) { } @Override public void enter(InstructionInfo arg0, XPathContext arg1) { } @Override public void leave(InstructionInfo arg0) { /*String str = messageOutputStream.toString("UTF-8"); length = str.length(); if (length != 0 && this.curPos != length ) { java.lang.System.err.println( str.substring(this.curPos) + " sysid:" + element.getSystemID() + " lineNum:" + element.getLineNumber()); message = str.substring(this.curPos); jsError = new Packages.org.xml.sax.SAXParseException(message,"" , element.getSystemID(), element.getLineNumber(), 1); this.curPos = length; }*/ } // @Override public void open() { //System.out.println("open"); } @Override public void startCurrentItem(Item item) { if(item instanceof TinyTextImpl) { //System.out.println("startCurrentItem: "+((TinyTextImpl)item).getLocalPart()+ " - line: "+((TinyTextImpl)item).getLineNumber()); setCurrentLineNumber(((TinyTextImpl)item).getLineNumber()); setCurrentColumn(((TinyTextImpl)item).getColumnNumber()); } else if(item instanceof net.sf.saxon.tree.tiny.TinyNodeImpl) { //System.out.println("startCurrentItem: "+((TinyNodeImpl)item).getLocalPart()+ " - line: "+((TinyNodeImpl)item).getLineNumber()); setCurrentLineNumber(((TinyNodeImpl)item).getLineNumber()); setCurrentColumn(((TinyNodeImpl)item).getColumnNumber()); } else { System.out.println("startCurrentItem: "+item.getClass()); } } public void setMessageEmitter(MessageEmitter messageEmitter) { me = messageEmitter; } public void setMessageOutputStream(OutputStream messageOutputStream) { mos = messageOutputStream; } public void setCurrentLineNumber(int currentLineNumber) { this.currentLineNumber = currentLineNumber; } public int getCurrentLineNumber() { return currentLineNumber; } public void setCurrentColumn(int currentColumn) { this.currentColumn = currentColumn; } public int getCurrentColumn() { return currentColumn; } public void setErrorCounter(int errorCounter) { this.errorCounter = errorCounter; } public int getErrorCounter() { return errorCounter; } public void incrementErrorCounter() { this.errorCounter++; } public void setOutputDestination(Logger logger){ throw new NotImplementedException(); } public void open(Controller controller){ open(); } }
25.988166
144
0.686248
2667e766fdb32232767559eb7386ba94eda20fd4
4,493
package it.nextworks.nfvmano.libs.osmr4PlusDataModel.vnfDescriptor; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.HashMap; import java.util.Map; public class InternalVld { @JsonInclude(JsonInclude.Include.NON_NULL) private String id; @JsonInclude(JsonInclude.Include.NON_NULL) private String name; @JsonInclude(JsonInclude.Include.NON_NULL) private String shortName; @JsonInclude(JsonInclude.Include.NON_NULL) private String description; @JsonInclude(JsonInclude.Include.NON_NULL) private String type; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("root-bandwidth") private Integer rootBandwidth; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("leaf-bandwidth") private Integer leafBandwidth; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("internal-connection-point") private InternalConnectionPointVld internalConnectionPoint; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("provider-network") private ProviderNetwork providerNetwork; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("vim-network-name") private String vimNetworkName; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("ip-profile-ref") private String ipProfileRef; private Map<String, Object> otherProperties = new HashMap<String, Object>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getShortName() { return shortName; } public void setShortName(String shortName) { this.shortName = shortName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Integer getRootBandwidth() { return rootBandwidth; } public void setRootBandwidth(Integer rootBandwidth) { this.rootBandwidth = rootBandwidth; } public Integer getLeafBandwidth() { return leafBandwidth; } public void setLeafBandwidth(Integer leafBandwidth) { this.leafBandwidth = leafBandwidth; } public InternalConnectionPointVld getInternalConnectionPoint() { return internalConnectionPoint; } public void setInternalConnectionPoint(InternalConnectionPointVld internalConnectionPoint) { this.internalConnectionPoint = internalConnectionPoint; } public ProviderNetwork getProviderNetwork() { return providerNetwork; } public void setProviderNetwork(ProviderNetwork providerNetwork) { this.providerNetwork = providerNetwork; } public String getVimNetworkName() { return vimNetworkName; } public void setVimNetworkName(String vimNetworkName) { this.vimNetworkName = vimNetworkName; } public String getIpProfileRef() { return ipProfileRef; } public void setIpProfileRef(String ipProfileRef) { this.ipProfileRef = ipProfileRef; } @JsonAnyGetter public Map<String, Object> any() { return otherProperties; } @JsonAnySetter public void set(String name, Object value) { otherProperties.put(name, value); } @Override public String toString() { return "InternalVld{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", shortName='" + shortName + '\'' + ", description='" + description + '\'' + ", type='" + type + '\'' + ", rootBandwidth=" + rootBandwidth + ", leafBandwidth=" + leafBandwidth + ", internalConnectionPoint=" + internalConnectionPoint + ", providerNetwork=" + providerNetwork + ", vimNetworkName='" + vimNetworkName + '\'' + ", ipProfileRef='" + ipProfileRef + '\'' + ", otherProperties=" + otherProperties + '}'; } }
28.08125
96
0.655241
ec81ddf53d69ee0319b36034ab935655cbf1c36a
867
package api.config; import services.*; public enum EntityConfiguration { USER { @Override public Class<?> getEntityService() { return UserService.class; } }, CONSULTAR_HORAS { @Override public Class<?> getEntityService() { return ConsultarHorasService.class; } }, AGREGAR_HORAS { @Override public Class<?> getEntityService() { return AddHorasService.class; } }, EDITAR_HORAS { @Override public Class<?> getEntityService() { return CambiarHorasService.class; } }, ELIMINAR_HORAS { @Override public Class<?> getEntityService() { return BorrarHorasService.class; } }; public abstract Class<?> getEntityService(); }
20.162791
51
0.537486
6b22f1563a43c98ec7c459fdd57e78317eeae2e6
5,986
/** * */ package gov.va.med.imaging.core.interfaces.router; import java.lang.reflect.Proxy; import gov.va.med.IdentityProxyInvocationHandler; import gov.va.med.JndiUtility; import gov.va.med.imaging.core.interfaces.FacadeRouter; import gov.va.med.imaging.core.interfaces.Router; import gov.va.med.server.ServerAdapterImpl; import javax.naming.NamingException; import org.apache.log4j.Logger; /** * @author vhaiswbeckec * */ public abstract class AbstractFacadeRouterImpl implements FacadeRouter { /** * The JNDI name of the core router */ private static final String CORE_ROUTER = "java:comp/env/CoreRouter"; private static final String CORE_ROUTER_GLOBAL_CONTEXT = "CoreRouter"; /** * The JNDI name of the command factory */ private static final String COMMAND_FACTORY = "java:comp/env/CommandFactory"; private static final String COMMAND_FACTORY_GLOBAL_CONTEXT = "CommandFactory"; private Router router; private CommandFactory commandFactory; /** * * @return */ private Logger getMyLogger() { return Logger.getLogger(AbstractFacadeRouterImpl.class); } /** * * @return */ protected synchronized Router getRouter() { if(router == null) { javax.naming.Context ctx; try { ctx = new javax.naming.InitialContext(); getMyLogger().info("Getting reference from context'" + ctx.getNameInNamespace() + "' to router using name '" + CORE_ROUTER + "'."); Object obj = ctx.lookup(CORE_ROUTER); try { router = (Router)obj; } catch (ClassCastException x) { getMyLogger().warn("Error casting object of type '" + obj.getClass().getName() + "', loaded by '" + obj.getClass().getClassLoader().getClass().getName() + "' to type '" + Router.class.getName() + "', loaded by '" + Router.class.getClassLoader().getClass().getName() + "'. \n" + "Creating proxied reference to implementation of Router."); IdentityProxyInvocationHandler<Router> classLoaderEndRun = new IdentityProxyInvocationHandler<Router>(obj, Router.class); router = (Router)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{Router.class}, classLoaderEndRun); } } catch (NamingException x) { try { ctx = ServerAdapterImpl.getSingleton().getGlobalNamingServer().getGlobalContext(); getMyLogger().info("Getting reference from the global context to router using name '" + CORE_ROUTER + "'."); Object obj = ctx.lookup(CORE_ROUTER_GLOBAL_CONTEXT); router = (Router)obj; } catch (NamingException nX1) { nX1.printStackTrace(); } } } return router; } private static String commandFactoryReferenceError = "Web applications must declare a resource to '" + COMMAND_FACTORY + "' in web.xml \n" + "and declare a resource reference in context.xml."; /** * * @return */ protected synchronized CommandFactory getCommandFactory() { if(commandFactory == null) { javax.naming.Context ctx; try { ctx = new javax.naming.InitialContext(); getMyLogger().info("Getting reference from context '" + ctx.getNameInNamespace() + "' to command factory using name '" + COMMAND_FACTORY + "'."); getMyLogger().info(JndiUtility.contextDump(ctx, "java:comp", true)); Object obj = ctx.lookup(COMMAND_FACTORY); ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { // switch the context class loader to the system class load, rather than // a web class loader, so that the casting will work. otherwise the // CommandFactory class may be loaded by the current web app class // and the cast will fail Thread.currentThread().setContextClassLoader(obj.getClass().getClassLoader()); commandFactory = (CommandFactory)obj; } catch(ClassCastException ccX) { getMyLogger().warn("Error casting object of type '" + obj.getClass().getName() + "', loaded by '" + obj.getClass().getClassLoader().getClass().getName() + "' to type '" + CommandFactory.class.getName() + "', loaded by '" + CommandFactory.class.getClassLoader().getClass().getName() + "'. \n" + "Creating proxied reference to implementation of CommandFactory."); IdentityProxyInvocationHandler<CommandFactory> classLoaderEndRun = new IdentityProxyInvocationHandler<CommandFactory>(obj, obj.getClass()); commandFactory = (CommandFactory)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{CommandFactory.class}, classLoaderEndRun); } finally { Thread.currentThread().setContextClassLoader(loader); } } catch (NamingException x) { try { getMyLogger().info( "Failed to get reference to command factory using web naming context." + "Getting reference from the global context to command factory using name '" + COMMAND_FACTORY_GLOBAL_CONTEXT + "'."); ctx = ServerAdapterImpl.getSingleton().getGlobalNamingServer().getGlobalContext(); Object obj = ctx.lookup(COMMAND_FACTORY_GLOBAL_CONTEXT); try { commandFactory = (CommandFactory)obj; } catch(ClassCastException ccX) { getMyLogger().error("Error casting object of type '" + obj.getClass().getName() + "', loaded by '" + obj.getClass().getClassLoader().getClass().getName() + "' to type '" + CommandFactory.class.getName() + "', loaded by '" + CommandFactory.class.getClassLoader().getClass().getName() + "'."); } } catch (NamingException nX1) { getMyLogger().error("Completely failed to get reference from the global context to command factory using name '" + COMMAND_FACTORY + "'.\n" + commandFactoryReferenceError ); } catch (Throwable t) { getMyLogger().error("Completely failed to get reference to command factory.\n" + commandFactoryReferenceError, t); } } } return commandFactory; } }
32.532609
149
0.674908
8dc9280b1279137ba523f3937d6baa19871850c7
9,406
package edu.msu.cme.rdp.rarefaction; import edu.msu.cme.pyro.cluster.io.RDPClustParser; import edu.msu.cme.pyro.cluster.io.RDPClustParser.ClusterSample; import edu.msu.cme.pyro.cluster.io.RDPClustParser.Cutoff; import edu.msu.cme.pyro.cluster.utils.Cluster; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; import java.util.Map; import java.util.HashMap; import java.util.Map.Entry; import java.util.Iterator; public class Rarefaction { /** * So this class is an extreme optimization on an inner for loop * * Originally this was representated by a Map<Integer, Double>, but it would result in * N^3 * 3 function calls in the calcV function per cutoff, so just think of this as a * map, where usedPValIndicies is a list of keys, and pvalues are the values (there can * and often are unused values) * * usedPValIndicies is a list of the cluster sizes and sums there of */ private static class PValues { int[] usedPValIndices; double[] pvalues; } /** * This class like PValues is an extreme optimization on a Map<Integer, Integer> * in this case however there is no key/value list, instead there are two parallel arrays * so clusterSizes[i] is the size of an arbitrary cluster and clustersOfSize[i] is the * number of clusters of that size * * Also we keep track of the largest cluster, since we'll need it to initialize the pvalues * (largest number of possible pvals is 2 * largest cluster size + 1), and it's practically free * to calculate that value while mapping the cluster sizes */ private static class ClusterCounts { int[] clusterSizes; int[] clustersOfSize; int largestCluster = 0; } public static Map<ClusterSample, List<RarefactionResult>> doRarefaction(RDPClustParser parser) throws IOException { Map<ClusterSample, List<RarefactionResult>> resultsMap = new HashMap(); for (ClusterSample clusterSample : parser.getClusterSamples()) { resultsMap.put(clusterSample, new ArrayList()); } Cutoff c; while((c = parser.readNextCutoff()) != null) { Map<ClusterSample, RarefactionResult> result = cutoffRarefaction(parser.getClusterSamples(), c); for (ClusterSample clusterSample : result.keySet()) { resultsMap.get(clusterSample).add(result.get(clusterSample)); } } return resultsMap; } private static Map<ClusterSample, RarefactionResult> cutoffRarefaction(List<ClusterSample> samples, Cutoff cutoff) { double distance = Double.valueOf(cutoff.getCutoff()); Map<ClusterSample, RarefactionResult> ret = new HashMap(); for (ClusterSample sample : samples) { int numSeqsInSample = sample.getSeqs(); double[] eValues = new double[numSeqsInSample + 1]; double[] vValues = new double[numSeqsInSample + 1]; List<Cluster> clusters = cutoff.getClusters().get(sample.getName()); for (Iterator<Cluster> iterator = clusters.listIterator(); iterator.hasNext();) { Cluster c = iterator.next(); if (c.getNumberOfSeqs() == 0) { iterator.remove(); } } ClusterCounts clusterSizeCounts = mapClusterSizes(clusters); PValues pvals = initializePValues(clusterSizeCounts); long p = 0, e = 0, v = 0; for (int i = 1; i <= numSeqsInSample; i++) { updatePValues(i, numSeqsInSample, pvals); eValues[i] = calcE(clusterSizeCounts, pvals); vValues[i] = calcV(clusterSizeCounts, pvals, clusters); } ret.put(sample, new RarefactionResult(distance, eValues, vValues)); } return ret; } /** * This function maps the size of clusters to the numbers of clusters of that size * * The result is a hella optimized class * * @see ClsuterCounts * * @param oneSampleCutoffClusters * @return */ private static ClusterCounts mapClusterSizes(List<Cluster> oneSampleCutoffClusters) { Map<Integer, Integer> clusterSizeCounts = new HashMap(); ClusterCounts ret = new ClusterCounts(); for (Cluster cluster : oneSampleCutoffClusters) { Integer count = clusterSizeCounts.get(cluster.getNumberOfSeqs()); if (count == null) { count = 0; } if (cluster.getNumberOfSeqs() > ret.largestCluster) { ret.largestCluster = cluster.getNumberOfSeqs(); } clusterSizeCounts.put(cluster.getNumberOfSeqs(), count + 1); } ret.clusterSizes = new int[clusterSizeCounts.size()]; ret.clustersOfSize = new int[clusterSizeCounts.size()]; int index = 0; for (Entry<Integer, Integer> entry : clusterSizeCounts.entrySet()) { ret.clusterSizes[index] = entry.getKey(); ret.clustersOfSize[index] = entry.getValue(); index++; } return ret; } private static PValues initializePValues(ClusterCounts clusterSizeCounts) { PValues ret = new PValues(); ret.pvalues = new double[clusterSizeCounts.largestCluster * 2 + 1]; Set<Integer> usedPValues = new HashSet(); for (int i = 0; i < clusterSizeCounts.clusterSizes.length; i++) { int countI = clusterSizeCounts.clusterSizes[i]; usedPValues.add(countI); ret.pvalues[countI] = 1f; for (int j = i; j < clusterSizeCounts.clusterSizes.length; j++) { int countK = clusterSizeCounts.clusterSizes[j] + countI; usedPValues.add(countK); ret.pvalues[countK] = 1f; } } ret.usedPValIndices = new int[usedPValues.size()]; int index = 0; for (int usedPValue : usedPValues) { ret.usedPValIndices[index++] = usedPValue; } return ret; } private static void updatePValues(double n, int totalSeqCount, PValues pvals) { double denominator = 1.0d / (totalSeqCount - n + 1.0d); for (int H : pvals.usedPValIndices) { double pval = pvals.pvalues[H]; pval *= (totalSeqCount - (double) H - n + 1.0d) * denominator; pvals.pvalues[H] = pval; } } private static double calcE(ClusterCounts clusterSizeToCounts, PValues pvals) { double E = 0; for (int index = 0; index < clusterSizeToCounts.clusterSizes.length; index++) { int clusterSize = clusterSizeToCounts.clusterSizes[index]; int clustersOfSize = clusterSizeToCounts.clustersOfSize[index]; E += clustersOfSize * (1.0d - pvals.pvalues[clusterSize]); } return E; } private static double calcV(ClusterCounts clusterSizeToCounts, PValues pvals, List<Cluster> clusters) { double V = 0; for (int i = 0; i < clusterSizeToCounts.clusterSizes.length; i++) { int sizeI = clusterSizeToCounts.clusterSizes[i]; int countI = clusterSizeToCounts.clustersOfSize[i]; for (int j = 0; j < clusterSizeToCounts.clusterSizes.length; j++) { int sizeJ = clusterSizeToCounts.clusterSizes[j]; int countJ = clusterSizeToCounts.clustersOfSize[j]; if (sizeI != sizeJ) { V += countI * countJ * (pvals.pvalues[sizeI + sizeJ] - pvals.pvalues[sizeI] * pvals.pvalues[sizeJ]); } else if (sizeI > 1) { // use to remove possibility that count_i > 1/2N because pValues[>N] may go to infinity V += countI * (countI - 1) * (pvals.pvalues[sizeI + sizeJ] - pvals.pvalues[sizeI] * pvals.pvalues[sizeJ]); } } } for (Cluster cluster : clusters) { double pval = pvals.pvalues[cluster.getNumberOfSeqs()]; V += pval * (1 - pval); } return V; } public static double getConf(double V) { double conf = 0.0; if (V > 0) { // can be very small negative due to rounding error conf = Math.sqrt(V) * 1.96d; } return conf; } public static void main(String[] args) throws IOException { String usage = "Usage:java Rarefaction in.clust output_dir [plot]"; if (args.length != 2 && args.length != 3) { throw new IllegalArgumentException(usage); } File clusterFile = new File(args[0]); File outputDir = new File(args[1]); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { throw new IOException("Failed to make output directory " + outputDir); } } else if (!outputDir.exists()) { } boolean plot = args.length == 3; RDPClustParser parser = new RDPClustParser(new File(args[0])); Map<ClusterSample, List<RarefactionResult>> resultsMap = doRarefaction(parser); parser.close(); RarefactionWriter.writeRarefactionResults(resultsMap, outputDir); if (plot) { RarefactionPlotter.plotRarefaction(resultsMap, outputDir); } } }
36.038314
127
0.611099
83f1d2b352922120572bc705f61d4777e619367c
16,734
package uk.gov.pay.connector.charge.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import uk.gov.pay.commons.api.json.ApiResponseDateTimeSerializer; import uk.gov.pay.commons.api.json.ExternalMetadataSerialiser; import uk.gov.pay.commons.model.SupportedLanguage; import uk.gov.pay.commons.model.charge.ExternalMetadata; import uk.gov.pay.connector.charge.model.builder.AbstractChargeResponseBuilder; import uk.gov.pay.connector.charge.model.domain.PersistedCard; import uk.gov.pay.connector.common.model.api.ExternalTransactionState; import uk.gov.pay.connector.util.DateTimeUtils; import uk.gov.pay.connector.wallets.WalletType; import java.net.URI; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; import java.util.Objects; import static com.fasterxml.jackson.annotation.JsonInclude.Include; import static uk.gov.pay.commons.model.ApiResponseDateTimeFormatter.ISO_INSTANT_MILLISECOND_PRECISION; @JsonInclude(Include.NON_NULL) @JsonFormat(shape = JsonFormat.Shape.OBJECT) public class ChargeResponse { @JsonProperty("links") private List<Map<String, Object>> dataLinks; @JsonProperty("charge_id") private String chargeId; @JsonProperty private Long amount; @JsonProperty private ExternalTransactionState state; @JsonProperty("card_brand") private String cardBrand; @JsonProperty("gateway_transaction_id") private String gatewayTransactionId; @JsonProperty("return_url") private String returnUrl; @JsonProperty("email") private String email; @JsonProperty private String description; @JsonProperty @JsonSerialize(using = ToStringSerializer.class) private ServicePaymentReference reference; @JsonProperty("payment_provider") private String providerName; @JsonProperty("created_date") @JsonSerialize(using = ApiResponseDateTimeSerializer.class) private ZonedDateTime createdDate; @JsonProperty("refund_summary") private RefundSummary refundSummary; @JsonProperty("settlement_summary") private SettlementSummary settlementSummary; @JsonProperty("auth_3ds_data") private Auth3dsData auth3dsData; @JsonProperty("card_details") protected PersistedCard cardDetails; @JsonProperty @JsonSerialize(using = ToStringSerializer.class) private SupportedLanguage language; @JsonProperty("delayed_capture") private boolean delayedCapture; @JsonProperty("corporate_card_surcharge") private Long corporateCardSurcharge; @JsonProperty("fee") private Long fee; @JsonProperty("total_amount") private Long totalAmount; @JsonProperty("net_amount") private Long netAmount; @JsonProperty("wallet_type") private WalletType walletType; @JsonProperty("metadata") @JsonSerialize(using = ExternalMetadataSerialiser.class) private ExternalMetadata externalMetadata; ChargeResponse(AbstractChargeResponseBuilder<?, ? extends ChargeResponse> builder) { this.dataLinks = builder.getLinks(); this.chargeId = builder.getChargeId(); this.amount = builder.getAmount(); this.state = builder.getState(); this.cardBrand = builder.getCardBrand(); this.gatewayTransactionId = builder.getGatewayTransactionId(); this.returnUrl = builder.getReturnUrl(); this.description = builder.getDescription(); this.reference = builder.getReference(); this.providerName = builder.getProviderName(); this.createdDate = builder.getCreatedDate(); this.email = builder.getEmail(); this.refundSummary = builder.getRefundSummary(); this.settlementSummary = builder.getSettlementSummary(); this.cardDetails = builder.getCardDetails(); this.auth3dsData = builder.getAuth3dsData(); this.language = builder.getLanguage(); this.delayedCapture = builder.isDelayedCapture(); this.corporateCardSurcharge = builder.getCorporateCardSurcharge(); this.fee = builder.getFee(); this.totalAmount = builder.getTotalAmount(); this.netAmount = builder.getNetAmount(); this.walletType = builder.getWalletType(); this.externalMetadata = builder.getExternalMetadata(); } public List<Map<String, Object>> getDataLinks() { return dataLinks; } public String getChargeId() { return chargeId; } public Long getAmount() { return amount; } public ExternalTransactionState getState() { return state; } public String getCardBrand() { return cardBrand; } public String getGatewayTransactionId() { return gatewayTransactionId; } public String getReturnUrl() { return returnUrl; } public String getEmail() { return email; } public String getDescription() { return description; } public ServicePaymentReference getReference() { return reference; } public String getProviderName() { return providerName; } public RefundSummary getRefundSummary() { return refundSummary; } public SettlementSummary getSettlementSummary() { return settlementSummary; } public Auth3dsData getAuth3dsData() { return auth3dsData; } public PersistedCard getCardDetails() { return cardDetails; } public SupportedLanguage getLanguage() { return language; } public boolean getDelayedCapture() { return delayedCapture; } public Long getCorporateCardSurcharge() { return corporateCardSurcharge; } public Long getFee() { return fee; } public Long getTotalAmount() { return totalAmount; } public Long getNetAmount() { return netAmount; } public WalletType getWalletType() { return walletType; } public ExternalMetadata getExternalMetadata() { return externalMetadata; } public URI getLink(String rel) { return dataLinks.stream() .filter(map -> rel.equals(map.get("rel"))) .findFirst() .map(link -> (URI) link.get("href")) .get(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ChargeResponse that = (ChargeResponse) o; return delayedCapture == that.delayedCapture && Objects.equals(dataLinks, that.dataLinks) && Objects.equals(chargeId, that.chargeId) && Objects.equals(amount, that.amount) && Objects.equals(state, that.state) && Objects.equals(cardBrand, that.cardBrand) && Objects.equals(gatewayTransactionId, that.gatewayTransactionId) && Objects.equals(returnUrl, that.returnUrl) && Objects.equals(email, that.email) && Objects.equals(description, that.description) && Objects.equals(reference, that.reference) && Objects.equals(providerName, that.providerName) && Objects.equals(createdDate, that.createdDate) && Objects.equals(refundSummary, that.refundSummary) && Objects.equals(settlementSummary, that.settlementSummary) && Objects.equals(auth3dsData, that.auth3dsData) && Objects.equals(cardDetails, that.cardDetails) && language == that.language && Objects.equals(corporateCardSurcharge, that.corporateCardSurcharge) && Objects.equals(totalAmount, that.totalAmount) && walletType == that.walletType; } @Override public int hashCode() { return Objects.hash(dataLinks, chargeId, amount, state, cardBrand, gatewayTransactionId, returnUrl, email, description, reference, providerName, createdDate, refundSummary, settlementSummary, auth3dsData, cardDetails, language, delayedCapture, corporateCardSurcharge, totalAmount, walletType); } @Override public String toString() { // Some services put PII in the description, so don’t include it in the stringification return "ChargeResponse{" + "dataLinks=" + dataLinks + ", chargeId='" + chargeId + '\'' + ", amount=" + amount + ", state=" + state + ", cardBrand='" + cardBrand + '\'' + ", gatewayTransactionId='" + gatewayTransactionId + '\'' + ", returnUrl='" + returnUrl + '\'' + ", reference='" + reference + '\'' + ", providerName='" + providerName + '\'' + ", createdDate=" + createdDate + ", refundSummary=" + refundSummary + ", settlementSummary=" + settlementSummary + ", auth3dsData=" + auth3dsData + ", language=" + language + ", delayedCapture=" + delayedCapture + ", corporateCardSurcharge=" + corporateCardSurcharge + ", totalAmount=" + totalAmount + ", walletType=" + walletType + '}'; } public static class ChargeResponseBuilder extends AbstractChargeResponseBuilder<ChargeResponseBuilder, ChargeResponse> { @Override protected ChargeResponseBuilder thisObject() { return this; } @Override public ChargeResponse build() { return new ChargeResponse(this); } } public static ChargeResponseBuilder aChargeResponseBuilder() { return new ChargeResponseBuilder(); } @JsonFormat(shape = JsonFormat.Shape.OBJECT) public static class RefundSummary { @JsonProperty("status") private String status; @JsonProperty("user_external_id") private String userExternalId; @JsonProperty("amount_available") private Long amountAvailable; @JsonProperty("amount_submitted") private Long amountSubmitted; public void setStatus(String status) { this.status = status; } public void setAmountAvailable(Long amountAvailable) { this.amountAvailable = amountAvailable; } public void setAmountSubmitted(Long amountSubmitted) { this.amountSubmitted = amountSubmitted; } public String getUserExternalId() { return userExternalId; } public void setUserExternalId(String userExternalId) { this.userExternalId = userExternalId; } public Long getAmountAvailable() { return amountAvailable; } public Long getAmountSubmitted() { return amountSubmitted; } public String getStatus() { return status; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RefundSummary that = (RefundSummary) o; if (!status.equals(that.status)) { return false; } if (userExternalId != null ? !userExternalId.equals(that.userExternalId) : that.userExternalId != null) { return false; } if (amountAvailable != null ? !amountAvailable.equals(that.amountAvailable) : that.amountAvailable != null) { return false; } return amountSubmitted != null ? amountSubmitted.equals(that.amountSubmitted) : that.amountSubmitted == null; } @Override public int hashCode() { int result = status.hashCode(); result = 31 * result + (userExternalId != null ? userExternalId.hashCode() : 0); result = 31 * result + (amountAvailable != null ? amountAvailable.hashCode() : 0); result = 31 * result + (amountSubmitted != null ? amountSubmitted.hashCode() : 0); return result; } @Override public String toString() { return "RefundSummary{" + "status='" + status + '\'' + "userExternalId='" + userExternalId + '\'' + ", amountAvailable=" + amountAvailable + ", amountSubmitted=" + amountSubmitted + '}'; } } @JsonFormat(shape = JsonFormat.Shape.OBJECT) public static class SettlementSummary { private ZonedDateTime captureSubmitTime, capturedTime; public void setCaptureSubmitTime(ZonedDateTime captureSubmitTime) { this.captureSubmitTime = captureSubmitTime; } @JsonProperty("capture_submit_time") public String getCaptureSubmitTime() { return (captureSubmitTime != null) ? ISO_INSTANT_MILLISECOND_PRECISION.format(captureSubmitTime) : null; } public void setCapturedTime(ZonedDateTime capturedTime) { this.capturedTime = capturedTime; } @JsonProperty("captured_date") public String getCapturedDate() { return (capturedTime != null) ? DateTimeUtils.toUTCDateString(capturedTime) : null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SettlementSummary that = (SettlementSummary) o; if (captureSubmitTime != null ? !captureSubmitTime.equals(that.captureSubmitTime) : that.captureSubmitTime != null) return false; return capturedTime != null ? capturedTime.equals(that.capturedTime) : that.capturedTime == null; } @Override public int hashCode() { int result = captureSubmitTime != null ? captureSubmitTime.hashCode() : 0; result = 31 * result + (capturedTime != null ? capturedTime.hashCode() : 0); return result; } @Override public String toString() { return "SettlementSummary{" + ", captureSubmitTime=" + captureSubmitTime + ", capturedTime=" + capturedTime + '}'; } } @JsonInclude(Include.NON_NULL) @JsonFormat(shape = JsonFormat.Shape.OBJECT) public static class Auth3dsData { @JsonProperty("paRequest") private String paRequest; @JsonProperty("issuerUrl") private String issuerUrl; @JsonProperty("htmlOut") private String htmlOut; @JsonProperty("md") private String md; public String getPaRequest() { return paRequest; } public void setPaRequest(String paRequest) { this.paRequest = paRequest; } public String getIssuerUrl() { return issuerUrl; } public void setIssuerUrl(String issuerUrl) { this.issuerUrl = issuerUrl; } public String getHtmlOut() { return htmlOut; } public void setHtmlOut(String htmlOut) { this.htmlOut = htmlOut; } public void setMd(String md) { this.md = md; } public String getMd() { return md; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Auth3dsData that = (Auth3dsData) o; return Objects.equals(paRequest, that.paRequest) && Objects.equals(issuerUrl, that.issuerUrl) && Objects.equals(htmlOut, that.htmlOut) && Objects.equals(md, that.md); } @Override public int hashCode() { return Objects.hash(paRequest, issuerUrl, htmlOut, md); } @Override public String toString() { return "Auth3dsData{" + "issuerUrl='" + issuerUrl + '\'' + ", htmlOut='" + htmlOut + '\'' + ", md='" + md + '\'' + '}'; } } }
31.693182
127
0.609956
8552db8266ad82b44e69847d12c5bbde50401856
5,872
package com.example.cartoon.passwordmanager.PersonalInformation.login; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.format.Formatter; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.example.cartoon.passwordmanager.BaseActivity; import com.example.cartoon.passwordmanager.Password.Main.Main; import com.example.cartoon.passwordmanager.R; import com.example.cartoon.passwordmanager.PersonalInformation.Register.Register; import com.example.cartoon.passwordmanager.PersonalInformation.RevampPassword.InformationRevampPassword; import com.example.cartoon.passwordmanager.data.MyDatabaseHelper; import com.example.cartoon.passwordmanager.util.PasswordManagerApplication; /** * Created by cartoon on 2018/1/31. */ public class Login extends BaseActivity<LoginPresenter> implements ILoginContract.View, View.OnClickListener{ private ImageView passwordForShow[]; private Button inputPassword[]; private int flag; //控制输入的密码个数 private StringBuilder password; //最终用户输入的密码 private Intent intent; private static final String TAG = "Activity2"; @Override protected LoginPresenter initPresent(){ MyDatabaseHelper helper=new MyDatabaseHelper(this,"PasswordManager.db",null,1); helper.getWritableDatabase(); return new LoginPresenter(this); } @Override protected int getLayout(){ return R.layout.login; } @Override protected void initView(){ passwordForShow=new ImageView[6]; inputPassword=new Button[12]; passwordForShow[0]=findViewById(R.id.loginPassword1); passwordForShow[1]=findViewById(R.id.loginPassword2); passwordForShow[2]=findViewById(R.id.loginPassword3); passwordForShow[3]=findViewById(R.id.loginPassword4); passwordForShow[4]=findViewById(R.id.loginPassword5); passwordForShow[5]=findViewById(R.id.loginPassword6); inputPassword[0]=findViewById(R.id.loginInputPassword0); inputPassword[1]=findViewById(R.id.loginInputPassword1); inputPassword[2]=findViewById(R.id.loginInputPassword2); inputPassword[3]=findViewById(R.id.loginInputPassword3); inputPassword[4]=findViewById(R.id.loginInputPassword4); inputPassword[5]=findViewById(R.id.loginInputPassword5); inputPassword[6]=findViewById(R.id.loginInputPassword6); inputPassword[7]=findViewById(R.id.loginInputPassword7); inputPassword[8]=findViewById(R.id.loginInputPassword8); inputPassword[9]=findViewById(R.id.loginInputPassword9); inputPassword[10]=findViewById(R.id.loginInputPasswordForgetPassword); inputPassword[11]=findViewById(R.id.loginInputPasswordDeletePassword); } @Override protected void onPrepare(){ flag=-1; password=new StringBuilder(); for(int i=0;i<12;i++){ inputPassword[i].setOnClickListener(this); } } @Override public void showToast(String code){ Toast.makeText(this,code,Toast.LENGTH_SHORT).show(); } @Override public void onClick(View view){ switch (view.getId()){ case R.id.loginInputPassword0:{ handleClick("0"); break; } case R.id.loginInputPassword1:{ handleClick("1"); break; } case R.id.loginInputPassword2:{ handleClick("2"); break; } case R.id.loginInputPassword3:{ handleClick("3"); break; } case R.id.loginInputPassword4:{ handleClick("4"); break; } case R.id.loginInputPassword5:{ handleClick("5"); break; } case R.id.loginInputPassword6:{ handleClick("6"); break; } case R.id.loginInputPassword7:{ handleClick("7"); break; } case R.id.loginInputPassword8:{ handleClick("8"); break; } case R.id.loginInputPassword9:{ handleClick("9"); break; } case R.id.loginInputPasswordDeletePassword:{ handleClick("-1"); break; } case R.id.loginInputPasswordForgetPassword:{ handleClick("-2"); break; } } } @Override public void handleClick(String password){ if(password.equals("-2")){ intent=new Intent(this,InformationRevampPassword.class); startActivity(intent); finish(); } else{ if(password.equals("-1")){ if(flag!=-1){ this.password.deleteCharAt(flag); passwordForShow[flag--].setImageResource(0); } } else{ this.password.append(password); passwordForShow[++flag].setImageResource(R.drawable.password); } } if(flag==5){ basePresenter.contrastInformation(this.password.toString()); } } @Override public void intentToMain(){ intent=new Intent(this, Main.class); startActivity(intent); finish(); } @Override public void intentToRegister(String password){ intent=new Intent(this, Register.class); intent.putExtra("passwordFromLogin",password); startActivity(intent); finish(); } }
33.942197
109
0.614101
6b01a05d2351addec8113c61ed43ff8c83f2c34e
6,161
package my.test.myapplication.activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Message; import android.view.View; import android.webkit.GeolocationPermissions; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.ProgressBar; import com.bumptech.glide.Glide; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.ycbjie.webviewlib.X5WebView; import androidx.appcompat.app.AppCompatActivity; import my.test.myapplication.R; import my.test.myapplication.utils.NetUtil; public class NewsDetailActivity extends AppCompatActivity { private WebView webView; private ProgressBar webProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_newsdetail); ImageView imageView =findViewById(R.id.toolbar_layout); Glide.with(this).load(getIntent().getStringExtra("img")).into( imageView); webView=findViewById(R.id.webview); webProgress=findViewById(R.id.web_progress); // webView.setWebViewClient(webViewClient); // YcX5WebChromeClient webChromeClient = new YcX5WebChromeClient(webView,this); webView.setWebChromeClient(chromeClient); webviewSetting(); webView.loadUrl(getIntent().getStringExtra("url")); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) // .setAction("Action", null).show(); shareToMore(); } }); } private void shareToMore() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); String title = getIntent().getStringExtra("title"); shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_link_format, title, getIntent().getStringExtra("url"))); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_to))); } WebViewClient webViewClient = new WebViewClient() { /** * 多页面在同一个WebView中打开,就是不新建activity或者调用系统浏览器打开 */ @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { //view.loadUrl(url); //Toast.makeText(WebViewActivity.this, "没有权限的数据", Toast.LENGTH_SHORT).show(); return false; } }; WebChromeClient chromeClient=new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); webProgress.setProgress(newProgress); if (newProgress==100){ webProgress.setVisibility(View.GONE); } } @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; transport.setWebView(view); resultMsg.sendToTarget(); return true; } @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } @Override public void onGeolocationPermissionsHidePrompt() { super.onGeolocationPermissionsHidePrompt(); } @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); super.onGeolocationPermissionsShowPrompt(origin, callback); } }; private void webviewSetting() { WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true);//支持js //设置自适应屏幕 webSettings.setUseWideViewPort(true); webSettings.setLoadWithOverviewMode(true); //webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。 // webSettings.setBuiltInZoomControls(true); //设置可以缩放 //webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件 //若上面是false,则该WebView不可缩放,这个不管设置什么都不能缩放。 //webSettings.setTextZoom(2);//设置文本的缩放倍数,默认为 100 //webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局 // webSettings.supportMultipleWindows(); //多窗口 //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存 //webSettings.setAllowFileAccess(true); //设置可以访问文件 //webSettings.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点 //webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口 webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片 webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式 //webSettings.setStandardFontFamily("");//设置 WebView 的字体,默认字体为 "sans-serif" webSettings.setDefaultFontSize(14);//设置 WebView 字体的大小,默认大小为 16 //webSettings.setMinimumFontSize(12);//设置 WebView 支持的最小字体大小,默认为 8 if (NetUtil.getNetWorkState(this)!=-1) { webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } else { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); } webSettings.setDomStorageEnabled(true);// 开启 DOM storage API 功能 // webSettings.setDatabaseEnabled(true);//开启 database storage API 功能 webSettings.setAppCacheEnabled(true);//开启 Application Caches 功能 String cacheDirPath = getFilesDir().getAbsolutePath() + "news_webviewcache"; webSettings.setAppCachePath(cacheDirPath); // moreWin(webSettings); } }
44.323741
113
0.69453
bd7d2429e2ed8946798a53849c166ab794cf6689
3,188
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.model.task; import com.intellij.openapi.externalSystem.model.ProjectSystemId; import com.intellij.openapi.externalSystem.model.project.AbstractExternalEntityData; import com.intellij.openapi.externalSystem.model.project.ExternalConfigPathAware; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Container for external system task information. * * @author Denis Zhdanov */ public class TaskData extends AbstractExternalEntityData implements ExternalConfigPathAware, Comparable<TaskData> { private static final long serialVersionUID = 1L; @NotNull private final String myName; @Nullable private final String myDescription; @NotNull private final String myLinkedExternalProjectPath; @Nullable private String myGroup; @Nullable private String myType; private boolean myInherited; public TaskData(@NotNull ProjectSystemId owner, @NotNull String name, @NotNull String path, @Nullable String description) { super(owner); myName = name; myLinkedExternalProjectPath = path; myDescription = description; } @NotNull public String getName() { return myName; } @Override @NotNull public String getLinkedExternalProjectPath() { return myLinkedExternalProjectPath; } @Nullable public String getDescription() { return myDescription; } @Nullable public String getGroup() { return myGroup; } public void setGroup(@Nullable String group) { myGroup = group; } @Nullable public String getType() { return myType; } public void setType(@Nullable String type) { myType = type; } public boolean isInherited() { return myInherited; } public void setInherited(boolean inherited) { myInherited = inherited; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + myName.hashCode(); result = 31 * result + (myGroup != null ? myGroup.hashCode() : 0); result = 31 * result + myLinkedExternalProjectPath.hashCode(); result = 31 * result + (myInherited ? 1 : 0); result = 31 * result + (myDescription != null ? myDescription.hashCode() : 0); return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; TaskData data = (TaskData)o; if (myInherited != data.myInherited) return false; if (!myName.equals(data.myName)) return false; if (myGroup != null ? !myGroup.equals(data.myGroup) : data.myGroup != null) return false; if (!myLinkedExternalProjectPath.equals(data.myLinkedExternalProjectPath)) return false; if (myDescription != null ? !myDescription.equals(data.myDescription) : data.myDescription != null) return false; return true; } @Override public int compareTo(@NotNull TaskData that) { return myName.compareTo(that.getName()); } @Override public String toString() { return myName; } }
27.964912
140
0.716437
1a2f6db21c60e54d9c70545b76fc8bac0309cf1d
898
package com.fishercoder.common.classes; import java.util.ArrayList; import java.util.List; /** * Created by fishercoder1534 on 9/30/16. */ public class UndirectedGraphNode { public int label; public List<UndirectedGraphNode> neighbors; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UndirectedGraphNode that = (UndirectedGraphNode) o; if (label != that.label) return false; return neighbors != null ? neighbors.equals(that.neighbors) : that.neighbors == null; } @Override public int hashCode() { int result = label; result = 31 * result + (neighbors != null ? neighbors.hashCode() : 0); return result; } public UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } }
27.212121
102
0.644766
b620c6998558f353312f77e1f39f7b96ddb865fa
8,196
package org.embulk.input; import static java.util.Locale.ENGLISH; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.embulk.config.ConfigException; import org.embulk.input.jdbc.AbstractJdbcInputPlugin; import org.embulk.input.tester.EmbulkPluginTester; import org.embulk.input.tester.EmbulkPluginTester.PluginDefinition; import org.yaml.snakeyaml.Yaml; import com.google.common.io.Files; public abstract class AbstractJdbcInputPluginTest { private static final String CONFIG_FILE_NAME = "tests.yml"; protected boolean enabled; // TODO:destroy EmbulkPluginTester after test protected EmbulkPluginTester tester = new EmbulkPluginTester(); private String pluginName; private Map<String, ?> testConfigurations; protected AbstractJdbcInputPluginTest() { try { prepare(); } catch (SQLException e) { throw new RuntimeException(e); } } protected abstract void prepare() throws SQLException; private Map<String, ?> getTestConfigs() { if (testConfigurations == null) { for (PluginDefinition pluginDefinition : tester.getPlugins()) { if (AbstractJdbcInputPlugin.class.isAssignableFrom(pluginDefinition.impl)) { pluginName = pluginDefinition.name; break; } } Yaml yaml = new Yaml(); File configFile = new File(CONFIG_FILE_NAME); if (!configFile.exists()) { configFile = new File("../" + CONFIG_FILE_NAME); if (!configFile.exists()) { throw new ConfigException(String.format(ENGLISH, "\"%s\" doesn't exist.", CONFIG_FILE_NAME)); } } try { InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile), Charset.forName("UTF8")); try { Map<String, ?> allTestConfigs = (Map<String, ?>)yaml.load(reader); if (!allTestConfigs.containsKey(pluginName)) { throw new ConfigException(String.format(ENGLISH, "\"%s\" doesn't contain \"%s\" element.", CONFIG_FILE_NAME, pluginName)); } testConfigurations = (Map<String, ?>)allTestConfigs.get(pluginName); } finally { reader.close(); } } catch (IOException e) { throw new RuntimeException(e); } } return testConfigurations; } protected Object getTestConfig(String name, boolean required) { Map<String, ?> testConfigs = getTestConfigs(); if (!testConfigs.containsKey(name)) { if (required) { throw new ConfigException(String.format(ENGLISH, "\"%s\" element in \"%s\" doesn't contain \"%s\" element.", pluginName, CONFIG_FILE_NAME, name)); } return null; } return testConfigs.get(name); } protected Object getTestConfig(String name) { return getTestConfig(name, true); } protected String getHost() { return (String)getTestConfig("host"); } protected int getPort() { return (Integer)getTestConfig("port"); } protected String getUser() { return (String)getTestConfig("user"); } protected String getPassword() { return (String)getTestConfig("password"); } protected String getDatabase() { return (String)getTestConfig("database"); } protected void dropTable(String table) throws SQLException { String sql = String.format("DROP TABLE %s", table); executeSQL(sql, true); } protected List<List<Object>> select(String table) throws SQLException { try (Connection connection = connect()) { try (Statement statement = connection.createStatement()) { List<List<Object>> rows = new ArrayList<List<Object>>(); String sql = String.format("SELECT * FROM %s", table); System.out.println(sql); try (ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { List<Object> row = new ArrayList<Object>(); for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) { row.add(getValue(resultSet, i)); } rows.add(row); } } // cannot sort by CLOB, so sort by Java Collections.sort(rows, new Comparator<List<Object>>() { @Override public int compare(List<Object> o1, List<Object> o2) { return o1.toString().compareTo(o2.toString()); } }); return rows; } } } protected Object getValue(ResultSet resultSet, int index) throws SQLException { return resultSet.getObject(index); } protected void executeSQL(String sql) throws SQLException { executeSQL(sql, false); } protected void executeSQL(String sql, boolean ignoreError) throws SQLException { if (!enabled) { return; } try (Connection connection = connect()) { try { connection.setAutoCommit(true); try (Statement statement = connection.createStatement()) { System.out.println(String.format("Execute SQL : \"%s\".", sql)); statement.execute(sql); } } catch (SQLException e) { if (!ignoreError) { throw e; } } } } protected void test(String ymlPath) throws Exception { if (!enabled) { return; } tester.run(convertYml(ymlPath)); } protected String convertYml(String ymlName) throws Exception { StringBuilder builder = new StringBuilder(); Pattern pathPrefixPattern = Pattern.compile("^ *path(_prefix)?: '(.*)'$"); for (String line : Files.readLines(convertPath(ymlName), Charset.forName("UTF8"))) { line = convertYmlLine(line); Matcher matcher = pathPrefixPattern.matcher(line); if (matcher.matches()) { int group = 2; builder.append(line.substring(0, matcher.start(group))); builder.append(convertPath(matcher.group(group)).getAbsolutePath()); builder.append(line.substring(matcher.end(group))); } else { builder.append(line); } builder.append(System.lineSeparator()); } return builder.toString(); } protected String convertYmlLine(String line) { line = line.replaceAll("#host#", getHost()); line = line.replaceAll("#port#", Integer.toString(getPort())); line = line.replaceAll("#database#", getDatabase()); line = line.replaceAll("#user#", getUser()); line = line.replaceAll("#password#", getPassword()); return line; } protected File convertPath(String name) throws URISyntaxException { return new File(getClass().getResource(name).toURI()); } protected List<String> read(String path) throws IOException { return Files.readLines(new File(path), Charset.forName("UTF8")); } protected abstract Connection connect() throws SQLException; }
32.141176
124
0.571742
33f463e8e8140e2cb16e69c4b45ca7d2c9e83a24
983
package app.views.page; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; public class PageController extends MouseAdapter implements MouseMotionListener { private PageView view; public PageController(PageView view) { this.view = view; } @Override public void mousePressed(MouseEvent e) { view.getStateManager().getCurrentState().onMousePressed(e); } @Override public void mouseReleased(MouseEvent e) { view.getStateManager().getCurrentState().onMouseReleased(e); } @Override public void mouseDragged(MouseEvent e ){ view.getStateManager().getCurrentState().onMouseDragged(e); } @Override public void mouseMoved(MouseEvent e) { view.getStateManager().getCurrentState().onMouseMoved(e); } }
25.868421
81
0.724313
66161cfb1b3fe3414eb263b2ef4a5b762e1dc944
611
package org.elastos.wallet.ela.ui.crvote.bean; public class FindListBean { private int resouceId; private String upText; private String downText; public int getResouceId() { return resouceId; } public void setResouceId(int resouceId) { this.resouceId = resouceId; } public String getUpText() { return upText; } public void setUpText(String upText) { this.upText = upText; } public String getDownText() { return downText; } public void setDownText(String downText) { this.downText = downText; } }
19.09375
46
0.628478
4293a208831c347ed73188de6b7057610679ad6f
896
package semanticAnalyzer.types; public class Array implements Type { Type subtype; public Array(Type S) { this.subtype=S; } public Type getSubtype(){ return this.subtype; } @Override public int getSize() { // TODO Auto-generated method stub return 4; } @Override public String infoString() { // TODO Auto-generated method stub return "ARRAY"+" "+subtype.infoString(); } @Override public boolean equivalent(Type otherType) { if(otherType instanceof Array){ Array otherArray=(Array)otherType; // System.out.println(subtype); // System.out.println(otherArray.getSubtype()); // System.out.println(subtype.equivalent(otherArray.getSubtype())); return subtype.equivalent(otherArray.getSubtype()); } return false; } @Override public Type getConcreteType() { Type concreteSubtype=subtype.getConcreteType(); return new Array(concreteSubtype); } }
20.363636
69
0.719866
882a5cf407cd7fe9601b587ab5e07c255ceb9732
2,414
/* * Copyright 2005--2008 Helsinki Institute for Information Technology * * This file is a part of Fuego middleware. Fuego middleware is free software; you can redistribute * it and/or modify it under the terms of the MIT license, included as the file MIT-LICENSE in the * Fuego middleware source distribution. If you did not receive the MIT license with the * distribution, write to the Fuego Core project at [email protected]. */ package fc.xml.xas.index; import fc.xml.xas.FragmentPointer; import fc.xml.xas.MutableFragmentPointer; import fc.xml.xas.Pointer; import fc.xml.xas.XasFragment; /** * A document that supports mutations while preserving pointers to itself. Any pointers acquired * from such a document with {@link #pointer()} or {@link #query(int[])} implement * {@link fc.xml.xas.MutablePointer} so they can be used to mutate the document. Also, any such * pointers will always follow their pointed-to item throughout these changes (note that a delete * may invalidate such a pointer). */ public class VersionedDocument extends Document { private VersionNode version = new VersionNode(); public VersionedDocument(XasFragment fragment) { super(fragment); } public Pointer pointer() { return new VersionedPointer(this, DeweyKey.initial()); } @Override protected Pointer constructPointer(DeweyKey key, MutableFragmentPointer pointer) { return new VersionedPointer(this, key, pointer); } VersionNode getVersion() { return version; } void insertAfter(DeweyKey key, FragmentPointer pointer) { version = version.insertAfter(key, pointer); } void insertAt(DeweyKey key, FragmentPointer pointer) { version = version.insertAt(key, pointer); } void delete(DeweyKey key, FragmentPointer pointer) { version = version.delete(key, pointer); } void moveAfter(DeweyKey source, FragmentPointer sourcePointer, DeweyKey target, FragmentPointer targetPointer) { version = version.moveAfter(source, sourcePointer, target, targetPointer); } void moveTo(DeweyKey source, FragmentPointer sourcePointer, DeweyKey target, FragmentPointer targetPointer) { version = version.moveTo(source, sourcePointer, target, targetPointer); } } // arch-tag: acf84674-e04b-41b4-9f88-74420ab84034
30.556962
99
0.717067
856fef317bef26ffddcfcb94737c3043717bbee7
771
import java.util.Scanner; class p6 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter the Weight in Pounds : "); double weight = sc.nextDouble(); System.out.print("Enter the Height in Inches : "); double height = sc.nextDouble(); double bmi; bmi = (0.45359237*weight)/((0.0254*height)*(0.0254*height)); System.out.println("BMI is : "+bmi); if(bmi<18.5) System.out.println("\nPerson is UNDERWEIGHT"); else if(bmi>=18.5 && bmi<25.0) System.out.println("\nPerson is NORMAL"); else if(bmi>=25.0 && bmi<30.0) System.out.println("\nPerson is OVERWEIGHT"); else if(bmi>=30.0) System.out.println("\nPerson is OBESE"); System.out.println("\nID : 18DCS007\nName : RUDRA BARAD"); } }
28.555556
62
0.658885
8bd7504b36c53c02fc7216b7a92c1a6fb0b6b0d6
1,302
package com.coredump.hc.Actions; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.coredump.hc.Actors.Nodes.NodeActor; import com.coredump.hc.Asset; import com.coredump.hc.HCGame; /** * Created by Gregory on 7/2/2016. */ public class SaveAction extends Action { private float stateTime = 0; private Animation actAnimation; public SaveAction(){ TextureAtlas buttonAtlas = Asset.manager.get(Asset.spritePack,TextureAtlas.class); Skin uiSkin = new Skin(); uiSkin.addRegions(buttonAtlas); actAnimation = new Animation(1f,buttonAtlas.findRegions("Save_R")); } @Override public void act(HCGame game, NodeActor node) { stateTime += Gdx.graphics.getDeltaTime(); game.addDebug("Save Processed:"+stateTime); if (stateTime >= 5.0) { complete = true; node.processAttack(NodeActor.AttackType.SAVE); } } @Override public TextureRegion getKeyFrame(){ return actAnimation.getKeyFrame(stateTime, true); } @Override public boolean hasKeyframe(){ return true; } }
26.04
90
0.685868
3b0f7bd0bb0eaaf62170d98f5214f966091a39f2
1,465
package trainingAssignment11; import java.util.Scanner; import java.util.Stack; class StackList{ Stack<Integer> s = new Stack<Integer>(); Scanner sc = new Scanner(System.in); void addItem() { System.out.println("Enter the elements in the stack: "); s.push(sc.nextInt()); s.push(sc.nextInt()); s.push(sc.nextInt()); s.push(sc.nextInt()); s.push(sc.nextInt()); } void displayStack() { System.out.println(s); } void removeItem() { s.pop(); System.out.println(s); } void stackSize() { System.out.println("Enter the elements in the stack: "); s.push(sc.nextInt()); s.push(sc.nextInt()); System.out.println("Size of this Stack is: " +s.size()); System.out.println(s); } void peekItem() { System.out.println(s.peek()); } void stackSearch() { int i; System.out.println("Enter an element to check"); i = sc.nextInt(); System.out.println("Does this Stack contains " +i+ "? " +s.search(i)+ "is the index number of i" +i); } void clearItem() { s.clear(); System.out.println(s); } void isEmptycheck() { if(s.isEmpty()) System.out.println("The Stack is empty"); else System.out.println("The Stack is not empty"); } } public class StackDemo { public static void main(String[] args) { StackList sl = new StackList(); sl.isEmptycheck(); sl.addItem(); sl.displayStack(); sl.removeItem(); sl.stackSize(); sl.peekItem(); sl.stackSearch(); sl.clearItem(); sl.isEmptycheck(); } }
20.068493
103
0.643003
e021c197e1170fce2d85e39bc3899a3178bbc1e4
3,545
/* * Copyright (C) 2010-2017 Cyril Deguet * * 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.dexilog.smartkeyboard; import android.content.SharedPreferences; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import java.util.Calendar; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class TrialPopupTest { private static final String LAST_TRIAL_POPUP = "LAST_TRIAL_POPUP"; @Mock SharedPreferences prefs; @Mock SharedPreferences.Editor prefEditor; @Mock Calendar calendar; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); private TrialPolicy trialPolicy; private long currentTime; @Before public void setUp() throws Exception { trialPolicy = new TrialPolicy(calendar, prefs); currentTime = getTimeMs(2017, 3, 15); when(prefs.edit()).thenReturn(prefEditor); when(prefEditor.putLong(anyString(), anyLong())).thenReturn(prefEditor); when(calendar.getTimeInMillis()).thenReturn(currentTime); } @Test public void dontShowPopupOnFirstLaunch() throws Exception { when(prefs.getLong(LAST_TRIAL_POPUP, 0L)).thenReturn(0L); assertThat(trialPolicy.checkDisplayPopup(), is(false)); verify(prefEditor).putLong(LAST_TRIAL_POPUP, currentTime); } @Test public void dontShowPopupBeforeDelay() throws Exception { setLastPopupDay(15 - 6); checkDisplayPopup(false); } @Test public void showPopupAfterDelay() throws Exception { setLastPopupDay(15 - 7); checkDisplayPopup(true); } @Test public void showPopupAfterPhoneDateSetInPast() throws Exception { setLastPopupDay(15 + 3); checkDisplayPopup(true); } @Test public void dontCheckAgainWithinSameSession() throws Exception { setLastPopupDay(15 - 8); trialPolicy.checkDisplayPopup(); assertThat(trialPolicy.checkDisplayPopup(), is(false)); } private void checkDisplayPopup(boolean mustDisplay) { assertThat(trialPolicy.checkDisplayPopup(), is(mustDisplay)); if (mustDisplay) { verify(prefEditor).putLong(LAST_TRIAL_POPUP, currentTime); } else { verify(prefEditor, never()).putLong(anyString(), anyLong()); } } private void setLastPopupDay(int day) { long prevTime = getTimeMs(2017, 3, day); when(prefs.getLong(LAST_TRIAL_POPUP, 0L)).thenReturn(prevTime); } private long getTimeMs(int year, int month, int day) { Calendar cal = Calendar.getInstance(); cal.set(year, month, day); return cal.getTimeInMillis(); } }
31.651786
80
0.704937
7e6bfee9aa5786c19ff63b52d4b14592607a35ab
5,221
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package com.amazon.dataprepper.plugins.processor.date; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.AssertTrue; import java.time.ZoneId; import java.util.List; import java.util.Locale; public class DateProcessorConfig { static final Boolean DEFAULT_FROM_TIME_RECEIVED = false; static final String DEFAULT_DESTINATION = "@timestamp"; static final String DEFAULT_SOURCE_TIMEZONE = ZoneId.systemDefault().toString(); static final String DEFAULT_DESTINATION_TIMEZONE = ZoneId.systemDefault().toString(); public static class DateMatch { @JsonProperty("key") private String key; @JsonProperty("patterns") private List<String> patterns; public DateMatch() { } public DateMatch(String key, List<String> patterns) { this.key = key; this.patterns = patterns; } public String getKey() { return key; } public List<String> getPatterns() { return patterns; } } @JsonProperty("from_time_received") private Boolean fromTimeReceived = DEFAULT_FROM_TIME_RECEIVED; @JsonProperty("match") private List<DateMatch> match; @JsonProperty("destination") private String destination = DEFAULT_DESTINATION; @JsonProperty("source_timezone") private String sourceTimezone = DEFAULT_SOURCE_TIMEZONE; @JsonProperty("destination_timezone") private String destinationTimezone = DEFAULT_DESTINATION_TIMEZONE; @JsonProperty("locale") private String locale; @JsonIgnore private ZoneId sourceZoneId; @JsonIgnore private ZoneId destinationZoneId; @JsonIgnore private Locale sourceLocale; public Boolean getFromTimeReceived() { return fromTimeReceived; } public List<DateMatch> getMatch() { return match; } public String getDestination() { return destination; } public ZoneId getSourceZoneId() { return sourceZoneId; } public ZoneId getDestinationZoneId() { return destinationZoneId; } public Locale getSourceLocale() { return sourceLocale; } private ZoneId buildZoneId(final String timezone) { try { return ZoneId.of(timezone); } catch (Exception e) { throw new IllegalArgumentException("Invalid timezone."); } } private Locale buildLocale(final String locale) { Locale currentLocale; if (locale == null || locale.equalsIgnoreCase("ROOT")) { return Locale.ROOT; } boolean isBCP47Format = locale.contains("-"); final String[] localeFields; if (isBCP47Format) { localeFields = locale.split("-"); } else localeFields = locale.split("_"); switch (localeFields.length) { case 1: currentLocale = new Locale(localeFields[0]); break; case 2: currentLocale = new Locale(localeFields[0], localeFields[1]); break; case 3: currentLocale = new Locale(localeFields[0], localeFields[1], localeFields[2]); break; default: throw new IllegalArgumentException("Invalid locale format. Only language, country and variant are supported."); } if (currentLocale.getISO3Language() != null && currentLocale.getISO3Country() != null) return currentLocale; else throw new IllegalArgumentException("Unknown locale provided."); } @AssertTrue(message = "match and from_time_received are mutually exclusive options. match or from_time_received is required.") boolean isValidMatchAndFromTimestampReceived() { return Boolean.TRUE.equals(fromTimeReceived) ^ match != null; } @AssertTrue(message = "match can have a minimum and maximum of 1 entry and at least one pattern.") boolean isValidMatch() { if (match != null) { if (match.size() != 1) return false; return match.get(0).getPatterns() != null && !match.get(0).getPatterns().isEmpty(); } return true; } @AssertTrue(message = "Invalid source_timezone provided.") boolean isSourceTimezoneValid() { try { sourceZoneId = buildZoneId(sourceTimezone); return true; } catch (Exception e) { return false; } } @AssertTrue(message = "Invalid destination_timezone provided.") boolean isDestinationTimezoneValid() { try { destinationZoneId = buildZoneId(destinationTimezone); return true; } catch (Exception e) { return false; } } @AssertTrue(message = "Invalid locale provided.") boolean isLocaleValid() { try { sourceLocale = buildLocale(locale); return true; } catch (Exception e) { return false; } } }
28.221622
130
0.623444
04df3d9ab92a180100fb184b0cdeafd2b9908281
8,207
package weka.classifiers.meta; import dafdt.models.DataAttribute; import dafdt.models.OverlappedAreas; import dafdt.models.Rule; import dafdt.utils.Box; import dafdt.wekaex.ClassifierEx; import dafdt.wekaex.DecisionStumpEx; import dafdt.wekaex.J48Ex; import weka.classifiers.Classifier; import weka.classifiers.ClassifierExposer; import weka.classifiers.trees.DecisionStump; import weka.classifiers.trees.DecisionStumpExposer; import weka.classifiers.trees.J48; import weka.classifiers.trees.J48Exposer; import weka.core.Attribute; import weka.core.AttributeStats; import weka.core.Instances; import weka.core.Utils; import java.util.ArrayList; import java.util.Collections; public class AdaBoostM1Ex extends AdaBoostM1 implements ClassifierEx { //@Override public double[] getRulesLeafsLabels() { // TODO Auto-generated method stub ArrayList<Classifier> classifiers = new ArrayList<Classifier>(); ArrayList<Rule> rules = new ArrayList<Rule>(); ArrayList<Attribute> metadatalist = new ArrayList<Attribute>(); for(Attribute att:Collections.list( ((ClassifierEx)m_Classifiers[0]).getTrainingData().enumerateAttributes())) {metadatalist.add(att);} ArrayList<String> labels = new ArrayList<String>(); for (Classifier classifier : getFilteredClassifiers()) { classifiers.add(classifier); for (Rule r : ((ClassifierEx)classifier).getRules()) { //double w = (Double)(r.total/(((J48)classifier).TotalInstances())); //r.weight = Utils.roundDouble(w, 2); //String label = (new DecimalFormat("0.00")).format(w); //labels.add(label); //labels.add(((Double)(((J48)classifier).TotalInstances()/r.total)).toString()); //ArrayList<DataAttribute> attributes = r.discoverAttributesDataBoundaries(metadatalist, ((J48)classifier).stats); rules.add(r); } } double[] rulesLeafsLabels = new double[rules.size()]; for (Rule r : rules) { rulesLeafsLabels[rules.indexOf(r)] = r.weight; } return rulesLeafsLabels; } @Override public boolean isNominal() { return false; } public OverlappedAreas findOverlapped(){ //getFilteredClassifiers(); ArrayList<double[]> overlaps = new ArrayList<double[]>(); ArrayList<Box> boxes = new ArrayList<Box>(); double[][] maxmins = getRulesMaxAndMin(); double[] leafs = getRulesLeafsLabels(); ArrayList<Rule> rules = getFilteredRules(); double[][][] data = new double[rules.size()][][]; double[][] lims = new double[rules.size()][] ; double[] weights = new double[rules.size()]; double[] labels = new double[rules.size()]; //info to calculate global leafs weights double totalInstancesGenerated = 0; double[] globalWeights = new double[rules.size()]; for (Rule r : rules) { data[rules.indexOf(r)] = r.generatedData; if(r.generatedData !=null) { totalInstancesGenerated += r.generatedData.length; } lims[rules.indexOf(r)] = maxmins[rules.indexOf(r)]; weights[rules.indexOf(r)] = r.weight; labels[rules.indexOf(r)] = r.data; } //calculate global leafs weights with totalinstancesgenerated for(Rule r:rules) { double w = (((r.generatedData.length * 100)/totalInstancesGenerated)/100); globalWeights[rules.indexOf(r)] = Utils.roundDouble(w, 2); if(w > 1) { System.out.println("w > 1"); } } for(int i = 0; i < maxmins.length; i++) { boxes.add(new Box(maxmins[i], leafs[i], rules.get(i))); } for (Box bi : boxes) { for(Box bj : boxes) { if(bi.overlaps(bj))bi.overlaps.add(bj); if(bi.overlaps(bj) && (bi.rule.data != bj.rule.data))bi.disagrementoverlaps.add(bj); } } OverlappedAreas ola = new OverlappedAreas(); ola.data = data; ola.maxmins = maxmins; ola.weights = globalWeights; ola.labels = labels; return ola; //matlab.plotOverlapped(data, maxmins, globalWeights, labels, filepath + "OverlappedColorGradient", title); //matlab.plotOverlappedGradientBoxes(data, maxmins, globalWeights, labels, filepath + "OverlappedGradientBoxes", title); //matlab.plotOverlappedGradientBoxesGrayAreas(data, maxmins, globalWeights, labels, filepath + "OverlappedGradientBoxesGrayAreas", title); //for each box bi check if there are boxes bj which are overlapping it, //if bj overlaps bi with class disagreement then increment the bi overlap counter. //The overlap counter will be the gradient factor for the plotting: as higher the counter higher the alpha } public ArrayList<Rule> getFilteredRules(){ ArrayList<Rule> filteredrules = new ArrayList<Rule>(); for (Classifier classifier : getFilteredClassifiers()) { for (Rule r : ((ClassifierEx)classifier).getRules()) { filteredrules.add(r); } } return filteredrules; } @Override public void setWeight(double weight) { } @Override public double getWeight() { return 0; } @Override public Instances getTrainingData() { return null; } @Override public ArrayList<Rule> getRules() { return null; } @Override public ArrayList<AttributeStats> getStats() { return null; } @Override public double TotalInstances() { return 0; } //@Override public double[][] getRulesMaxAndMin() { // TODO Auto-generated method stub ArrayList<Classifier> classifiers = new ArrayList<Classifier>(); ArrayList<Rule> rules = new ArrayList<Rule>(); ArrayList<Attribute> metadatalist = new ArrayList<Attribute>(); for(Attribute att:Collections.list(ClassifierExposer.getDecisionStumpTrainingData(((Classifier)m_Classifiers[0])).enumerateAttributes())) {metadatalist.add(att);} ArrayList<double[]> maxnmins = new ArrayList<double[]>(); for (Classifier classifier : getFilteredClassifiers()) { classifiers.add(classifier); for (Rule r : DecisionStumpExposer.getRules((DecisionStump)classifier)) { ArrayList<DataAttribute> attributes = r.discoverAttributesDataBoundaries(metadatalist, ((ClassifierEx)classifier).getStats()); rules.add(r); maxnmins.add(new double[] {attributes.get(0).getMin(), attributes.get(0).getMax(),attributes.get(1).getMin(),attributes.get(1).getMax()}); } } double[][] rulesMaxAndMin = new double[rules.size()][4]; for (double[] mm : maxnmins) { rulesMaxAndMin[maxnmins.indexOf(mm)] = mm; } return rulesMaxAndMin; } public ArrayList<Classifier> getFilteredClassifiers(){ ArrayList<Classifier> result = new ArrayList<Classifier>(); if (m_NumIterationsPerformed == 1) { ClassifierEx classifier = ((ClassifierEx)m_Classifiers[0]); classifier.setWeight(1); result.add(classifier); } else { int cIndex = 0; for (Classifier classifier : m_Classifiers) { if(classifier.getClass().getName().equals(J48.class.getName())) { J48Ex c = (J48Ex)classifier; if(J48Exposer.GetNumNodes(c)>1) { if(c.getWeight()!=0) { result.add(c); } } } if(classifier.getClass().getName().equals(DecisionStump.class.getName())) { if(Utils.roundDouble(m_Betas[cIndex], 2)!=0) { result.add((Classifier) classifier); } } cIndex++; } } return result; } }
34.483193
170
0.603266
b0904d6aaffd2cba53b90401d627b8a56d4484d2
2,002
package com.kemalyanmaz.portfoliowork.business.concretes; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.kemalyanmaz.portfoliowork.business.abstracts.AddressService; import com.kemalyanmaz.portfoliowork.business.abstracts.CityService; import com.kemalyanmaz.portfoliowork.dataAccess.abstracts.AddressDao; import com.kemalyanmaz.portfoliowork.dataAccess.concretes.AddressDto; import com.kemalyanmaz.portfoliowork.entities.concretes.Address; @Service public class AddressManager implements AddressService{ private AddressDao addressDao; private CityService cityService; @Autowired public AddressManager(AddressDao addressDao, CityService cityService) { super(); this.addressDao = addressDao; this.cityService = cityService; } @Override public List<AddressDto> getAll() { Map<Long,AddressDto> addressMap = new HashMap<>(); addressDao.findAll().forEach(address->{ addressMap.put(address.getId(), addressToDto(address)); }); List<AddressDto> addressList = new ArrayList<>(); for(long id:addressMap.keySet()) { addressList.add(addressMap.get(id)); } return addressList; } private AddressDto addressToDto(Address address) { AddressDto addressDto = new AddressDto(); addressDto.setDistrict(address.getDistrict()); addressDto.setNeighborhood(address.getNeigborhood()); addressDto.setDoorNo(address.getDoorNo()); addressDto.setFloor(address.getFloor()); addressDto.setCity(cityService.getCityById(address.getCityId())); return addressDto; } @Override public Address addAddress(Address address) { return addressDao.save(address); } @Override public AddressDto getAddressDtoById(long id) { return addressToDto(addressDao.findById(id).orElse(new Address())); } @Override public boolean existsById(long id) { return addressDao.existsById(id); } }
26
72
0.78022
7016f675f913b9d539bddb0eedf53d56674d02d5
522
package org.argouml.language.csharp.importer.csparser.nodes.expressions; /** * Created by IntelliJ IDEA. * User: Thilina * Date: Jun 7, 2008 * Time: 7:18:34 PM */ public class TypeOfExpression extends PrimaryExpression { public TypeOfExpression() { } public TypeOfExpression(ExpressionNode expression) { this.Expression = expression; } private ExpressionNode Expression; public void ToSource(StringBuilder sb) { sb.append("typeof("); Expression.ToSource(sb); sb.append(")"); } }
18
72
0.703065
7f95b5959ca8dd0751410fc4176885d62347e1db
3,573
/* * Copyright (c) 2015-2020, David A. Bauer. 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 io.actor4j.core.internal.balancing; import static io.actor4j.core.logging.ActorLogger.*; import static io.actor4j.core.utils.ActorUtils.actorLabel; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import io.actor4j.core.actors.Actor; import io.actor4j.core.actors.ActorDistributedGroupMember; import io.actor4j.core.actors.ActorGroupMember; import io.actor4j.core.actors.ResourceActor; import io.actor4j.core.internal.ActorCell; import io.actor4j.core.internal.ActorThread; public class ActorLoadBalancingBeforeStart { public void registerCells(Map<UUID, Long> cellsMap, List<ActorThread> actorThreads, Map<UUID, Long> groupsMap, Map<UUID, Integer> groupsDistributedMap, Map<UUID, ActorCell> cells) { List<UUID> buffer = new LinkedList<>(); for (ActorCell cell : cells.values()) if (!(cell.getActor() instanceof ResourceActor)) buffer.add(cell.getId()); int i=0, j=0; for (ActorCell cell : cells.values()) { Actor actor = cell.getActor(); if (actor instanceof ResourceActor) continue; if (actor instanceof ActorDistributedGroupMember) { Integer threadIndex = groupsDistributedMap.get(((ActorDistributedGroupMember)actor).getDistributedGroupId()); Long threadId = null; if (threadIndex==null) { threadId = actorThreads.get(j).getId(); groupsDistributedMap.put(((ActorDistributedGroupMember)actor).getDistributedGroupId(), j); } else { threadIndex++; if (threadIndex==actorThreads.size()) threadIndex = 0; threadId = actorThreads.get(threadIndex).getId(); groupsDistributedMap.put(((ActorDistributedGroupMember)actor).getDistributedGroupId(), threadIndex); } if (buffer.remove(cell.getId())) cellsMap.put(cell.getId(), threadId); j++; if (j==actorThreads.size()) j = 0; if (actor instanceof ActorGroupMember) { if (groupsMap.get(((ActorGroupMember)actor).getGroupId())==null) groupsMap.put(((ActorGroupMember)actor).getGroupId(), threadId); else systemLogger().log(ERROR, String.format("[LOAD BALANCING] actor (%s) must be first initial group member", actorLabel(cell.getActor()))); } } else if (actor instanceof ActorGroupMember) { Long threadId = groupsMap.get(((ActorGroupMember)actor).getGroupId()); if (threadId==null) { threadId = actorThreads.get(i).getId(); groupsMap.put(((ActorGroupMember)actor).getGroupId(), threadId); i++; if (i==actorThreads.size()) i = 0; } if (buffer.remove(cell.getId())) cellsMap.put(cell.getId(), threadId); } } i=0; for (UUID id : buffer) { cellsMap.put(id, actorThreads.get(i).getId()); i++; if (i==actorThreads.size()) i = 0; } /* int i=0; for (UUID id : system.cells.keySet()) { cellsMap.put(id, actorThreads.get(i).getId()); i++; if (i==actorThreads.size()) i = 0; } */ } }
33.392523
182
0.694374
19ba5ff29ca4d4d626b8f4d50b2ffb022cce62ac
3,349
package jw.kingdom.hall.kingdomtimer.data.file.save.record; import jw.kingdom.hall.kingdomtimer.config.model.Config; import jw.kingdom.hall.kingdomtimer.config.model.ConfigReadable; import jw.kingdom.hall.kingdomtimer.data.file.save.UniqueFileUtils; import jw.kingdom.hall.kingdomtimer.domain.countdown.Countdown; import jw.kingdom.hall.kingdomtimer.domain.countdown.CountdownListenerProxy; import jw.kingdom.hall.kingdomtimer.domain.task.TaskBean; import jw.kingdom.hall.kingdomtimer.domain.schedule.Schedule; import jw.kingdom.hall.kingdomtimer.recorder.common.files.FileRecordProvider; import java.io.File; /** * This file is part of KingdomHallTimer which is released under "no licence". */ public class DefaultFileRecordProvider implements FileRecordProvider { private static final TaskBean EMPTY = getEmptyTask(); private final Config config; private TaskBean lastTask = EMPTY; public DefaultFileRecordProvider(Config config, Schedule schedule, Countdown countdown){ this.config = config; countdown.addListener(new CountdownListenerProxy() { @Override public void onStart(TaskBean task) { super.onStart(task); lastTask = task; } @Override public void onStop() { super.onStop(); if(schedule.getList().size()==0){ new Thread(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } lastTask = EMPTY; }).start(); } } }); } @Override public File getBackupFile(String extension) { createRootPath(); return UniqueFileUtils.buildUniqueFile(getDestPath(), getBackupFileRawName(), extension); } /** * @return Name of file without extension */ private String getBackupFileRawName() { String raw; if(getConfig().isAutoSeparate()) { raw = getConfig().getRawFileNameBackupGroups(); } else { raw = getConfig().getRawFileNameBackup(); } return NameParser.getParsedName(raw, lastTask); } @Override public File getFinalFile(String extension) { createRootPath(); return UniqueFileUtils.buildUniqueFile(getDestPath(), getFinalFileRawName(), extension); } /** * @return Name of file without extension */ private String getFinalFileRawName() { String raw; if(getConfig().isAutoSeparate()) { raw = getConfig().getRawFileNameFinalGroups(); } else { raw = getConfig().getRawFileNameFinal(); } return NameParser.getParsedName(raw, lastTask); } private void createRootPath() { UniqueFileUtils.createPath(getDestPath()); } private String getDestPath() { return getConfig().getRecordDestPath(); } private static TaskBean getEmptyTask() { TaskBean empty = new TaskBean(); empty.setType(TaskBean.Type.NONE); empty.setName("Nagranie poza programem"); return empty; } private ConfigReadable getConfig() { return config; } }
31.895238
97
0.617796
53579993c54accb6b806a1eea248344a9dfdfff4
460
package pw.lemmmy.ts3protocol.utils.properties; import java.util.Map; public abstract class ShortProperty extends Property<Short> { protected String name; @Override public void encodeProperty(Map<String, String> arguments) { arguments.put(name, Short.toString(getValue())); } @Override public void decodeProperty(Map<String, String> arguments) { if (!arguments.containsKey(name)) return; setValue(Short.parseShort(arguments.get(name))); } }
24.210526
61
0.758696
3feee88d06517a8909af75254a56d576da58ed17
1,477
package br.com.casadocodigo.cupom; import javax.validation.constraints.*; import java.math.BigDecimal; import java.time.LocalDate; public class CupomRequest { private @NotBlank(message ="Código Cupom Inválido") String codigoCupom; private @Positive(message ="Percentual Desconto Inválido") @NotNull BigDecimal percentualDesconto; private @Future (message ="Data Validade não está no futuro")@NotNull LocalDate validade; public CupomRequest() { } public CupomRequest(@NotBlank(message = "Código Cupom Inválido") String codigoCupom, @Positive(message = "Percentual Desconto Inválido") @NotNull BigDecimal percentualDesconto, @Future(message = "Data Validade não está no futuro") @NotNull LocalDate validade) { this.codigoCupom = codigoCupom; this.percentualDesconto = percentualDesconto; this.validade = validade; } public String getCodigoCupom() { return codigoCupom; } public void setCodigoCupom(String codigoCupom) { this.codigoCupom = codigoCupom; } public BigDecimal getPercentualDesconto() { return percentualDesconto; } public void setPercentualDesconto(BigDecimal percentualDesconto) { this.percentualDesconto = percentualDesconto; } public LocalDate getValidade() { return validade; } public void setValidade(LocalDate validade) { this.validade = validade; } }
32.108696
266
0.693297
000b2b41ac49281753b185d1cbe93196a118e803
6,860
package com.example.application.views.sync; import com.example.application.data.entity.Person; import com.example.application.data.entity.User; import com.example.application.data.service.PersonService; import com.example.application.data.service.ZkService; import com.example.application.views.main.MainView; import com.example.application.views.user.UserView; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.data.provider.ListDataProvider; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteParameters; import java.util.ArrayList; import java.util.List; @Route(value = "sync-detail/:timeZoneID?/:action?(edit)", layout = MainView.class) @PageTitle("sync-Detail") public class SyncView extends Div { private ZkService<Person> zkService = new ZkService<>(); public SyncView(PersonService personService) { List<Person> personList = onlyInOnePlace(personService.findAll(),getListDevice()); Grid<Person> grid = new Grid<>(Person.class); grid.setItems(personList); // Use the component constructor that accepts an item -> // new PersonComponent(Person person) // Or you can use an ordinary function to setup the component grid.setColumns("uid", "name"); grid.addComponentColumn(item -> createRemoveButton(grid, item,personService)) .setHeader("Actions"); grid.addComponentColumn(item -> createAddButton(grid, item,personService)) .setHeader("Actions"); grid.addComponentColumn(item -> createAddButton1()) .setHeader("Actions"); grid.setSelectionMode(Grid.SelectionMode.NONE); add(grid); } private Button createRemoveButton(Grid<Person> grid, Person item ,PersonService personService) { @SuppressWarnings("unchecked") Button button = new Button("Remove", clickEvent -> { ListDataProvider<Person> dataProvider = (ListDataProvider<Person>) grid .getDataProvider(); ZkService<User> zkService2 = new ZkService<>(); try { item.setUid(item.getUid()); User user = new User(); user.setId(item.getId()); user.setUid(item.getUid()); user.setName(item.getName()); user.setGroup_id(item.getGroup_id()); user.setPrivilege(item.getPrivilege()); user.setPassword(item.getPassword()); user.setCard(item.getCard()); user.setUser_id(item.getUser_id()); zkService2.post("http://127.0.0.1:5000/deleteUser",user); personService.delete(item); dataProvider.getItems().remove(item); } catch (Exception e) { e.printStackTrace(); } dataProvider.refreshAll(); }); return button; } private Button createAddButton1() { @SuppressWarnings("unchecked") Button button = new Button("navigation",e -> getUI().ifPresent(ui -> ui.navigate( UserView.class, new RouteParameters("timeZoneID", "123") )) ); return button; } private Button createAddButton(Grid<Person> grid, Person item,PersonService personService) { @SuppressWarnings("unchecked") Button button = new Button("Save", clickEvent -> { ListDataProvider<Person> dataProvider = (ListDataProvider<Person>) grid .getDataProvider(); ZkService<User> zkService2 = new ZkService<>(); try { item.setUid(item.getUid()); User user = new User(); user.setId(item.getId()); user.setUid(item.getUid()); user.setName(item.getName()); user.setGroup_id(item.getGroup_id()); user.setPrivilege(item.getPrivilege()); user.setPassword(item.getPassword()); user.setCard(item.getCard()); user.setUser_id(item.getUser_id()); zkService2.post("http://127.0.0.1:5000/setUsers",user); personService.save(item); dataProvider.getItems().remove(item); } catch (Exception e) { e.printStackTrace(); } dataProvider.refreshAll(); }); return button; } public List<Person> onlyInOnePlace(List<Person> source,List<Person> target){ if (target.size()==0) return source; if (source.size()==0) return target; System.out.println(source.size()); System.out.println(target.size()); List<Person> result = new ArrayList<>(); for (int i = 0; i < target.size(); i++) { result.add(target.get(i)); for (int j = 0; j < source.size(); j++) { if (target.get(i).getUid()== source.get(j).getUid()) { result.remove(target.get(i)); } } } List<Person> result2 = new ArrayList<>(); for (int i = 0; i < source.size(); i++) { result2.add(source.get(i)); for (int j = 0; j < target.size(); j++) { if (source.get(i).getUid()== target.get(j).getUid()) { result2.remove(source.get(i)); } } } result.addAll(result2); return result; } public List<Person> getListDevice(){ List<Person> attendances = new ArrayList<>(); try { String data = zkService.get("http://127.0.0.1:5000/getUsers"); ObjectMapper mapper = new ObjectMapper(); List<User> users = mapper.readValue(data, new TypeReference<List<User>>() {}); users.stream().forEach(user -> { Person person = new Person(); person.setId(user.getId()); person.setUid(user.getUid()); person.setName(user.getName()); person.setGroup_id(user.getGroup_id()); person.setPrivilege(user.getPrivilege()); person.setPassword(user.getPassword()); person.setCard(user.getCard()); person.setUser_id(user.getUser_id()); attendances.add(person); }); }catch (Exception e){ Notification.show("error to connect to device"); } return attendances; } }
33.300971
100
0.578571
c9bb41eeee949bf73bb04de5dd1fce479ec7c3c9
11,873
package com.efp.common.data; import com.intellij.database.model.DasNamespace; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * @author primerxiao */ public class EfpCovert { public static List<ModuleCovertBean> list = new ArrayList<>(); static { list.add(new ModuleCovertBean("basic.sequence.impl", "basic_sequence", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("cdp.pboc.common", "cdp_pboc", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("basic.sequence.middle", "basic_sequence", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("cdp.pboc.impl", "cdp_pboc", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("basic.sequence.service", "basic_sequence", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("cdp.pboc.middle", "cdp_pboc", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.batch.common", "efp_batch", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("cdp.pboc.service", "cdp_pboc", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.batch.service", "efp_batch", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.batch.middle", "efp_batch", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.console.common", "efp_console", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.console.front", "efp_console", EfpModuleType.FRONT)); list.add(new ModuleCovertBean("efp.console.middle", "efp_console", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.console.service", "efp_console", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.console.impl", "efp_console", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.ctr.common", "efp_ctr", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.batch.impl", "efp_batch", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.ctr.middle", "efp_ctr", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.ctr.impl", "efp_ctr", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.ctr.service", "efp_ctr", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.cus.front", "efp_cus", EfpModuleType.FRONT)); list.add(new ModuleCovertBean("efp.cus.impl", "efp_cus", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.cus.common", "efp_cus", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.cus.service", "efp_cus", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.cus.middle", "efp_cus", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.e4a.common", "efp_e4a", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.e4a.front", "efp_e4a", EfpModuleType.FRONT)); list.add(new ModuleCovertBean("efp.e4a.impl", "efp_e4a", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.e4a.middle", "efp_e4a", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.e4a.service", "efp_e4a", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.console.api", "efp_console", EfpModuleType.API)); list.add(new ModuleCovertBean("efp.edoc.api", "efp_edoc", EfpModuleType.API)); list.add(new ModuleCovertBean("efp.cus.api", "efp_cus", EfpModuleType.API)); list.add(new ModuleCovertBean("efp.e4a.api", "efp_e4a", EfpModuleType.API)); list.add(new ModuleCovertBean("efp.edoc.front", "efp_edoc", EfpModuleType.FRONT)); list.add(new ModuleCovertBean("efp.edoc.middle", "efp_edoc", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.edoc.service", "efp_edoc", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.esb.api", "efp_esb", EfpModuleType.API)); list.add(new ModuleCovertBean("efp.esb.front", "efp_esb", EfpModuleType.FRONT)); list.add(new ModuleCovertBean("efp.edoc.common", "efp_edoc", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.edoc.impl", "efp_edoc", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.esb.middle", "efp_esb", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.esb.impl", "efp_esb", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.esb.service", "efp_esb", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.esb.common", "efp_esb", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.flow.front", "efp_flow", EfpModuleType.FRONT)); list.add(new ModuleCovertBean("efp.flow.middle", "efp_flow", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.flow.common", "efp_flow", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.flow.api", "efp_flow", EfpModuleType.API)); list.add(new ModuleCovertBean("efp.limit.common", "efp_limit", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.limit.impl", "efp_limit", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.flow.service", "efp_flow", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.flow.impl", "efp_flow", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.limit.middle", "efp_limit", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.loan.impl", "efp_loan", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.limit.service", "efp_limit", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.loan.service", "efp_loan", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.loan.middle", "efp_loan", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.nls.front", "efp_nls", EfpModuleType.FRONT)); list.add(new ModuleCovertBean("efp.loan.common", "efp_loan", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.nls.middle", "efp_nls", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.nls.impl", "efp_nls", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.nls.api", "efp_nls", EfpModuleType.API)); list.add(new ModuleCovertBean("efp.report.common", "efp_report", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.nls.common", "efp_nls", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.nls.service", "efp_nls", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.report.impl", "efp_report", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.riskm.common", "efp_riskm", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.riskm.front", "efp_riskm", EfpModuleType.FRONT)); list.add(new ModuleCovertBean("efp.riskm.impl", "efp_riskm", EfpModuleType.IMPL)); list.add(new ModuleCovertBean("efp.riskm.middle", "efp_riskm", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.riskm.service", "efp_riskm", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.rule.common", "efp_rule", EfpModuleType.COMMON)); list.add(new ModuleCovertBean("efp.report.service", "efp_report", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.rule.middle", "efp_rule", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.report.middle", "efp_report", EfpModuleType.MIDDLE)); list.add(new ModuleCovertBean("efp.riskm.api", "efp_risk", EfpModuleType.API)); list.add(new ModuleCovertBean("efp.rule.service", "efp_rule", EfpModuleType.SERVICE)); list.add(new ModuleCovertBean("efp.rule.impl", "efp_rule", EfpModuleType.IMPL)); } /** * 根据条件获取项目module * * @return */ public static Module getModule(Project project, DasNamespace dasNamespace, EfpModuleType moduleType) { //根据数据库名获取转换对象 for (ModuleCovertBean moduleCovertBean : list) { if (moduleCovertBean.getNameSpaceName().equalsIgnoreCase(dasNamespace.getName())) { if (moduleCovertBean.getEfpModuleType().getModuleTypeValue() == moduleType.getModuleTypeValue()) { return ModuleManager.getInstance(project).findModuleByName(moduleCovertBean.getModuleName()); } } } //如果不存在 那么按默认规则返回 String dasNamespaceName = dasNamespace.getName(); final String[] dasNamespaceNameArr = dasNamespaceName.split("_"); //a_b a.b.* switch (moduleType) { case API: return ModuleManager.getInstance(project).findModuleByName(dasNamespaceNameArr[0] + "." + dasNamespaceNameArr[1] + ".api"); case IMPL: return ModuleManager.getInstance(project).findModuleByName(dasNamespaceNameArr[0] + "." + dasNamespaceNameArr[1] + ".impl"); case FRONT: return ModuleManager.getInstance(project).findModuleByName(dasNamespaceNameArr[0] + "." + dasNamespaceNameArr[1] + ".front"); case COMMON: return ModuleManager.getInstance(project).findModuleByName(dasNamespaceNameArr[0] + "." + dasNamespaceNameArr[1] + ".common"); case MIDDLE: return ModuleManager.getInstance(project).findModuleByName(dasNamespaceNameArr[0] + "." + dasNamespaceNameArr[1] + ".middle"); case SERVICE: return ModuleManager.getInstance(project).findModuleByName(dasNamespaceNameArr[0] + "." + dasNamespaceNameArr[1] + ".service"); } return null; } /** * 根据模块获取对应的模块对象 * * @param module 模块 * @param moduleType 要获取的模块类型 * @return */ public static Module getModule(Module module, EfpModuleType moduleType) { //判断当前模块的模块类型 final String moduleName = module.getName(); final ModuleCovertBean moduleCovertBean = list.stream(). filter(e -> e.getModuleName().equalsIgnoreCase(moduleName) && e.getEfpModuleType().getModuleTypeValue() == moduleType.getModuleTypeValue()). findFirst().orElse(null); if (moduleCovertBean != null) { return ModuleManager.getInstance(module.getProject()).findModuleByName(moduleCovertBean.getModuleName()); } //找到为空的话按约定来找 final String[] moduleNameArr = getModuleNameArr(module); //a_b a.b.* switch (moduleType) { case API: return ModuleManager.getInstance(module.getProject()).findModuleByName(moduleNameArr[0] + "." + moduleNameArr[1] + ".api"); case IMPL: return ModuleManager.getInstance(module.getProject()).findModuleByName(moduleNameArr[0] + "." + moduleNameArr[1] + ".impl"); case FRONT: return ModuleManager.getInstance(module.getProject()).findModuleByName(moduleNameArr[0] + "." + moduleNameArr[1] + ".front"); case COMMON: return ModuleManager.getInstance(module.getProject()).findModuleByName(moduleNameArr[0] + "." + moduleNameArr[1] + ".common"); case MIDDLE: return ModuleManager.getInstance(module.getProject()).findModuleByName(moduleNameArr[0] + "." + moduleNameArr[1] + ".middle"); case SERVICE: return ModuleManager.getInstance(module.getProject()).findModuleByName(moduleNameArr[0] + "." + moduleNameArr[1] + ".service"); } return null; } public static void main(String[] args) { String n = "efp.val"; final String[] split = n.split("."); System.out.println(split[0]); } /** * 或者模块名的切割数组 * * @param module * @return */ public static String[] getModuleNameArr(Module module) { String name = module.getName(); return name.split("\\."); } }
62.489474
156
0.677756
6b77ce6c461820bee091f7abc52fea2bb9b5e2b7
1,752
package com.goverse.capturer.transformation; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import java.io.ByteArrayOutputStream; public class QualityCompressTransformation implements ITransformation { private int mQuality; private Bitmap.CompressFormat mCompressFormat = Bitmap.CompressFormat.PNG; public QualityCompressTransformation(int quality) { mQuality = quality; } public QualityCompressTransformation(Bitmap.CompressFormat compressFormat, int quality) { mCompressFormat = compressFormat; mQuality = quality; } @Override public Bitmap transform(Bitmap bitmap) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Bitmap srcBitmap = bitmap; if (mCompressFormat == Bitmap.CompressFormat.JPEG) { srcBitmap = convertBitmapToJpg(bitmap); } srcBitmap.compress(mCompressFormat, mQuality, bos); byte[] bytes = bos.toByteArray(); Bitmap destBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); if (!srcBitmap.isRecycled()) srcBitmap.recycle(); return destBitmap; } /** * 把bitmap,png格式的图片 转换成jpg图片 * 因jpg不支持透明,透明部分会显示黑色。 * 处理逻辑如下: * 复制Bitmap,把透明底色变成白色。 * 创建一张白色图片,把原来的绘制上去,生成新的bitmap。 * @param bitmap bitmap */ private Bitmap convertBitmapToJpg(Bitmap bitmap) { Bitmap outBitmap = bitmap.copy(Bitmap.Config.RGB_565,true); Canvas canvas = new Canvas(outBitmap); canvas.drawColor(Color.WHITE); canvas.drawBitmap(bitmap, 0, 0, null); return outBitmap; } }
31.285714
94
0.671804
d78bb6ab1faed194efa283a3112cfe9cc5b6ffd5
3,536
package jat.application.EarthSatellite; import org.eclipse.swt.SWT; import org.eclipse.swt.opengl.GLCanvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GLContext; import org.eclipse.swt.graphics.*; import org.eclipse.swt.opengl.GLData; import org.lwjgl.opengl.glu.GLU; public class AnimationPane extends Composite implements Runnable { Display display; final GLCanvas canvas; int rot; float frot = 1.0f; float faWhite[] = { 1.0f, 1.0f, 1.0f, 1.0f }; float faLightBlue[] = { 0.8f, 0.8f, .9f, 1f }; float lightPosition[] = { -4f, 3f, 3f, 1.0f }; int sphereTextureHandle = 0; public AnimationPane(Display display, Composite parent) { super(parent, SWT.NONE); this.display = display; GLData data = new GLData(); data.doubleBuffer = true; canvas = new GLCanvas(this, SWT.NONE, data); canvas.setCurrent(); try { GLContext.useContext(canvas); } catch (LWJGLException e) { e.printStackTrace(); } canvas.addListener(SWT.Resize, new Listener() { public void handleEvent(Event event) { Rectangle bounds = canvas.getBounds(); float fAspect = (float) bounds.width / (float) bounds.height; canvas.setCurrent(); try { GLContext.useContext(canvas); } catch (LWJGLException e) { e.printStackTrace(); } GL11.glViewport(0, 0, bounds.width, bounds.height); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GLU.gluPerspective(45.0f, fAspect, 0.5f, 400.0f); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); } }); //GL11.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); //GL11.glColor3f(0.1f, 0.0f, 0.4f); GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST); GL11.glClearDepth(1.0); GL11.glLineWidth(1); GL11.glEnable(GL11.GL_DEPTH_TEST); // enable lighting and texture rendering GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_TEXTURE_2D); // Create sphere texture GLImage textureImg = GLlib.loadImage("images/earth.jpg"); sphereTextureHandle = GLlib.makeTexture(textureImg); display.timerExec(50, this); } public void run() { { if (!canvas.isDisposed()) { canvas.setCurrent(); try { GLContext.useContext(canvas); } catch (LWJGLException e) { e.printStackTrace(); } GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); //GL11.glClearColor(.1f, .1f, .1f, 1.0f); GL11.glLoadIdentity(); GL11.glTranslatef(0.0f, 0.0f, -5.0f); //GL11.glRotatef(0.15f * rot, 2.0f * frot, 10.0f * frot, 1.0f); GL11.glRotatef(frot, 0.0f , 1.0f * frot, 1.0f); frot=frot+0.1f; GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_SMOOTH); //GL11.glColor3f(0.9f, 0.5f, 0.3f); // Create a light (diffuse light, ambient light, position) GLlib.setLight(GL11.GL_LIGHT1, faWhite, faLightBlue, lightPosition); // drawTorus(1, 1.9f + ((float) Math.sin((0.004f * frot))), 15, 15); GLlib.renderSphere(); GL11.glColor3f(1.0f, 0.0f, 0.0f); GLlib.drawLine(0.0f,0.0f,0.0f,0.0f,0.0f,1.5f); GLlib.drawLine(0.0f,0.0f,0.0f,0.0f,1.5f,0.0f); //GLlib.drawTriangle(); canvas.swapBuffers(); display.timerExec(5, this); // try { // //wait for Producer to put value // wait(50); // } catch (InterruptedException e) { } // display.asyncExec(this); } } } }
28.747967
72
0.674208
6dd2069798f1d72b6b9070d3f2bcc5bfc535d689
269
package ${package}.source; /** * Testcase of ${classNameOfSource}. */ public class TestCaseOf${classNameOfSource} { // If you will know about this related testcase, //refer https://github.com/siddhi-io/siddhi-io-file/blob/master/component/src/test }
26.9
90
0.695167
8413b6a0a62a17a6b03594e6bfad0b759dd6b2e5
3,126
package com.studerw.activiti.model; import com.google.common.base.Objects; import org.activiti.engine.identity.User; import org.codehaus.jackson.annotate.JsonIgnore; import org.hibernate.validator.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; /** * User: studerw * Date: 5/18/14 */ public class UserForm implements Serializable { @NotNull @Size(min = 5, max = 50) private String userName; @JsonIgnore @NotNull @Size(min = 8, max = 30) private String password; @NotNull @Email private String email; @NotNull private String firstName; @NotNull private String lastName; @NotNull private String group; public UserForm() {} public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public UserForm(String userName, String password, String email, String firstName, String lastName, String group) { this.userName = userName; this.password = password; this.email = email; this.firstName = firstName; this.lastName = lastName; this.group = group; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UserForm)) return false; UserForm userForm = (UserForm) o; if (userName != null ? !userName.equals(userForm.userName) : userForm.userName != null) return false; return true; } @Override public int hashCode() { return userName != null ? userName.hashCode() : 0; } @Override public String toString() { return Objects.toStringHelper(this) .add("userName", userName) .add("email", email) .add("firstName", firstName) .add("lastName", lastName) .add("group", group) .toString(); } public static UserForm fromUser(User user){ UserForm userForm = new UserForm(); userForm.setUserName(user.getId()); userForm.setPassword(user.getPassword()); userForm.setFirstName(user.getFirstName()); userForm.setLastName(user.getLastName()); userForm.setEmail(user.getEmail()); return userForm; } }
23.503759
118
0.616443
04d103ac04369a78249e45a424c08695f50b7430
3,929
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under // the terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0 // // This Source Code may also be made available under the following // Secondary Licenses when the conditions for such availability set // forth in the Eclipse Public License, v. 2.0 are satisfied: // the Apache License v2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.server; import java.util.List; import org.eclipse.jetty.http.BadMessageException; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.EndPoint; /** * A Factory to create {@link Connection} instances for {@link Connector}s. * <p> * A Connection factory is responsible for instantiating and configuring a {@link Connection} instance * to handle an {@link EndPoint} accepted by a {@link Connector}. * <p> * A ConnectionFactory has a protocol name that represents the protocol of the Connections * created. Example of protocol names include: * <dl> * <dt>http</dt><dd>Creates an HTTP connection that can handle multiple versions of HTTP from 0.9 to 1.1</dd> * <dt>h2</dt><dd>Creates an HTTP/2 connection that handles the HTTP/2 protocol</dd> * <dt>SSL-XYZ</dt><dd>Create an SSL connection chained to a connection obtained from a connection factory * with a protocol "XYZ".</dd> * <dt>SSL-http</dt><dd>Create an SSL connection chained to an HTTP connection (aka https)</dd> * <dt>SSL-ALPN</dt><dd>Create an SSL connection chained to a ALPN connection, that uses a negotiation with * the client to determine the next protocol.</dd> * </dl> */ public interface ConnectionFactory { /** * @return A string representing the primary protocol name. */ public String getProtocol(); /** * @return A list of alternative protocol names/versions including the primary protocol. */ public List<String> getProtocols(); /** * <p>Creates a new {@link Connection} with the given parameters</p> * * @param connector The {@link Connector} creating this connection * @param endPoint the {@link EndPoint} associated with the connection * @return a new {@link Connection} */ public Connection newConnection(Connector connector, EndPoint endPoint); public interface Upgrading extends ConnectionFactory { /** * Create a connection for an upgrade request. * <p>This is a variation of {@link #newConnection(Connector, EndPoint)} that can create (and/or customise) * a connection for an upgrade request. Implementations may call {@link #newConnection(Connector, EndPoint)} or * may construct the connection instance themselves.</p> * * @param connector The connector to upgrade for. * @param endPoint The endpoint of the connection. * @param upgradeRequest The meta data of the upgrade request. * @param responseFields The fields to be sent with the 101 response * @return Null to indicate that request processing should continue normally without upgrading. A new connection instance to * indicate that the upgrade should proceed. * @throws BadMessageException Thrown to indicate the upgrade attempt was illegal and that a bad message response should be sent. */ public Connection upgradeConnection(Connector connector, EndPoint endPoint, MetaData.Request upgradeRequest, HttpFields responseFields) throws BadMessageException; } }
44.146067
171
0.69127
344f1f3a9e7c717ac0677ef9edddd8306f5b6fe9
6,850
package net.runelite.client.plugins.vorkath; import com.google.common.eventbus.Subscribe; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Actor; import net.runelite.api.Client; import net.runelite.api.GameState; import net.runelite.api.NPC; import net.runelite.api.Projectile; import net.runelite.api.ProjectileID; import net.runelite.api.coords.LocalPoint; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.LocalPlayerDeath; import net.runelite.api.events.NpcDespawned; import net.runelite.api.events.NpcSpawned; import net.runelite.api.events.ProjectileMoved; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.overlay.OverlayManager; import javax.inject.Inject; @PluginDescriptor( name = "Vorkath" ) @Slf4j public class VorkathPlugin extends Plugin { private static final int ANIMATION_VORKATH_WAKE_UP = 7950; private static final int ANIMATION_VORKATH_DEATH = 7949; private static final int ANIMATION_SPAWN_DEATH = 7891; private static final String NPC_NAME_VORKATH = "Vorkath"; private static final String NPC_NAME_SPAWN = "Zombified Spawn"; private static final int ATTACKS_AMOUNT_BETWEEN_SPECIAL_ATTACK = 6; private static final int AMOUNT_OF_POISON_BOLTS = 25; @Inject private Client client; @Inject private OverlayManager overlayManager; @Inject private VorkathAttacksOverlay vorkathAttacksOverlay; @Inject private VorkathSceneOverlay vorkathSceneOverlay; @Getter private int normalAttackCounter; @Getter private int poisonBoltsCounter = 0; @Getter private boolean isInVorkathArea; @Getter private VorkathState vorkathState; private VorkathState nextSpecialAttack; @Getter private LocalPoint fireBombHitLocation; @Getter private NPC spawnNpc; boolean isZombieSpawnAlive = false; VorkathState getNextSpecialAttack() { if (nextSpecialAttack == null) { return VorkathState.IDLE; } return nextSpecialAttack; } int getAttacksAmountUntilSpecialAttack(){ return ATTACKS_AMOUNT_BETWEEN_SPECIAL_ATTACK - normalAttackCounter; } int getAmountOfPoisonBoltsLeft(){ return AMOUNT_OF_POISON_BOLTS - poisonBoltsCounter; } @Override protected void startUp() throws Exception { overlayManager.add(vorkathAttacksOverlay); overlayManager.add(vorkathSceneOverlay); reset(); } @Override protected void shutDown() throws Exception { overlayManager.remove(vorkathAttacksOverlay); overlayManager.remove(vorkathSceneOverlay); } private void reset() { normalAttackCounter = 0; poisonBoltsCounter = 0; vorkathState = VorkathState.IDLE; nextSpecialAttack = VorkathState.IDLE; } @Subscribe public void onAnimationChanged(AnimationChanged event) { Actor actor = event.getActor(); if (actor instanceof NPC) { NPC npc = (NPC) actor; if (npc.getName() != null && npc.getName().equals(NPC_NAME_VORKATH)) { switch (npc.getAnimation()) { case ANIMATION_VORKATH_WAKE_UP: onCombatStarted(); break; case ANIMATION_VORKATH_DEATH: onCombatEnded(); break; case ANIMATION_SPAWN_DEATH: isZombieSpawnAlive = false; } } } } @Subscribe public void onNpcSpawned(NpcSpawned npcSpawned) { final NPC npc = npcSpawned.getNpc(); final String npcName = npc.getName(); if (npcName != null){ if (npcName.contains(NPC_NAME_VORKATH)){ isInVorkathArea = true; reset(); } else if (npcName.contains(NPC_NAME_SPAWN)){ spawnNpc = npc; isZombieSpawnAlive = true; } } } @Subscribe public void onNpcDespawned(NpcDespawned npcDespawned) { final NPC npc = npcDespawned.getNpc(); final String npcName = npc.getName(); if (npcName != null) { if (npcName.contains(NPC_NAME_VORKATH)) { isInVorkathArea = false; reset(); } else if (npcName.contains(NPC_NAME_SPAWN)) { isZombieSpawnAlive = false; } } } @Subscribe public void onProjectileMoved(ProjectileMoved event) { Projectile projectile = event.getProjectile(); if (projectile.getInteracting() != null && client.getGameCycle() >= projectile.getStartMovementCycle()) { return; } int projectileId = projectile.getId(); switch (projectileId) { case VorkathProjectileID.VORKATH_DRAGONBREATH: onDragonBreathAttack(); break; case VorkathProjectileID.VORKATH_RANGED: onRangeAttack(); break; case VorkathProjectileID.VORKATH_MAGIC: onMagicAttack(); break; case VorkathProjectileID.VORKATH_VENOM: onVenomAttack(); break; case VorkathProjectileID.VORKATH_PRAYER_DISABLE: onPrayerDisableAttack(); break; case VorkathProjectileID.VORKATH_BOMB_AOE: onFireBombAttack(); break; case VorkathProjectileID.VORKATH_FREEZE: onFreezeAttack(); break; case VorkathProjectileID.VORKATH_SPAWN_AOE: onMinionSpawn(); break; case ProjectileID.VORKATH_TICK_FIRE_AOE: onPoisonFireAttack(); break; } } @Subscribe public void onGameState(GameStateChanged event) { GameState gs = event.getGameState(); if (gs == GameState.LOGGING_IN || gs == GameState.CONNECTION_LOST || gs == GameState.HOPPING) { reset(); } } @Subscribe public void onLocalPlayerDeath(LocalPlayerDeath player) { reset(); } private void onCombatStarted() { reset(); } private void onCombatEnded() { reset(); } private void onDragonBreathAttack() { normalAttackCounter++; vorkathState = VorkathState.DRAGON_BREATH_ATTACK; } private void onRangeAttack() { normalAttackCounter++; vorkathState = VorkathState.RANGED_ATTACK; } private void onMagicAttack() { normalAttackCounter++; vorkathState = VorkathState.MAGIC_ATTACK; } private void onVenomAttack() { normalAttackCounter++; System.out.println("venom"); vorkathState = VorkathState.VENOM_ATTACK; } private void onFireBombAttack() { normalAttackCounter++; fireBombHitLocation = client.getLocalPlayer().getLocalLocation(); vorkathState = VorkathState.FIRE_BOMB_ATTACK; } private void onPrayerDisableAttack() { normalAttackCounter++; System.out.println("prayer"); vorkathState = VorkathState.PRAYER_DISABLE_ATTACK; } private void onFreezeAttack() { normalAttackCounter = 0; vorkathState = VorkathState.FREEZE_SPECIAL_ATTACK; nextSpecialAttack = VorkathState.POISON_FIRE_SPECIAL_ATTACK; } private void onPoisonFireAttack() { normalAttackCounter = 0; poisonBoltsCounter++; if (poisonBoltsCounter == AMOUNT_OF_POISON_BOLTS){ System.out.println("done"); poisonBoltsCounter = 0; } vorkathState = VorkathState.POISON_FIRE_SPECIAL_ATTACK; nextSpecialAttack = VorkathState.FREEZE_SPECIAL_ATTACK; } private void onMinionSpawn() { System.out.println("spawn"); } }
21.20743
71
0.746569
769c6b30cdbf2ba51e7d0fb6d4bda2e45af2a094
4,740
package net.minestom.server.gamedata.loottables; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import net.minestom.server.gamedata.Condition; import net.minestom.server.registry.ResourceGatherer; import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.NamespaceIDHashMap; import java.io.*; /** * Handles loading and configuration of loot tables */ public class LootTableManager { private NamespaceIDHashMap<JsonDeserializer<? extends Condition>> conditionDeserializers = new NamespaceIDHashMap<>(); private NamespaceIDHashMap<LootTableType> tableTypes = new NamespaceIDHashMap<>(); private NamespaceIDHashMap<LootTableEntryType> entryTypes = new NamespaceIDHashMap<>(); private NamespaceIDHashMap<LootTableFunction> functions = new NamespaceIDHashMap<>(); private NamespaceIDHashMap<LootTable> cache = new NamespaceIDHashMap<>(); private Gson gson; public LootTableManager() { gson = new GsonBuilder() .registerTypeAdapter(RangeContainer.class, new RangeContainer.Deserializer()) .registerTypeAdapter(ConditionContainer.class, new ConditionContainer.Deserializer(this)) .create(); } /** * Registers a condition factory to the given namespaceID * @param namespaceID * @param factory */ public <T extends Condition> void registerConditionDeserializer(NamespaceID namespaceID, JsonDeserializer<T> factory) { conditionDeserializers.put(namespaceID, factory); } /** * Registers a loot table type to the given namespaceID * @param namespaceID * @param type */ public void registerTableType(NamespaceID namespaceID, LootTableType type) { tableTypes.put(namespaceID, type); } /** * Registers a loot table entry type to the given namespaceID * @param namespaceID * @param type */ public void registerEntryType(NamespaceID namespaceID, LootTableEntryType type) { entryTypes.put(namespaceID, type); } /** * Registers a loot table function to the given namespaceID * @param namespaceID * @param function */ public void registerFunction(NamespaceID namespaceID, LootTableFunction function) { functions.put(namespaceID, function); } public LootTable load(NamespaceID name) throws FileNotFoundException { return load(name, new FileReader(new File(ResourceGatherer.DATA_FOLDER, "data/"+name.getDomain()+"/loot_tables/"+name.getPath()+".json"))); } /** * Loads a loot table with the given name. Loot tables can be cached, so 'reader' is used only on cache misses * @param name the name to cache the loot table with * @param reader the reader to read the loot table from, if none cached. **Will** be closed no matter the results of this call * @return */ public LootTable load(NamespaceID name, Reader reader) { try { return cache.computeIfAbsent(name, _name -> create(reader)); } finally { try { reader.close(); } catch (IOException e) {} } } private LootTable create(Reader reader) { LootTableContainer container = gson.fromJson(reader, LootTableContainer.class); return container.createTable(this); } /** * Returns the registered table type corresponding to the given namespace ID. If none is registered, throws {@link IllegalArgumentException} * @param id * @return */ public LootTableType getTableType(NamespaceID id) { if(!tableTypes.containsKey(id)) throw new IllegalArgumentException("Unknown table type: "+id); return tableTypes.get(id); } /** * Returns the registered entry type corresponding to the given namespace ID. If none is registered, throws {@link IllegalArgumentException} * @param id * @return */ public LootTableEntryType getEntryType(NamespaceID id) { if(!entryTypes.containsKey(id)) throw new IllegalArgumentException("Unknown entry type: "+id); return entryTypes.get(id); } /** * Returns the registered table type corresponding to the given namespace ID. If none is registered, returns {@link LootTableFunction#IDENTITY} * @param id * @return */ public LootTableFunction getFunction(NamespaceID id) { return functions.getOrDefault(id, LootTableFunction.IDENTITY); } public JsonDeserializer<? extends Condition> getConditionDeserializer(NamespaceID id) { return conditionDeserializers.getOrDefault(id, (json, typeOfT, context) -> Condition.ALWAYS_NO); } }
37.03125
147
0.691983
e4ee67b5c315e6ed263121e0fa97a899156e9cd2
10,124
package de.ieg.infra.utils; import java.io.File; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.faces.FactoryFinder; import javax.faces.application.Application; import javax.faces.application.ApplicationFactory; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.el.ValueBinding; import javax.faces.event.FacesEvent; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author steinkamp * Utility class * */ public class Utils { /** * Get servlet context. * * @return the servlet context */ public static ServletContext getServletContext() { return (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext(); } /** * @return the spring application context */ public static ApplicationContext getApplicationContext() { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); return ctx; } /** * Get managed bean based on the bean name. * * @param beanName the bean name * @return the managed bean associated with the bean name */ public static Object getManagedBean(String beanName) { Object o = getValueBinding(getJsfEl(beanName)).getValue(FacesContext.getCurrentInstance()); return o; } /** * Remove the managed bean based on the bean name. * * @param beanName the bean name of the managed bean to be removed */ public static void resetManagedBean(String beanName) { getValueBinding(getJsfEl(beanName)).setValue(FacesContext.getCurrentInstance(), null); } /** * Store the managed bean inside the session scope. * * @param beanName the name of the managed bean to be stored * @param managedBean the managed bean to be stored */ public static void setManagedBeanInSession(String beanName, Object managedBean) { FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(beanName, managedBean); } /** * Get parameter value from request scope. * * @param name the name of the parameter * @return the parameter value * * Works only with the commandLink and the outputLink * Example: * <h:commandLink action="#{myBean.action}"> *<f:param name="paramname1" value="paramvalue1" /> *<f:param name="paramname2" value="paramvalue2" /> *<h:outputText value="Click here" /> *</h:commandLink> */ public static Object getRequestParameter(String name) { return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(name); } /** * Retrieve parameters from FacesEvents. Works with the CommandLink and the * Command button * @param ev an FacesEvent * @param key the attribute name * @return the parameter value * * Example *<h:commandLink actionListener="#{myBean.action}"> *<f:attribute name="attrname1" value="attrvalue1" /> *<f:attribute name="attrname2" value="attrvalue2" /> * <h:outputText value="Click here" /> * </h:commandLink> */ public static Object getAttributeFromEvent(FacesEvent ev,String key) { Object attrValue = ev.getComponent().getAttributes().get(key); return attrValue; } /** * Add information message to a sepcific client and log debug message. * * @param clientId the client id * @param msg the information message */ public static void addInfoMessage(String clientId, String msg) { FacesContext.getCurrentInstance().addMessage(clientId, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg)); } /** * Add error message to a sepcific client. * * @param clientId the client id * @param msg the error message */ public static void addErrorMessage(String clientId, String msg) { FacesContext.getCurrentInstance().addMessage(clientId, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg)); } /** * Sets an request attribute * @param attName * @param attValue */ public static void setRequestAttribute(String attName, Object attValue) { getServletRequest().setAttribute(attName, attValue); } /** * Returns a session attribute * @param attName * @return */ public static Object getSessionAttribute(String attName) { return getServletRequest().getSession().getAttribute(attName); } /** * Remose a session attribute * @param attName */ public static void removeSessionAttribute(String attName) { getServletRequest().getSession().removeAttribute(attName); } /** * Returns a HttpServletresponse * @return */ public static HttpServletResponse getServletResponse() { return (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); } /** * Retruns the application context * @return */ private static Application getApplication() { ApplicationFactory appFactory = (ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); return appFactory.getApplication(); } /** * @param el * @return */ private static ValueBinding getValueBinding(String el) { return getApplication().createValueBinding(el); } /** * Returns a HttpServletRequest * @return */ private static HttpServletRequest getServletRequest() { return (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); } /** * @param value * @return */ private static String getJsfEl(String value) { return "#{" + value + "}"; } /** * Returns a message string from the message bundle * @param bundleName * @param id * @param params * @param locale * @return */ public static String getDisplayString(String bundleName, String id, Object params[], Locale locale) { String text = null; ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale, getCurrentClassLoader(params)); try { text = bundle.getString(id); } catch (MissingResourceException e) { text = "!! key " + id + " not found !!"; } if (params != null) { MessageFormat mf = new MessageFormat(text, locale); text = mf.format(params, new StringBuffer(), null).toString(); } return text; } /** * @param defaultObject * @return */ protected static ClassLoader getCurrentClassLoader(Object defaultObject) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = defaultObject.getClass().getClassLoader(); } return loader; } /** * Adds a new entry to the session map * @param key * @param ob */ public static void addToSessionMap(String key,Object ob) { getSessionMap().put(key, ob); } /** * Returns the session map * @return */ public static Map getSessionMap() { return FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); } /** * Returns a value from the session map * @param key * @return */ public static Object getValueFromSessionMap(String key) { return getSessionMap().get(key); } /** * Returns the remote ip address from a servlet requester * @return */ public static String getIpAddress() { String ipAddress = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRemoteAddr(); return ipAddress; } /** * Returns the url of the application context * @return */ public static String getContextURL () { FacesContext context = FacesContext.getCurrentInstance(); String contextPath = context.getExternalContext().getRequestContextPath(); String url = ((HttpServletRequest)context.getExternalContext().getRequest()).getRequestURL().toString(); url = url.substring(0, url.indexOf(contextPath, url.indexOf("/"))) + contextPath; return url; } /** * Returns the path of the application context * @return */ public static String getContextPath() { FacesContext context = FacesContext.getCurrentInstance(); return context.getExternalContext().getRequestContextPath(); } /** * Returns the complete path for the passed directory * @param directory * @return */ public static String getPath4Directory(String directory) { ServletContext context = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext(); return context.getRealPath(directory); } /** * Returns a file list for the passed directory * @param directory * @return */ public static List getFileList (String directory) { List fileList = new ArrayList(); String path = Utils.getPath4Directory(directory); File dir = new File(path); File [] files= dir.listFiles(); if (files== null) { return fileList; }else { for (int i=0;i < files.length;i++){ File reportFile = files[i]; if (reportFile.isFile()) { fileList.add(files[i]); } } } return fileList; } /** * Returns the param value that fits to the passed param name * @param name * @return */ public static String getFacesParamValue(String name) { return (String)FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(name); } public static String formatDate(Date date) { String sDate=null; SimpleDateFormat formatter= new SimpleDateFormat("dd.MM.yyyy"); try { sDate=formatter.format(date); } catch(Exception ex) { Logger.getLogger(Utils.class).error("formatDate() creates an error " + ex.getMessage()); } return sDate; } }
27.889807
128
0.691229
1243df79a98c5711090131e64ebe60710ff178f3
2,835
package com.cottee.managerstore.adapter; import android.content.Context; import android.content.Intent; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; import com.cottee.managerstore.R; import com.cottee.managerstore.activity.ChangeVIPStandardActivity; import com.cottee.managerstore.bean.VIPStandard; import java.util.List; /** * Created by Administrator on 2017-11-14. */ public class VIPStandardAdapter extends BaseAdapter { private Context context; private List<VIPStandard> vipStandardList; public VIPStandardAdapter(Context context, List<VIPStandard> list) { this.context = context; this.vipStandardList = list; } @Override public int getCount() { return vipStandardList.size(); } @Override public Object getItem(int i) { return vipStandardList.get( i ); } @Override public long getItemId(int i) { return i; } @Override public View getView(final int i, View view, ViewGroup viewGroup) { final ViewHolder viewHolder; if (view == null) { viewHolder = new ViewHolder(); view = View.inflate( context, R.layout.item_vipstandard, null ); // viewHolder.tv_vipLevelNumber = view.findViewById( R.id.tv_vipnumber ); viewHolder.tv_vipname = view.findViewById( R.id.tv_vipname ); viewHolder.tv_min = view.findViewById( R.id.tv_min ); viewHolder.discount = view.findViewById( R.id.tv_discount ); viewHolder.btn_change=view.findViewById( R.id.btn_vip_change ); viewHolder.tv_level=view.findViewById( R .id.tv_level); view.setTag( viewHolder ); } else { viewHolder = (ViewHolder) view.getTag(); } viewHolder.tv_vipname.setText( vipStandardList.get( i ).getVIP_name() ); viewHolder.tv_min.setText( vipStandardList.get( i ).getMin_num() ); viewHolder.discount.setText( vipStandardList.get( i ).getDiscount() ); viewHolder.btn_change.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ChangeVIPStandardActivity.class); intent.putExtra( "vip",vipStandardList.get( i ) ); intent.putExtra( "level",i+1 ); context.startActivity( intent ); } } ); viewHolder.tv_level.setText( "VIP"+(i+1) ); return view; } public static class ViewHolder { TextView tv_vipname;//等级名称 TextView tv_min;//等级积分 // TextView tv_vipLevelNumber;//等级人数 TextView discount;//优惠折扣 Button btn_change; TextView tv_level; } }
32.965116
85
0.649735
66df0461102fbcd573f3aba8e3570e8020fb8dea
631
package ru.vyarus.guice.ext.managed.destroyable; import java.lang.reflect.Method; /** * Destroyable annotation used to call @PostConstruct annotated methods on context destroy. * * @author Vyacheslav Rusakov * @since 30.06.2014 */ public class AnnotatedMethodDestroyable implements Destroyable { private final Method method; private final Object instance; public AnnotatedMethodDestroyable(final Method method, final Object instance) { this.method = method; this.instance = instance; } @Override public void preDestroy() throws Exception { method.invoke(instance); } }
24.269231
91
0.721078
944037a5cef434ed173f3368636c42832833ae8c
3,535
package tk.beason.common.utils.location; import android.app.Dialog; import android.content.Context; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import tk.beason.common.entries.Location; import tk.beason.common.utils.log.LogManager; /** * 位置信息获取 * modify by beasontk on 2018-06-22 */ public class LocationUtils { private static final String TAG = "LocationUtils"; /** * 获取当前位置信息 */ @SuppressWarnings("WeakerAccess") public static void getLocation(final Context context, final OnLocationListener listener) { LocationClientOption option = new LocationClientOption(); /* * 设置为高精度模式 * LocationMode.Hight_Accuracy:高精度 * LocationMode. Battery_Saving:低功耗 * LocationMode. Device_Sensors:仅使用设备 */ option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); /* * 设置返回经纬度坐标类型 * gcj02:国测局坐标; * bd09ll:百度经纬度坐标; * bd09:百度墨卡托坐标; * 海外地区定位,无需设置坐标类型,统一返回wgs84类型坐标 */ option.setCoorType("gcj02"); option.setIsNeedAddress(true); option.setOpenGps(true); final LocationClient client = new LocationClient(context.getApplicationContext()); client.registerLocationListener(new BaiduLocationListener(client, listener)); client.setLocOption(option); client.start(); // 如果之前已经获取到 那么先把之前获取到的提供出来 notificationOnReceiveLocation(listener, client.getLastKnownLocation()); } /** * 获取当前位置信息 * * @param dialog Loading显示的逻辑,在APP层面进行实现 */ @Deprecated public static void getCurrentLocation(final Context context, final Dialog dialog, final OnLocationListener listener) { getLocation(context, listener); } /** * 注销位置监听 */ private static void unregisterLocationListener(LocationClient client, BDLocationListener listener) { if (client != null) { client.stop(); client.unRegisterLocationListener(listener); } } /** * 通知已经接收到位置信息 */ private static void notificationOnReceiveLocation(OnLocationListener listener, BDLocation bdLocation) { if (listener == null || bdLocation == null) { LogManager.e(TAG, "notificationOnReceiveLocation: listener is null or BDLocation is null"); return; } Location location = new Location(); location.setLatitude(bdLocation.getLatitude()); location.setLongitude(bdLocation.getLongitude()); location.setAddress(bdLocation.getAddress()); listener.onReceiveLocation(location); } /** * 百度的位置监听 */ private static class BaiduLocationListener implements BDLocationListener { /** * 百度的Location信息 */ private LocationClient mLocationClient; /** * BaseLib中的监听回调 */ private OnLocationListener mListener; private BaiduLocationListener(LocationClient client, OnLocationListener listener) { mListener = listener; mLocationClient = client; } @Override public void onReceiveLocation(BDLocation bdLocation) { LogManager.d(TAG, "位置信息: " + bdLocation.getAddrStr()); notificationOnReceiveLocation(mListener, bdLocation); unregisterLocationListener(mLocationClient, this); } } }
30.474138
122
0.65686
b4aed4361ea53b69c31fac09ab1d804aa4051281
2,564
package org.fandev.utils; import javax.annotation.Nullable; import org.fandev.lang.fan.psi.api.modifiers.FanModifierListOwner; import org.fandev.lang.fan.psi.api.statements.FanTopLevelDefintion; import org.fandev.lang.fan.psi.api.statements.typeDefs.FanTypeDefinition; import org.fandev.lang.fan.psi.api.statements.typeDefs.members.FanMember; import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; /** * @author Dror Bereznitsky * @date Feb 21, 2009 3:30:29 PM */ public class PsiUtil { public static boolean isAccessible(final PsiElement place, final FanMember member) { return true; //TODO [VISTALL] } public static int getFlags(final FanModifierListOwner paramPsiModifierListOwner, final boolean paramBoolean) { final PsiFile localPsiFile = paramPsiModifierListOwner.getContainingFile(); final VirtualFile localVirtualFile = (localPsiFile == null) ? null : localPsiFile.getVirtualFile(); final int enumFlag = ((paramPsiModifierListOwner instanceof FanTypeDefinition) && (((FanTypeDefinition) paramPsiModifierListOwner).isEnum())) ? 1 : 0; int mainFlag = (((paramPsiModifierListOwner.hasModifierProperty("final")) && (enumFlag == 0)) ? 1024 : 0) | (((paramPsiModifierListOwner.hasModifierProperty("static")) && (enumFlag == 0)) ? 512 : 0) | ((paramBoolean) ? 2048 : 0) | ((isExcluded(localVirtualFile, paramPsiModifierListOwner.getProject())) ? 4096 : 0); if(paramPsiModifierListOwner instanceof FanTypeDefinition) { if((paramPsiModifierListOwner.hasModifierProperty("abstract")) && (!(((FanTypeDefinition) paramPsiModifierListOwner).isInterface()))) { mainFlag |= 256; } } return mainFlag; } public static boolean isExcluded(final VirtualFile paramVirtualFile, final Project paramProject) { return ((paramVirtualFile != null) && (ProjectRootManager.getInstance(paramProject).getFileIndex().isInSource(paramVirtualFile)) && (CompilerManager.getInstance(paramProject).isExcludedFromCompilation(paramVirtualFile))); } @Nullable public static FanTopLevelDefintion findPreviousTopLevelElementByThisElement(final PsiElement element) { PsiElement parent = element.getParent(); while(parent != null && !(parent instanceof FanTopLevelDefintion)) { parent = parent.getParent(); } if(parent == null) { return null; } return ((FanTopLevelDefintion) parent); } }
35.123288
152
0.765211
a3211398802900fcc4ae841ed098777a444cadd7
10,727
/* * Copyright (C) 2014 Square, 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 okhttp3; import java.io.IOException; import java.net.ProtocolException; import java.util.logging.Level; import okhttp3.internal.NamedRunnable; import okhttp3.internal.http.HttpEngine; import okhttp3.internal.http.RequestException; import okhttp3.internal.http.RouteException; import okhttp3.internal.http.StreamAllocation; import static okhttp3.internal.Internal.logger; import static okhttp3.internal.http.HttpEngine.MAX_FOLLOW_UPS; final class RealCall implements Call { private final OkHttpClient client; // Guarded by this. private boolean executed; volatile boolean canceled; /** * The application's original request unadulterated by redirects or auth headers. */ Request originalRequest; HttpEngine engine; protected RealCall(OkHttpClient client, Request originalRequest) { this.client = client; this.originalRequest = originalRequest; } @Override public Request request() { return originalRequest; } @Override public Response execute() throws IOException { synchronized (this) { if (executed) throw new IllegalStateException("Already Executed"); executed = true; } try { client.dispatcher().executed(this); Response result = getResponseWithInterceptorChain(false); if (result == null) throw new IOException("Canceled"); return result; } finally { client.dispatcher().finished(this); } } Object tag() { return originalRequest.tag(); } @Override public void enqueue(Callback responseCallback) { enqueue(responseCallback, false); } void enqueue(Callback responseCallback, boolean forWebSocket) { synchronized (this) { if (executed) throw new IllegalStateException("Already Executed"); executed = true; } client.dispatcher().enqueue(new AsyncCall(responseCallback, forWebSocket)); } @Override public void cancel() { canceled = true; if (engine != null) engine.cancel(); } @Override public synchronized boolean isExecuted() { return executed; } @Override public boolean isCanceled() { return canceled; } final class AsyncCall extends NamedRunnable { private final Callback responseCallback; private final boolean forWebSocket; private AsyncCall(Callback responseCallback, boolean forWebSocket) { super("OkHttp %s", originalRequest.url().toString()); this.responseCallback = responseCallback; this.forWebSocket = forWebSocket; } String host() { return originalRequest.url().host(); } Request request() { return originalRequest; } Object tag() { return originalRequest.tag(); } void cancel() { RealCall.this.cancel(); } RealCall get() { return RealCall.this; } @Override protected void execute() { boolean signalledCallback = false; try { Response response = getResponseWithInterceptorChain(forWebSocket); if (canceled) { signalledCallback = true; responseCallback.onFailure(RealCall.this, new IOException("Canceled")); } else { signalledCallback = true; responseCallback.onResponse(RealCall.this, response); } } catch (IOException e) { if (signalledCallback) { // Do not signal the callback twice! logger.log(Level.INFO, "Callback failure for " + toLoggableString(), e); } else { responseCallback.onFailure(RealCall.this, e); } } finally { client.dispatcher().finished(this); } } } /** * Returns a string that describes this call. Doesn't include a full URL as that might contain * sensitive information. */ private String toLoggableString() { String string = canceled ? "canceled call" : "call"; HttpUrl redactedUrl = originalRequest.url().resolve("/..."); return string + " to " + redactedUrl; } private Response getResponseWithInterceptorChain(boolean forWebSocket) throws IOException { Interceptor.Chain chain = new ApplicationInterceptorChain(0, originalRequest, forWebSocket); return chain.proceed(originalRequest); } class ApplicationInterceptorChain implements Interceptor.Chain { private final int index; private final Request request; private final boolean forWebSocket; ApplicationInterceptorChain(int index, Request request, boolean forWebSocket) { this.index = index; this.request = request; this.forWebSocket = forWebSocket; } @Override public Connection connection() { return null; } @Override public Request request() { return request; } @Override public Response proceed(Request request) throws IOException { // If there's another interceptor in the chain, call that. if (index < client.interceptors().size()) { Interceptor.Chain chain = new ApplicationInterceptorChain(index + 1, request, forWebSocket); Interceptor interceptor = client.interceptors().get(index); Response interceptedResponse = interceptor.intercept(chain); if (interceptedResponse == null) { throw new NullPointerException("application interceptor " + interceptor + " returned null"); } return interceptedResponse; } // No more interceptors. Do HTTP. return getResponse(request, forWebSocket); } } /** * Performs the request and returns the response. May return null if this call was canceled. */ Response getResponse(Request request, boolean forWebSocket) throws IOException { // Copy body metadata to the appropriate request headers. RequestBody body = request.body(); if (body != null) { Request.Builder requestBuilder = request.newBuilder(); MediaType contentType = body.contentType(); if (contentType != null) { requestBuilder.header("Content-Type", contentType.toString()); } long contentLength = body.contentLength(); if (contentLength != -1) { requestBuilder.header("Content-Length", Long.toString(contentLength)); requestBuilder.removeHeader("Transfer-Encoding"); } else { requestBuilder.header("Transfer-Encoding", "chunked"); requestBuilder.removeHeader("Content-Length"); } request = requestBuilder.build(); } // Create the initial HTTP engine. Retries and redirects need new engine for each attempt. engine = new HttpEngine(client, request, false, false, forWebSocket, null, null, null); int followUpCount = 0; while (true) { if (canceled) { engine.releaseStreamAllocation(); throw new IOException("Canceled"); } boolean releaseConnection = true; try { engine.sendRequest(); engine.readResponse(); releaseConnection = false; } catch (RequestException e) { // The attempt to interpret the request failed. Give up. throw e.getCause(); } catch (RouteException e) { // The attempt to connect via a route failed. The request will not have been sent. HttpEngine retryEngine = engine.recover(e.getLastConnectException(), null); if (retryEngine != null) { releaseConnection = false; engine = retryEngine; continue; } // Give up; recovery is not possible. throw e.getLastConnectException(); } catch (IOException e) { // An attempt to communicate with a server failed. The request may have been sent. HttpEngine retryEngine = engine.recover(e, null); if (retryEngine != null) { releaseConnection = false; engine = retryEngine; continue; } // Give up; recovery is not possible. throw e; } finally { // We're throwing an unchecked exception. Release any resources. if (releaseConnection) { StreamAllocation streamAllocation = engine.close(); streamAllocation.release(); } } Response response = engine.getResponse(); Request followUp = engine.followUpRequest(); if (followUp == null) { if (!forWebSocket) { engine.releaseStreamAllocation(); } return response; } StreamAllocation streamAllocation = engine.close(); if (++followUpCount > MAX_FOLLOW_UPS) { streamAllocation.release(); throw new ProtocolException("Too many follow-up requests: " + followUpCount); } if (!engine.sameConnection(followUp.url())) { streamAllocation.release(); streamAllocation = null; } request = followUp; engine = new HttpEngine(client, request, false, false, forWebSocket, streamAllocation, null, response); } } }
33.946203
108
0.582922
9cfd795044cdea1142eccf2955c3eec120336c87
28,896
package com.shokry.games.states; import static com.shokry.games.handlers.B2DVars.PPM; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.maps.MapLayer; import com.badlogic.gdx.maps.MapObject; import com.badlogic.gdx.maps.objects.EllipseMapObject; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.math.Ellipse; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.badlogic.gdx.physics.box2d.ChainShape; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.MassData; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Array; import com.shokry.games.Game; import com.shokry.games.entities.Bridge; import com.shokry.games.entities.Bullet; import com.shokry.games.entities.Crystal; import com.shokry.games.entities.Gun; import com.shokry.games.entities.HUD; import com.shokry.games.entities.Ladder; import com.shokry.games.entities.MovingPlatform; import com.shokry.games.entities.Player; import com.shokry.games.entities.Spike; import com.shokry.games.entities.Spring; import com.shokry.games.entities.Tunnel; import com.shokry.games.entities.EnemySnail; import com.shokry.games.handlers.B2DVars; import com.shokry.games.handlers.GameContactListener; import com.shokry.games.handlers.GameInput; import com.shokry.games.handlers.Background; import com.shokry.games.handlers.BoundedCamera; import com.shokry.games.handlers.GameStateManager; public class Play extends GameState { private boolean debug = false; //Set to true to see body boundaries private static final float WAIT_TIME = 3f; public static int crystalNum; public static int bulletNum; public static float time ; public static int health ; //modified in Contact listener public static World world; private Box2DDebugRenderer b2dRenderer; private GameContactListener cl; private BoundedCamera b2dCam; public static Player player; public static boolean facingRight = true; public static boolean rightFacingBodyCreated; public static boolean leftFacingBodyCreated; private TiledMap tileMap; private int tileMapWidth; private int tileMapHeight; private int tileSize; private OrthogonalTiledMapRenderer tmRenderer; private Array<Crystal> crystals; private Array<Spike> spikes; private Array<Ladder> ladders; private Array<MovingPlatform> movingPlaforms; private Array<Bullet> bullets; private Array<Gun> guns; private Array<Tunnel> tunnels; private Array<Bridge> bridges; private Array<EnemySnail> enemySnails; private Array<Spring> springs; // Make a platform velocity constant variable private boolean platformMovingRight; private Background[] backgrounds; private HUD hud; public static int level; public Play(GameStateManager gsm) { super(gsm); // set up the box2d world and contact listener world = new World(new Vector2(0, -7f), true); cl = new GameContactListener(); world.setContactListener(cl); b2dRenderer = new Box2DDebugRenderer(); //Creating objects from the tile map createPlayer(); createWalls(); cam.setBounds(0, tileMapWidth * tileSize, 0, tileMapHeight * tileSize); createCrystals(); player.setTotalCrystals(crystals.size); createSpikes(); createGuns(); createLadders(); createMovingPlatforms(); createTunnels(); //Falling bridges (count down-fall) createBridges(); //Enemy snails createSnails(); //Jumping springs createSprings(); // create backgrounds Texture bgs = Game.res.getTexture("bgs"); TextureRegion sky = new TextureRegion(bgs, 0, 0, 320, 240); TextureRegion clouds = new TextureRegion(bgs, 0, 240, 320, 240); TextureRegion mountains = new TextureRegion(bgs, 0, 480, 320, 240); backgrounds = new Background[3]; backgrounds[0] = new Background(sky, cam, 0f); backgrounds[1] = new Background(clouds, cam, 0.1f); backgrounds[2] = new Background(mountains, cam, 0.2f); // create hud hud = new HUD(player); // set up box2d cam b2dCam = new BoundedCamera(); b2dCam.setToOrtho(false, Game.V_WIDTH / PPM, Game.V_HEIGHT / PPM); b2dCam.setBounds(0, (tileMapWidth * tileSize) / PPM, 0, (tileMapHeight * tileSize) / PPM); } /** * Creates the player. Sets up the box2d body and sprites. */ private void createPlayer() { bullets = new Array <Bullet>(); BodyDef bdef = new BodyDef(); bdef.type = BodyType.DynamicBody; bdef.position.set(60 / PPM, 120 / PPM); bdef.fixedRotation = true; // create body from bodydef Body body = world.createBody(bdef); // create box shape for player collision box PolygonShape shape = new PolygonShape(); shape.setAsBox(13 / PPM, 13 / PPM); // create fixturedef for player collision box FixtureDef fdef = new FixtureDef(); fdef.shape = shape; fdef.density = 1; fdef.friction = 0; fdef.filter.categoryBits = B2DVars.BIT_PLAYER; fdef.filter.maskBits = B2DVars.BIT_BLOCK | B2DVars.BIT_CRYSTAL | B2DVars.BIT_SPIKE | B2DVars.BIT_LADDER | B2DVars.BIT_PLATFORM | B2DVars.BIT_GUN | B2DVars.BIT_TUNNEL | B2DVars.BIT_BRIDGE | B2DVars.BIT_SNAIL | B2DVars.BIT_SPRING; // create player collision box fixture body.createFixture(fdef).setUserData("player");; shape.dispose(); // create box shape for player foot shape = new PolygonShape(); shape.setAsBox(13 / PPM, 3 / PPM, new Vector2(0, -13 / PPM), 0); // create fixturedef for player foot fdef.shape = shape; fdef.isSensor = true; fdef.filter.categoryBits = B2DVars.BIT_PLAYER; fdef.filter.maskBits = B2DVars.BIT_BLOCK;; // create player foot fixture body.createFixture(fdef).setUserData("foot"); shape.dispose(); // create new player player = new Player(body); body.setUserData(player); // final tweaks, manually set the player body mass to 1 kg MassData md = body.getMassData(); md.mass = 1; body.setMassData(md); } /** * Sets up the tile map collidable tiles. Reads in tile map layers and sets * up box2d bodies. */ private void createWalls() { // load tile map and map renderer try { tileMap = new TmxMapLoader() .load("res/maps/level" + level + ".tmx"); } catch (Exception e) { System.out.println("Cannot find file: res/maps/level" + level + ".tmx"); Gdx.app.exit(); } tileMapWidth = (int) tileMap.getProperties() .get("width", Integer.class); tileMapHeight = (int) tileMap.getProperties().get("height", Integer.class); tileSize = (int) tileMap.getProperties() .get("tilewidth", Integer.class); tmRenderer = new OrthogonalTiledMapRenderer(tileMap); TiledMapTileLayer layer; layer = (TiledMapTileLayer) tileMap.getLayers().get("red"); createBlocks(layer, B2DVars.BIT_BLOCK); } /** * Creates box2d bodies for all non-null tiles in the specified layer and * assigns the specified category bits. * * @param layer * the layer being read * @param bits * category bits assigned to fixtures */ private void createBlocks(TiledMapTileLayer layer, short bits) { // tile size float ts = layer.getTileWidth(); // go through all cells in layer for (int row = 0; row < layer.getHeight(); row++) { for (int col = 0; col < layer.getWidth(); col++) { // get cell Cell cell = layer.getCell(col, row); // check that there is a cell if (cell == null) continue; if (cell.getTile() == null) continue; // create body from cell BodyDef bdef = new BodyDef(); bdef.type = BodyType.StaticBody; bdef.position.set((col + 0.5f) * ts / PPM, (row + 0.5f) * ts / PPM); ChainShape cs = new ChainShape(); Vector2[] v = new Vector2[3]; v[0] = new Vector2(-ts / 2 / PPM, -ts / 2 / PPM); v[1] = new Vector2(-ts / 2 / PPM, ts / 2 / PPM); v[2] = new Vector2(ts / 2 / PPM, ts / 2 / PPM); cs.createChain(v); FixtureDef fd = new FixtureDef(); fd.friction = 0.3f; fd.shape = cs; fd.filter.categoryBits = bits; fd.filter.maskBits = B2DVars.BIT_PLAYER | B2DVars.BIT_SNAIL | B2DVars.BIT_SPRING; world.createBody(bdef).createFixture(fd); cs.dispose(); } } } /** * Set up box2d bodies for crystals in tile map "crystals" layer */ private void createCrystals() { // create list of crystals crystals = new Array<Crystal>(); // get all crystals in "crystals" layer, // create bodies for each, and add them // to the crystals list MapLayer ml = tileMap.getLayers().get("crystals"); if (ml == null) { return; } for (MapObject mo : ml.getObjects()) { BodyDef cdef = new BodyDef(); cdef.type = BodyType.StaticBody; float x = 0, y = 0; if (mo instanceof EllipseMapObject) { Ellipse e = ((EllipseMapObject) mo).getEllipse(); x = e.x / PPM; y = e.y / PPM; } if (mo instanceof RectangleMapObject) { Rectangle r = ((RectangleMapObject) mo).getRectangle(); x = r.x; y = r.y; } cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); CircleShape cshape = new CircleShape(); cshape.setRadius(8 / PPM); cfdef.shape = cshape; cfdef.isSensor = true; cfdef.filter.categoryBits = B2DVars.BIT_CRYSTAL; cfdef.filter.maskBits = B2DVars.BIT_PLAYER; body.createFixture(cfdef).setUserData("crystal"); Crystal c = new Crystal(body); body.setUserData(c); crystals.add(c); cshape.dispose(); } } /** * Set up box2d bodies for spikes in "spikes" layer */ private void createSpikes() { spikes = new Array<Spike>(); MapLayer ml = tileMap.getLayers().get("spikes"); if (ml == null) return; for (MapObject mo : ml.getObjects()) { BodyDef cdef = new BodyDef(); cdef.type = BodyType.StaticBody; float x = 0, y = 0; if (mo instanceof EllipseMapObject) { Ellipse e = ((EllipseMapObject) mo).getEllipse(); x = e.x / PPM; y = e.y / PPM; } if (mo instanceof RectangleMapObject) { Rectangle r = ((RectangleMapObject) mo).getRectangle(); x = r.x; y = r.y; } cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); CircleShape cshape = new CircleShape(); cshape.setRadius(5 / PPM); cfdef.shape = cshape; cfdef.isSensor = true; cfdef.filter.categoryBits = B2DVars.BIT_SPIKE; cfdef.filter.maskBits = B2DVars.BIT_PLAYER; body.createFixture(cfdef).setUserData("spike"); Spike s = new Spike(body); body.setUserData(s); spikes.add(s); cshape.dispose(); } } /** * Set up box2d bodies for ladders in "ladder" layer */ private void createLadders() { ladders = new Array<Ladder>(); MapLayer ml = tileMap.getLayers().get("ladder"); if (ml == null) return; for (MapObject mo : ml.getObjects()) { BodyDef cdef = new BodyDef(); cdef.type = BodyType.StaticBody; float x = 0, y = 0; float w = 0, h = 0; if (mo instanceof RectangleMapObject) { Rectangle r = ((RectangleMapObject) mo).getRectangle(); x = r.x / PPM; y = (r.y * 2) / PPM; w = r.width; h = r.height; } cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); PolygonShape pshape = new PolygonShape(); pshape.setAsBox((w / 2) / PPM, (h / 4) / PPM); cfdef.shape = pshape; cfdef.isSensor = true; cfdef.filter.categoryBits = B2DVars.BIT_LADDER; cfdef.filter.maskBits = B2DVars.BIT_PLAYER ;//| B2DVars.BIT_BULLET; body.createFixture(cfdef).setUserData("ladder"); Ladder s = new Ladder(body); body.setUserData(s); ladders.add(s); pshape.dispose(); } } /** * Set up box2d bodies for moving platforms in "platform" layer */ private void createMovingPlatforms() { movingPlaforms = new Array<MovingPlatform>(); MapLayer ml = tileMap.getLayers().get("platform"); if (ml == null) return; for (MapObject mo : ml.getObjects()) { BodyDef cdef = new BodyDef(); cdef.type = BodyType.KinematicBody; float x = 0, y = 0, w, h; Rectangle r = ((RectangleMapObject) mo).getRectangle(); x = r.x / PPM; y = (r.y) / PPM; w = 70f / 2; h = 70f / 2; PolygonShape pshape = new PolygonShape(); pshape.setAsBox((w) / PPM, (h + 2f) / PPM); cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); cfdef.shape = pshape; cfdef.filter.categoryBits = B2DVars.BIT_PLATFORM; cfdef.filter.maskBits = B2DVars.BIT_PLAYER; body.createFixture(cfdef).setUserData("movingPlatform"); MovingPlatform s = new MovingPlatform(body); s.setCoordinates(x, y); body.setUserData(s); movingPlaforms.add(s); pshape.dispose(); } } /** * Set up box2d bodies for guns in "guns" layer */ private void createGuns() { guns = new Array<Gun>(); MapLayer ml = tileMap.getLayers().get("gun"); if (ml == null){ return; } for (MapObject mo : ml.getObjects()) { BodyDef cdef = new BodyDef(); cdef.type = BodyType.StaticBody; float x = 0, y = 0, w = 0, h = 0; if (mo instanceof RectangleMapObject) { Rectangle r = ((RectangleMapObject) mo).getRectangle(); x = r.x / PPM; y = (r.y) / PPM; w = Game.res.getTexture("raygun").getWidth()/2; h = Game.res.getTexture("raygun").getHeight()/2; } cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); PolygonShape pshape = new PolygonShape(); pshape.setAsBox((w / 2) / PPM, (h / 2) / PPM); cfdef.shape = pshape; cfdef.isSensor = true; cfdef.filter.categoryBits = B2DVars.BIT_GUN; cfdef.filter.maskBits = B2DVars.BIT_PLAYER; body.createFixture(cfdef).setUserData("gun"); Gun s = new Gun(body); body.setUserData(s); guns.add(s); pshape.dispose(); } } /** * Set up box2d bodies for tunnels in "tunnel" layer */ private void createTunnels() { tunnels = new Array<Tunnel>(); MapLayer ml = tileMap.getLayers().get("tunnel"); if (ml == null){ return; } for (MapObject mo : ml.getObjects()) { BodyDef cdef = new BodyDef(); cdef.type = BodyType.StaticBody; float x = 0, y = 0, w = 0, h = 0; if (mo instanceof RectangleMapObject) { Rectangle r = ((RectangleMapObject) mo).getRectangle(); x = r.x / PPM; y = (r.y) / PPM; w = Game.res.getTexture("tunnel").getWidth(); h = Game.res.getTexture("tunnel").getHeight(); } cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); PolygonShape pshape = new PolygonShape(); pshape.setAsBox((w / 2) / PPM, (h / 2) / PPM); cfdef.shape = pshape; cfdef.isSensor = true; cfdef.filter.categoryBits = B2DVars.BIT_TUNNEL; cfdef.filter.maskBits = B2DVars.BIT_PLAYER; body.createFixture(cfdef).setUserData("tunnel"); Tunnel s = new Tunnel(body); body.setUserData(s); tunnels.add(s); pshape.dispose(); } } /** * Set up box2d bodies for bridges in "bridge" layer */ private void createBridges() { bridges = new Array<Bridge>(); MapLayer ml = tileMap.getLayers().get("bridge"); if (ml == null){ return; } for (MapObject mo : ml.getObjects()) { BodyDef cdef = new BodyDef(); cdef.type = BodyType.KinematicBody; float x = 0, y = 0, w = 0, h = 0; if (mo instanceof RectangleMapObject) { Rectangle r = ((RectangleMapObject) mo).getRectangle(); x = r.x / PPM; y = (r.y) / PPM; w = Game.res.getTexture("bridge").getWidth(); h = Game.res.getTexture("bridge").getHeight(); } cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); PolygonShape pshape = new PolygonShape(); pshape.setAsBox((w / 2) / PPM, (h/2) / PPM); cfdef.shape = pshape; cfdef.filter.categoryBits = B2DVars.BIT_BRIDGE; cfdef.filter.maskBits = B2DVars.BIT_PLAYER; body.createFixture(cfdef).setUserData("bridge"); Bridge s = new Bridge(body); body.setUserData(s); bridges.add(s); pshape.dispose(); } } /** * Set up box2d bodies for snail enemies in "enemySnail" layer */ private void createSnails() { enemySnails = new Array<EnemySnail>(); MapLayer ml = tileMap.getLayers().get("enemySnail"); if (ml == null){ return; } for (MapObject mo : ml.getObjects()) { BodyDef cdef = new BodyDef(); cdef.type = BodyType.DynamicBody; float x = 0, y = 0, w = 0, h = 0; if (mo instanceof RectangleMapObject) { Rectangle r = ((RectangleMapObject) mo).getRectangle(); x = r.x / PPM; y = (r.y) / PPM; w = 54; h = 31; } cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); PolygonShape pshape = new PolygonShape(); pshape.setAsBox((w / 2) / PPM, (h/2) / PPM); cfdef.shape = pshape; cfdef.filter.categoryBits = B2DVars.BIT_SNAIL; cfdef.filter.maskBits = B2DVars.BIT_PLAYER | B2DVars.BIT_BLOCK | B2DVars.BIT_BULLET; body.createFixture(cfdef).setUserData("snail"); pshape.dispose(); pshape = new PolygonShape(); pshape.setAsBox(5 / PPM, (h/2) / PPM, new Vector2((float) -0.25, 2 / PPM), 0); // create fixturedef for snail head cfdef.shape = pshape; cfdef.isSensor = true; cfdef.filter.categoryBits = B2DVars.BIT_SNAIL; cfdef.filter.maskBits = B2DVars.BIT_PLAYER; // create snail head fixture body.createFixture(cfdef).setUserData("snailHead"); pshape.dispose(); EnemySnail s = new EnemySnail(body); body.setUserData(s); enemySnails.add(s); } } /** * Set up box2d bodies for springs in "spring" layer */ private void createSprings() { springs = new Array<Spring>(); MapLayer ml = tileMap.getLayers().get("spring"); if (ml == null){ return; } for (MapObject mo : ml.getObjects()) { BodyDef cdef = new BodyDef(); cdef.type = BodyType.DynamicBody; float x = 0, y = 0, w = 0, h = 0; if (mo instanceof RectangleMapObject) { Rectangle r = ((RectangleMapObject) mo).getRectangle(); x = r.x / PPM; y = (r.y) / PPM; w = Game.res.getTexture("springboardDown").getWidth(); h = Game.res.getTexture("springboardDown").getHeight(); } cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); PolygonShape pshape = new PolygonShape(); pshape.setAsBox((w / 2) / PPM, (h/2) / PPM); cfdef.shape = pshape; cfdef.filter.categoryBits = B2DVars.BIT_SPRING; cfdef.filter.maskBits = B2DVars.BIT_PLAYER | B2DVars.BIT_BLOCK; body.createFixture(cfdef).setUserData("spring"); pshape.dispose(); pshape = new PolygonShape(); pshape.setAsBox((w/2) / PPM, 3 / PPM, new Vector2(0, 17 / PPM), 0); // create fixturedef for snail head cfdef.shape = pshape; cfdef.isSensor = true; cfdef.filter.categoryBits = B2DVars.BIT_SPRING; cfdef.filter.maskBits = B2DVars.BIT_PLAYER; body.createFixture(cfdef).setUserData("springTop"); pshape.dispose(); Spring s = new Spring(body); body.setUserData(s); springs.add(s); } } /** * Apply upward force to player body. */ private void playerJump() { if (cl.playerCanJump()>0) { player.getBody().setLinearVelocity( player.getBody().getLinearVelocity().x, 0); player.getBody().applyForceToCenter(0, 200, true); Game.res.getSound("jump").play(); } } public void handleInput() { // keyboard input if (GameInput.isPressed(GameInput.BTNJMP)) { playerJump(); } if (GameInput.isDown(GameInput.BTNRIGHT)) { moveRight(true, true); } if (GameInput.isMvReleased(GameInput.BTNRIGHT)) { moveRight(false, true); } if (GameInput.isDown(GameInput.BTNLEFT)) { moveRight(true, false); } if (GameInput.isMvReleased(GameInput.BTNLEFT)) { moveRight(false, false); } if (GameInput.isDown(GameInput.BTNUP)) { climb(true); } if (GameInput.isClimbPressed(GameInput.BTNUP)) { climb(false); } if (GameInput.isPressed(GameInput.BTNFIRE)) { if(bulletNum>0) fire(); } // mouse/touch input for Android // left side of screen to switch blocks // right side of screen to jump if (GameInput.isDown()) { if (GameInput.x < Gdx.graphics.getWidth() / 2) { moveRight(true, false); } else { moveRight(true, true); } } if(GameInput.isPressed()){ if (GameInput.y < Gdx.graphics.getHeight() / 2){ playerJump(); } } } private void fire() { BodyDef cdef = new BodyDef(); cdef.type = BodyType.DynamicBody; float x = 0, y = 0; x = player.getBody().getPosition().x; y = player.getBody().getPosition().y; cdef.position.set(x, y); Body body = world.createBody(cdef); FixtureDef cfdef = new FixtureDef(); CircleShape pshape = new CircleShape(); pshape.setRadius((Game.res.getTexture("bullet").getWidth() / 2) / PPM); cfdef.shape = pshape; cfdef.filter.categoryBits = B2DVars.BIT_BULLET; cfdef.filter.maskBits = B2DVars.BIT_SNAIL | B2DVars.BIT_BLOCK; body.createFixture(cfdef).setUserData("bullet"); Bullet bullet = new Bullet(body); body.setUserData(bullet); if(facingRight) body.setLinearVelocity(2f, 0); else body.setLinearVelocity(-2f, 0); body.setGravityScale(0f); bullets.add(bullet); pshape.dispose(); bulletNum--; Game.res.getSound("WeaponBlow").play(); } private void climb(boolean upArrowPressed) { if (cl.isPlayerClimb()) { if (upArrowPressed) { player.getBody().setActive(true); player.getBody().setLinearVelocity( player.getBody().getLinearVelocity().x, 1f); } else { player.getBody().setActive(false); } } } private void moveRight(boolean pressed, boolean right) { if (pressed) { player.getBody().setActive(true); if (right) { player.getBody().setLinearVelocity(1f, player.getBody().getLinearVelocity().y); facingRight = true; if (!rightFacingBodyCreated && !cl.isPlayerClimb()) { player = new Player(player.getBody()); rightFacingBodyCreated = true; leftFacingBodyCreated = false; } } else { player.getBody().setLinearVelocity(-1f, player.getBody().getLinearVelocity().y); facingRight = false; if (!leftFacingBodyCreated && !cl.isPlayerClimb()) { player = new Player(player.getBody()); leftFacingBodyCreated = true; rightFacingBodyCreated = false; } } } else if (GameInput.isMvReleased(GameInput.BTNLEFT) && GameInput.isMvReleased(GameInput.BTNRIGHT)) { if (!cl.isPlayerOnPlatform()) player.getBody().setLinearVelocity(0f, player.getBody().getLinearVelocity().y); player.animatePlayer(true); } } public void update(float dt) { // check input handleInput(); // update box2d world world.step(Game.STEP, 1, 1); if(cl.isPlayerOnBridge()){ time += dt; if(time>=WAIT_TIME){ cl.getCurrentBridge().setLinearVelocity(0, -3f); // Reset timer (not set to 0) time -= WAIT_TIME; } } // check for collected crystals Array<Body> bodies = cl.getBodies(); for (int i = 0; i < bodies.size; i++) { Body b = bodies.get(i); if(b.getFixtureList().first().getUserData().equals("crystal")){ crystals.removeValue((Crystal) b.getUserData(), true); world.destroyBody(bodies.get(i)); crystalNum++; Game.res.getSound("crystal").play(); } else if(b.getFixtureList().first().getUserData().equals("bullet")){ bullets.removeValue((Bullet) b.getUserData(), true); world.destroyBody(bodies.get(i)); } else if(b.getFixtureList().first().getUserData().equals("gun")){ guns.removeValue((Gun) b.getUserData(), true); world.destroyBody(bodies.get(i)); } else if(b.getFixtureList().first().getUserData().equals("snail")){ enemySnails.removeValue((EnemySnail) b.getUserData(), true); world.destroyBody(bodies.get(i)); Game.res.getSound("enemyHit").play(); } } bodies.clear(); // update player player.update(dt); if(bullets != null) for (int i = 0; i < bullets.size; i++) { bullets.get(i).update(dt); } // check player win if (player.getBody().getPosition().x * PPM > tileMapWidth * tileSize) { Game.res.getSound("levelselect").play(); gsm.setState(GameStateManager.LEVEL_SELECT); } // check player failed if (player.getBody().getPosition().y < 0) { Game.res.getSound("hit").play(); gsm.setState(GameStateManager.LEVEL_SELECT); } if (cl.isPlayerDead()) { Game.res.getSound("hit").play(); gsm.setState(GameStateManager.LEVEL_SELECT); } if (cl.isPlayerOnPlatform()) { if (platformMovingRight == false) { player.getBody().setLinearVelocity(-.5f, player.getBody().getLinearVelocity().y); } else { player.getBody().setLinearVelocity(.5f, player.getBody().getLinearVelocity().y); } } if (cl.isPlayerOnSpring()) { player.getBody().setLinearVelocity(player.getBody().getLinearVelocity().x, 4f); } //Check if player is in a tunnel if(cl.isPlayerInTunnel()) { player.getBody().setTransform(player.getBody().getPosition().x+2f, player.getBody().getPosition().y, player.getBody().getAngle()); } // update crystals for (int i = 0; i < crystals.size; i++) { crystals.get(i).update(dt); } // update spikes for (int i = 0; i < spikes.size; i++) { spikes.get(i).update(dt); } // update ladders for (int i = 0; i < ladders.size; i++) { ladders.get(i).update(dt); } // update moving platforms for (int i = 0; i < movingPlaforms.size; i++) { movingPlaforms.get(i).update(dt); if (movingPlaforms.get(i).getPosition().x > movingPlaforms.get(i) .getCoordinates().x + .5) { movingPlaforms.get(i).getBody().setLinearVelocity(-.5f, 0); platformMovingRight = false; } else if (movingPlaforms.get(i).getPosition().x <= movingPlaforms .get(i).getCoordinates().x) { movingPlaforms.get(i).getBody().setLinearVelocity(.5f, 0); platformMovingRight = true; } } // update guns for (int i = 0; i < guns.size; i++) { guns.get(i).update(dt); } // update tunnels for (int i = 0; i < tunnels.size; i++) { tunnels.get(i).update(dt); } // update bridges for (int i = 0; i < bridges.size; i++) { bridges.get(i).update(dt); } // update jumping springs for (int i = 0; i < springs.size; i++) { springs.get(i).update(dt); } // update snails for (int i = 0; i < enemySnails.size; i++) { enemySnails.get(i).update(dt); } } public void render() { // camera to follow player cam.setPosition(player.getPosition().x * PPM + Game.V_WIDTH / 4, Game.V_HEIGHT / 2); cam.update(); // draw bgs sb.setProjectionMatrix(hudCam.combined); for (int i = 0; i < backgrounds.length; i++) { backgrounds[i].render(sb); } // draw tilemap tmRenderer.setView(cam); tmRenderer.render(); // Set camera sb.setProjectionMatrix(cam.combined); // draw ladders for (int i = 0; i < ladders.size; i++) { ladders.get(i).renderImg(sb); } // draw player player.render(sb); if (bullets !=null) for (int i = 0; i < bullets.size; i++) { bullets.get(i).renderImg(sb); } // draw crystals for (int i = 0; i < crystals.size; i++) { crystals.get(i).render(sb); } // draw spikes for (int i = 0; i < spikes.size; i++) { spikes.get(i).renderImg(sb); } // draw moving platforms for (int i = 0; i < movingPlaforms.size; i++) { movingPlaforms.get(i).renderImg(sb); } // draw guns for (int i = 0; i < guns.size; i++) { guns.get(i).renderImg(sb); } // draw tunnels for (int i = 0; i < tunnels.size; i++) { tunnels.get(i).renderImg(sb); } // draw bridges for (int i = 0; i < bridges.size; i++) { bridges.get(i).renderImg(sb); } // draw jumping springs for (int i = 0; i < springs.size; i++) { springs.get(i).renderImg(sb); } // draw Snails for (int i = 0; i < enemySnails.size; i++) { enemySnails.get(i).render(sb); } // draw hud sb.setProjectionMatrix(hudCam.combined); hud.render(sb); // debug draw box2d if (debug) { b2dCam.setPosition(player.getPosition().x + Game.V_WIDTH / 4 / PPM, Game.V_HEIGHT / 2 / PPM); b2dCam.update(); b2dRenderer.render(world, b2dCam.combined); } } public void dispose() { // everything is in the resource manager // com.shokry.games.handlers.Content } }
26.780352
87
0.661926
987ee7d7dec0e6cacef32ed1ae0f6296a40a33c2
1,373
/* * Copyright DataStax, 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.datastax.oss.quarkus.runtime.api.reactive; import com.datastax.dse.driver.api.core.cql.continuous.reactive.ContinuousReactiveResultSet; import com.datastax.dse.driver.api.core.cql.reactive.ReactiveRow; import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.quarkus.runtime.api.session.QuarkusCqlSession; import io.smallrye.mutiny.Multi; /** * A marker interface for {@code Multi<ReactiveRow>} returned by {@link QuarkusCqlSession}. * * @see QuarkusCqlSession#executeContinuouslyReactive(String) * @see QuarkusCqlSession#executeContinuouslyReactive(Statement) * @see ContinuousReactiveResultSet */ public interface MutinyContinuousReactiveResultSet extends Multi<ReactiveRow>, ContinuousReactiveResultSet, MutinyReactiveQueryMetadata {}
41.606061
92
0.79024
9c491ba55a122cdd67a2e36f1d108520cec2abce
3,668
package Main.Entities; import Packages.Chihab.Models.enums.RoleEnum; import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject; import de.ailis.pherialize.MixedArray; import java.sql.Timestamp; import java.util.Objects; public class User extends RecursiveTreeObject<User> { public static final String ROLE_CUSTOMER="ROLE_CUSTOMER"; public static final String ROLE_MEMBER= "ROLE_MEMBER"; public static final String ROLE_SUPER_ADMIN="ROLE_SUPER_ADMIN"; public static final String ROLE_ADMIN_ASSOCIATION="ROLE_ASSOCIATION_ADMIN"; @Override public String toString() { return username ; } private int id; private String username, email, password; private Timestamp last_login; private boolean enabled, approuved, banned; private MixedArray roles; private Profile profile; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Boolean getBanned() { return banned; } public void setBanned(Boolean banned) { this.banned = banned; } public MixedArray getRoles() { return roles; } public void setRoles(MixedArray roles) { this.roles = roles; } public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Timestamp getLast_login() { return last_login; } public void setLast_login(Timestamp last_login) { this.last_login = last_login; } public User(String email, String username, String password, String profileImage) { this.email = email; this.username = username; this.password = password; this.banned = false; this.enabled = true; this.roles = new MixedArray(); this.roles.put(0, RoleEnum.ROLE_CLIENT); this.profile = new Profile(); this.profile.setImage(profileImage); } public void setApprouved(Boolean approuved) { this.approuved = approuved; } public boolean getEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isAdmin() { return this.roles.containsValue(ROLE_SUPER_ADMIN); } public boolean isAssociationAdmin() { return this.roles.containsValue(ROLE_ADMIN_ASSOCIATION); } public boolean isMember() { return this.roles.containsValue(ROLE_MEMBER); } public boolean isClient() { return this.roles.containsValue(ROLE_CUSTOMER); } public boolean getApprouved() { return approuved; } public void addRole(RoleEnum role) { this.roles.put(this.roles.keySet().size(), role); } public User() { this.profile = new Profile(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id; } @Override public int hashCode() { return Objects.hash(id); } public void removeRole(RoleEnum role) { // TODO } }
23.512821
86
0.632497
2c652c2153af32a9524267034076e4aa28e7edd1
7,343
/** * Copyright 2016-2017 By_syk * * 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.by_syk.netupdown.fragment; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.SwitchPreference; import android.provider.Settings; import android.view.WindowManager; import com.by_syk.lib.storage.SP; import com.by_syk.netupdown.R; import com.by_syk.netupdown.service.NetTrafficService; import com.by_syk.netupdown.util.C; /** * Created by By_syk on 2016-11-08. */ @TargetApi(11) public class PrefFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { private SP sp; private SwitchPreference switchPreference; private CheckBoxPreference checkBoxPreference; private ServiceReceiver serviceReceiver; public static int OVERLAY_PERMISSION_REQ_CODE = 1234; public static PrefFragment newInstance() { return new PrefFragment(); } @TargetApi(14) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); /* * SwitchPreferences calls multiple times the onPreferenceChange() method * It is due to the bug in SwitchPreference implementation. * And it's solved in API 21+ */ //if (C.SDK >= 14) { if (C.SDK >= 21) { switchPreference = (SwitchPreference) findPreference("run"); } else { checkBoxPreference = (CheckBoxPreference) findPreference("run"); } findPreference("run").setOnPreferenceChangeListener(this); serviceReceiver = new ServiceReceiver(); sp = new SP(getActivity(), false); } @Override public void onStart() { super.onStart(); if (isChecked() && !NetTrafficService.isRunning) { if (canDrawOverlays()) { runService(); } } IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(NetTrafficService.ACTION_SERVICE_RUN); intentFilter.addAction(NetTrafficService.ACTION_SERVICE_DIED); getActivity().registerReceiver(serviceReceiver, intentFilter); } @Override public void onStop() { super.onStop(); getActivity().unregisterReceiver(serviceReceiver); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { switch (preference.getKey()) { case "run": boolean isChecked = (Boolean) newValue; if (isChecked) { if (!NetTrafficService.isRunning) { if (canDrawOverlays()) { if (!sp.getBoolean("priorityHint")) { hintPriorityDialog(); } else { runService(); } } else { // No permission requestDrawOverLays(); } } } else { stopService(); } return false; default: return true; } } @TargetApi(14) private void setChecked(boolean checked) { if (C.SDK >= 21) { switchPreference.setChecked(checked); } else { checkBoxPreference.setChecked(checked); } } @TargetApi(14) private boolean isChecked() { if (C.SDK >= 21) { return switchPreference.isChecked(); } else { return checkBoxPreference.isChecked(); } } private void runService() { getActivity().startService(new Intent(getActivity().getApplicationContext(), NetTrafficService.class)); } private void stopService() { getActivity().stopService(new Intent(getActivity().getApplicationContext(), NetTrafficService.class)); } @TargetApi(23) private boolean canDrawOverlays() { return C.SDK < 23 || Settings.canDrawOverlays(getActivity()); } @TargetApi(23) private void requestDrawOverLays() { if (canDrawOverlays()) { return; } Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getActivity().getPackageName())); startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE); } private void hintPriorityDialog() { AlertDialog alertDialog = new AlertDialog.Builder(getActivity()) .setTitle(R.string.dlg_title_window_priority) .setMessage(R.string.priority_desc) .setPositiveButton(R.string.dlg_bt_high_priority, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { sp.put("window", WindowManager.LayoutParams.TYPE_SYSTEM_ERROR) .put("priorityHint", true).save(); runService(); } }) .setNegativeButton(R.string.dlg_bt_low_priority, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { sp.put("window", WindowManager.LayoutParams.TYPE_SYSTEM_ALERT) .put("priorityHint", true).save(); runService(); } }) .create(); alertDialog.show(); } @TargetApi(23) @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == OVERLAY_PERMISSION_REQ_CODE) { if (canDrawOverlays()) { setChecked(true); } } } class ServiceReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case NetTrafficService.ACTION_SERVICE_RUN: setChecked(true); break; case NetTrafficService.ACTION_SERVICE_DIED: if (isChecked()) { setChecked(false); } } } } }
32.928251
111
0.59921
31c2748bd713d2db0ef372be77c10c0e98bb5fa9
5,238
package com.klinker.android.twitter_l.services.background_refresh; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.firebase.jobdispatcher.Constraint; import com.firebase.jobdispatcher.FirebaseJobDispatcher; import com.firebase.jobdispatcher.GooglePlayDriver; import com.firebase.jobdispatcher.Job; import com.firebase.jobdispatcher.JobParameters; import com.firebase.jobdispatcher.Lifetime; import com.firebase.jobdispatcher.SimpleJobService; import com.firebase.jobdispatcher.Trigger; import com.klinker.android.twitter_l.activities.MainActivity; import com.klinker.android.twitter_l.adapters.TimelinePagerAdapter; import com.klinker.android.twitter_l.data.sq_lite.ListDataSource; import com.klinker.android.twitter_l.services.CatchupPull; import com.klinker.android.twitter_l.settings.AppSettings; import com.klinker.android.twitter_l.utils.Utils; import java.util.ArrayList; import java.util.List; import twitter4j.Paging; import twitter4j.Status; import twitter4j.Twitter; public class ListRefreshService extends SimpleJobService { public static final String JOB_TAG = "list-timeline-refresh"; SharedPreferences sharedPrefs; public static boolean isRunning = false; public static void cancelRefresh(Context context) { FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context)); dispatcher.cancel(JOB_TAG); } public static void scheduleRefresh(Context context) { AppSettings settings = AppSettings.getInstance(context); int refreshInterval = (int) settings.listRefresh / 1000; // convert to seconds FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context)); if (settings.listRefresh != 0) { Job myJob = dispatcher.newJobBuilder() .setService(ListRefreshService.class) .setTag(JOB_TAG) .setRecurring(true) .setLifetime(Lifetime.FOREVER) .setTrigger(Trigger.executionWindow(refreshInterval, (5 * 60) + refreshInterval)) .setConstraints(settings.syncMobile ? Constraint.ON_ANY_NETWORK : Constraint.ON_UNMETERED_NETWORK) .setReplaceCurrent(true) .build(); dispatcher.mustSchedule(myJob); } else { dispatcher.cancel(JOB_TAG); } } @Override public int onRunJob(JobParameters job) { if (!MainActivity.canSwitch || CatchupPull.isRunning || WidgetRefreshService.isRunning || ListRefreshService.isRunning) { return 0; } sharedPrefs = AppSettings.getSharedPreferences(this); int currentAccount = sharedPrefs.getInt("current_account", 1); List<Long> listIds = new ArrayList<>(); for (int i = 0; i < TimelinePagerAdapter.MAX_EXTRA_PAGES; i++) { String listIdentifier = "account_" + currentAccount + "_list_" + (i + 1) + "_long"; String pageIdentifier = "account_" + currentAccount + "_page_" + (i + 1); int type = sharedPrefs.getInt(pageIdentifier, AppSettings.PAGE_TYPE_NONE); if (type == AppSettings.PAGE_TYPE_LIST) { listIds.add(sharedPrefs.getLong(listIdentifier, 0L)); } } for (Long listId : listIds) { if (MainActivity.canSwitch) { Log.v("talon_refresh", "refreshing list: " + listId); ListRefreshService.isRunning = true; Context context = getApplicationContext(); AppSettings settings = AppSettings.getInstance(context); Twitter twitter = Utils.getTwitter(context, settings); long[] lastId = ListDataSource.getInstance(context).getLastIds(listId); final List<twitter4j.Status> statuses = new ArrayList<>(); boolean foundStatus = false; Paging paging = new Paging(1, 200); if (lastId[0] > 0) { paging.setSinceId(lastId[0]); } for (int i = 0; i < settings.maxTweetsRefresh; i++) { try { if (!foundStatus) { paging.setPage(i + 1); List<Status> list = twitter.getUserListStatuses(listId, paging); statuses.addAll(list); } } catch (Exception e) { // the page doesn't exist foundStatus = true; } catch (OutOfMemoryError o) { // don't know why... } } ListDataSource dataSource = ListDataSource.getInstance(context); dataSource.insertTweets(statuses, listId); sharedPrefs.edit().putBoolean("refresh_me_list_" + listId, true).apply(); sendBroadcast(new Intent("com.klinker.android.twitter.LIST_REFRESHED_" + listId)); } ListRefreshService.isRunning = false; } return 0; } }
37.414286
129
0.62753
29d409c2e4734c8a13253bcac3c2e0e2c8c21299
7,474
package org.apache.ofbiz.marketing.segment; import lombok.experimental.FieldNameConstants; import java.io.Serializable; import lombok.Getter; import lombok.Setter; import java.sql.Timestamp; import org.apache.ofbiz.entity.GenericValue; import java.util.List; import java.util.ArrayList; /** * Segment Group View Related Parties */ @FieldNameConstants public class SegmentGroupViewRelatedParties implements Serializable { public static final long serialVersionUID = 3667643984689623040L; public static final String NAME = "SegmentGroupViewRelatedParties"; /** * Sgr Role Type Id */ @Getter @Setter private String sgrRoleTypeId; /** * Sgr Segment Group Id */ @Getter @Setter private String sgrSegmentGroupId; /** * Sgr Party Id */ @Getter @Setter private String sgrPartyId; /** * Sgr To Role Type Id */ @Getter @Setter private String sgrToRoleTypeId; /** * Sgr To Segment Group Id */ @Getter @Setter private String sgrToSegmentGroupId; /** * Sgr To Party Id */ @Getter @Setter private String sgrToPartyId; /** * Pr Sgr Role Type Id To */ @Getter @Setter private String prSgrRoleTypeIdTo; /** * Pr Sgr Party Id From */ @Getter @Setter private String prSgrPartyIdFrom; /** * Pr Sgr Position Title */ @Getter @Setter private String prSgrPositionTitle; /** * Pr Sgr Comments */ @Getter @Setter private String prSgrComments; /** * Pr Sgr Priority Type Id */ @Getter @Setter private String prSgrPriorityTypeId; /** * Pr Sgr Permissions Enum Id */ @Getter @Setter private String prSgrPermissionsEnumId; /** * Pr Sgr Role Type Id From */ @Getter @Setter private String prSgrRoleTypeIdFrom; /** * Pr Sgr Thru Date */ @Getter @Setter private Timestamp prSgrThruDate; /** * Pr Sgr From Date */ @Getter @Setter private Timestamp prSgrFromDate; /** * Pr Sgr Relationship Name */ @Getter @Setter private String prSgrRelationshipName; /** * Pr Sgr Security Group Id */ @Getter @Setter private String prSgrSecurityGroupId; /** * Pr Sgr Party Relationship Type Id */ @Getter @Setter private String prSgrPartyRelationshipTypeId; /** * Pr Sgr Status Id */ @Getter @Setter private String prSgrStatusId; /** * Pr Sgr Party Id To */ @Getter @Setter private String prSgrPartyIdTo; /** * Sgc Party Classification Group Id */ @Getter @Setter private String sgcPartyClassificationGroupId; /** * Sgc Segment Group Id */ @Getter @Setter private String sgcSegmentGroupId; /** * Pc From Date */ @Getter @Setter private Timestamp pcFromDate; /** * Pc Party Classification Group Id */ @Getter @Setter private String pcPartyClassificationGroupId; /** * Pc Party Id */ @Getter @Setter private String pcPartyId; /** * Pc Thru Date */ @Getter @Setter private Timestamp pcThruDate; /** * Pr Pc Role Type Id To */ @Getter @Setter private String prPcRoleTypeIdTo; /** * Pr Pc Party Id From */ @Getter @Setter private String prPcPartyIdFrom; /** * Pr Pc Position Title */ @Getter @Setter private String prPcPositionTitle; /** * Pr Pc Comments */ @Getter @Setter private String prPcComments; /** * Pr Pc Priority Type Id */ @Getter @Setter private String prPcPriorityTypeId; /** * Pr Pc Permissions Enum Id */ @Getter @Setter private String prPcPermissionsEnumId; /** * Pr Pc Role Type Id From */ @Getter @Setter private String prPcRoleTypeIdFrom; /** * Pr Pc Thru Date */ @Getter @Setter private Timestamp prPcThruDate; /** * Pr Pc From Date */ @Getter @Setter private Timestamp prPcFromDate; /** * Pr Pc Relationship Name */ @Getter @Setter private String prPcRelationshipName; /** * Pr Pc Security Group Id */ @Getter @Setter private String prPcSecurityGroupId; /** * Pr Pc Party Relationship Type Id */ @Getter @Setter private String prPcPartyRelationshipTypeId; /** * Pr Pc Status Id */ @Getter @Setter private String prPcStatusId; /** * Pr Pc Party Id To */ @Getter @Setter private String prPcPartyIdTo; public SegmentGroupViewRelatedParties(GenericValue value) { sgrRoleTypeId = (String) value.get(FIELD_SGR_ROLE_TYPE_ID); sgrSegmentGroupId = (String) value.get(FIELD_SGR_SEGMENT_GROUP_ID); sgrPartyId = (String) value.get(FIELD_SGR_PARTY_ID); sgrToRoleTypeId = (String) value.get(FIELD_SGR_TO_ROLE_TYPE_ID); sgrToSegmentGroupId = (String) value.get(FIELD_SGR_TO_SEGMENT_GROUP_ID); sgrToPartyId = (String) value.get(FIELD_SGR_TO_PARTY_ID); prSgrRoleTypeIdTo = (String) value.get(FIELD_PR_SGR_ROLE_TYPE_ID_TO); prSgrPartyIdFrom = (String) value.get(FIELD_PR_SGR_PARTY_ID_FROM); prSgrPositionTitle = (String) value.get(FIELD_PR_SGR_POSITION_TITLE); prSgrComments = (String) value.get(FIELD_PR_SGR_COMMENTS); prSgrPriorityTypeId = (String) value.get(FIELD_PR_SGR_PRIORITY_TYPE_ID); prSgrPermissionsEnumId = (String) value .get(FIELD_PR_SGR_PERMISSIONS_ENUM_ID); prSgrRoleTypeIdFrom = (String) value .get(FIELD_PR_SGR_ROLE_TYPE_ID_FROM); prSgrThruDate = (Timestamp) value.get(FIELD_PR_SGR_THRU_DATE); prSgrFromDate = (Timestamp) value.get(FIELD_PR_SGR_FROM_DATE); prSgrRelationshipName = (String) value .get(FIELD_PR_SGR_RELATIONSHIP_NAME); prSgrSecurityGroupId = (String) value .get(FIELD_PR_SGR_SECURITY_GROUP_ID); prSgrPartyRelationshipTypeId = (String) value .get(FIELD_PR_SGR_PARTY_RELATIONSHIP_TYPE_ID); prSgrStatusId = (String) value.get(FIELD_PR_SGR_STATUS_ID); prSgrPartyIdTo = (String) value.get(FIELD_PR_SGR_PARTY_ID_TO); sgcPartyClassificationGroupId = (String) value .get(FIELD_SGC_PARTY_CLASSIFICATION_GROUP_ID); sgcSegmentGroupId = (String) value.get(FIELD_SGC_SEGMENT_GROUP_ID); pcFromDate = (Timestamp) value.get(FIELD_PC_FROM_DATE); pcPartyClassificationGroupId = (String) value .get(FIELD_PC_PARTY_CLASSIFICATION_GROUP_ID); pcPartyId = (String) value.get(FIELD_PC_PARTY_ID); pcThruDate = (Timestamp) value.get(FIELD_PC_THRU_DATE); prPcRoleTypeIdTo = (String) value.get(FIELD_PR_PC_ROLE_TYPE_ID_TO); prPcPartyIdFrom = (String) value.get(FIELD_PR_PC_PARTY_ID_FROM); prPcPositionTitle = (String) value.get(FIELD_PR_PC_POSITION_TITLE); prPcComments = (String) value.get(FIELD_PR_PC_COMMENTS); prPcPriorityTypeId = (String) value.get(FIELD_PR_PC_PRIORITY_TYPE_ID); prPcPermissionsEnumId = (String) value .get(FIELD_PR_PC_PERMISSIONS_ENUM_ID); prPcRoleTypeIdFrom = (String) value.get(FIELD_PR_PC_ROLE_TYPE_ID_FROM); prPcThruDate = (Timestamp) value.get(FIELD_PR_PC_THRU_DATE); prPcFromDate = (Timestamp) value.get(FIELD_PR_PC_FROM_DATE); prPcRelationshipName = (String) value .get(FIELD_PR_PC_RELATIONSHIP_NAME); prPcSecurityGroupId = (String) value.get(FIELD_PR_PC_SECURITY_GROUP_ID); prPcPartyRelationshipTypeId = (String) value .get(FIELD_PR_PC_PARTY_RELATIONSHIP_TYPE_ID); prPcStatusId = (String) value.get(FIELD_PR_PC_STATUS_ID); prPcPartyIdTo = (String) value.get(FIELD_PR_PC_PARTY_ID_TO); } public static SegmentGroupViewRelatedParties fromValue( org.apache.ofbiz.entity.GenericValue value) { return new SegmentGroupViewRelatedParties(value); } public static List<SegmentGroupViewRelatedParties> fromValues( List<GenericValue> values) { List<SegmentGroupViewRelatedParties> entities = new ArrayList<>(); for (GenericValue value : values) { entities.add(new SegmentGroupViewRelatedParties(value)); } return entities; } }
22.856269
74
0.737891
de09bb38a88ac878aea7c63fcb02285d7ee10b35
379
package com.zc.javabasic.designpatterns.composite; /** * @description: 抽象组件 * @author: Zhangc * @date: 2018-12-24 */ public interface Component { void operation(); } /** * 叶子组件 */ interface Leaf extends Component{ } /** * 容器组件 */ interface Composite extends Component{ void add(Component c); void remove(Component c); Component getChild(int index); }
14.037037
50
0.667546
ffbab0fc508d838a652e7873b370219e6b09a0c0
1,035
package com.howtodoinjava.demo.gson; import java.lang.reflect.Type; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class LocalDateAdapter implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> { @Override public JsonElement serialize(final LocalDate date, final Type typeOfSrc, final JsonSerializationContext context) { return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE)); // "yyyy-MM-dd" } @Override public LocalDate deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { return LocalDate.parse(json.getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd")); } }
33.387097
92
0.805797
bebfc57849cffdde7a72a9144d315e423f4d59d1
97
package com.braintreepayments.api; enum DropInExitTransition { NO_ANIMATION, FADE_OUT }
13.857143
34
0.762887
bcf9234edeaf27d158ede7b8953dca7e41626d4e
12,597
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.coreservice.api.parameter; import org.kuali.rice.core.api.CoreConstants; import org.kuali.rice.core.api.criteria.QueryByCriteria; import org.kuali.rice.core.api.exception.RiceIllegalArgumentException; import org.kuali.rice.core.api.exception.RiceIllegalStateException; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import java.util.Collection; /** * Service for interacting with {@link Parameter Parameters}. */ @WebService(name = "parameterService", targetNamespace = CoreConstants.Namespaces.CORE_NAMESPACE_2_0) @SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED) public interface ParameterRepositoryService { /** * This will create a {@link Parameter} exactly like the parameter passed in. * * @param parameter the parameter to create * @return the parameter that was created * @throws RiceIllegalArgumentException if the parameter is null * @throws RiceIllegalStateException if the parameter is already existing in the system */ @WebMethod(operationName="createParameter") @WebResult(name = "parameter") @CacheEvict(value={Parameter.Cache.NAME}, allEntries = true) Parameter createParameter(@WebParam(name = "parameter") Parameter parameter) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * This will update a {@link Parameter}. * * <p> * If the parameter does not exist under the application * code passed, then this method will check if the parameter * exists under the default rice application id and * will update that parameter. * </p> * * @param parameter the parameter to update * @return the parameter that was updated * @throws RiceIllegalArgumentException if the parameter is null * @throws RiceIllegalStateException if the parameter does not exist in the system under the * specific application id or default rice application id */ @WebMethod(operationName="updateParameter") @WebResult(name = "parameter") @CacheEvict(value={Parameter.Cache.NAME}, allEntries = true) Parameter updateParameter(@WebParam(name = "parameter") Parameter parameter) throws RiceIllegalArgumentException, RiceIllegalStateException; /** * Gets a {@link Parameter} from a {@link ParameterKey}. * * <p> * If the parameter does not exist under the application * code passed, then this method will check if the parameter * exists under the default rice application id and * will return that parameter. * </p> * * <p> * This method will return null if the parameter does not exist. * </p> * * @param key the key to retrieve the parameter by. cannot be null. * @return a {@link Parameter} or null * @throws RiceIllegalArgumentException if the key is null */ @WebMethod(operationName="getParameter") @WebResult(name = "parameter") @Cacheable(value= Parameter.Cache.NAME, key="'key=' + #p0.getCacheKey()") Parameter getParameter(@WebParam(name = "key") ParameterKey key) throws RiceIllegalArgumentException; /** * Gets a {@link ParameterContract#getValue()} from a {@link ParameterKey}. * * <p> * If the parameter does not exist under the application * code passed, then this method will check if the parameter * exists under the default rice application id and * will return that parameter. * </p> * * <p> * This method will return null if the parameter does not exist. * </p> * * @param key the key to retrieve the parameter by. cannot be null. * @return a string value or null * @throws RiceIllegalArgumentException if the key is null */ @WebMethod(operationName="getParameterValueAsString") @WebResult(name = "value") @Cacheable(value= Parameter.Cache.NAME, key="'{getParameterValueAsString}' + 'key=' + #p0.getCacheKey()") String getParameterValueAsString(@WebParam(name = "key") ParameterKey key) throws RiceIllegalArgumentException; /** * Gets a {@link ParameterContract#getValue()} as a Boolean from a {@link ParameterKey}. * * <p> * If the parameter does not exist under the application * code passed, then this method will check if the parameter * exists under the default rice application id and * will return that parameter. * </p> * * <p> * This method will return null if the parameter does not exist or is not a valid truth value. * </p> * * valid true values (case insensitive): * <ul> * <li>Y</li> * <li>true</li> * <li>on</li> * <li>1</li> * <li>t</li> * <li>enabled</li> * </ul> * * valid false values (case insensitive): * <ul> * <li>N</li> * <li>false</li> * <li>off</li> * <li>0</li> * <li>f</li> * <li>disabled</li> * </ul> * * @param key the key to retrieve the parameter by. cannot be null. * @return a boolean value or null * @throws RiceIllegalArgumentException if the key is null */ @WebMethod(operationName="getParameterValueAsBoolean") @WebResult(name = "value") @Cacheable(value= Parameter.Cache.NAME, key="'{getParameterValueAsBoolean}' + 'key=' + #p0.getCacheKey()") Boolean getParameterValueAsBoolean(@WebParam(name = "key") ParameterKey key) throws RiceIllegalArgumentException; /** * Gets a {@link ParameterContract#getValue()} from a {@link ParameterKey} * where the value is split on a semi-colon delimeter and each token is trimmed * of white space. * * for example: param_name=foo; bar; baz * * will yield a collection containing foo, bar, baz * * <p> * If the parameter does not exist under the application * code passed, then this method will check if the parameter * exists under the default rice application id and * will return that parameter. * </p> * * <p> * This method will always return an <b>immutable</b> Collection * even when no values exist. * </p> * * @param key the key to retrieve the parameter by. cannot be null. * @return an immutable collection of strings * @throws RiceIllegalArgumentException if the key is null */ @WebMethod(operationName="getParameterValuesAsString") @XmlElementWrapper(name = "values", required = true) @XmlElement(name = "value", required = false) @WebResult(name = "values") @Cacheable(value= Parameter.Cache.NAME, key="'{getParameterValuesAsString}' + 'key=' + #p0.getCacheKey()") Collection<String> getParameterValuesAsString(@WebParam(name = "key") ParameterKey key) throws RiceIllegalArgumentException; /** * Gets a {@link ParameterContract#getValue()} from a {@link ParameterKey} * where the value is split on a semi-colon delimeter and each token is trimmed * of white space. Those values are themselves keyvalue pairs which are searched * for the sub parameter name. * * for example: * * param_name=foo=f1; bar=b1; baz=z1 * subParameterName=bar * * will yield b1 * * <p>if multiple subparameters are contained in the parameter value the first one is returned</p> * * <p> * If the parameter does not exist under the application * code passed, then this method will check if the parameter * exists under the default rice application id and * will return that parameter. * </p> * * <p> * This method will always return null when the subparameter does not * exist or if the parameter value does not conform to the following format(s): * <ol> * <li>subparameter_name=subparameter_value;</li> * </ol> * </p> * * @param key the key to retrieve the parameter by. cannot be null. * @param subParameterName the sub parameter to search for * @return a string value or null * @throws RiceIllegalArgumentException if the key is null or if the subParameterName is blank */ @WebMethod(operationName="getSubParameterValueAsString") @WebResult(name = "value") String getSubParameterValueAsString(@WebParam(name = "key") ParameterKey key, @WebParam(name = "subParameterName") String subParameterName) throws RiceIllegalArgumentException; /** * Gets a {@link ParameterContract#getValue()} from a {@link ParameterKey} * where the value is split on a semi-colon delimeter and each token is trimmed * of white space. Those values are themselves keyvalue pairs which are searched * for the sub parameter name. After the sub parameter is found it is split on a comma * and trimmed or whitespace before adding it to the final collection for return. * * for example: * * param_name=foo=f1,f2,f3; bar=b1,b2; baz=z1 * subParameterName=bar * * will yield a collection containing b1, b2 * * <p>if multiple subparameters are contained in the parameter value the first one is returned</p> * * <p> * If the parameter does not exist under the application * code passed, then this method will check if the parameter * exists under the default rice application id and * will return that parameter. * </p> * * <p> * This method will always return an <b>immutable</b> Collection * even when no values exist. * </p> * * <p> * This method will always return an empty <b>immutable</b> Collection when * the subparameter does not exist or if the parameter value does not * conform to the following format(s): * <ol> * <li>subparameter_name=subparameter_value;</li> * <li>subparameter_name=subparameter_value1, subparameter_value2;</li> * <li>subparameter_name=subparameter_value1, subparameter_value2,;</li> * </ol> * </p> * * @param key the key to retrieve the parameter by. cannot be null. * @param subParameterName the sub parameter to search for * @return an immutable collection of strings * @throws RiceIllegalArgumentException if the key is null or if the subParameterName is blank */ @WebMethod(operationName="getSubParameterValuesAsString") @XmlElementWrapper(name = "values", required = true) @XmlElement(name = "value", required = false) @WebResult(name = "values") Collection<String> getSubParameterValuesAsString(@WebParam(name = "key") ParameterKey key, @WebParam(name = "subParameterName") String subParameterName) throws RiceIllegalArgumentException; @WebMethod(operationName="findParameters") @WebResult(name = "results") ParameterQueryResults findParameters(@WebParam(name = "query") QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException; }
42.271812
137
0.652616
0dd875ad95ae30a6f2ca962da683e9e9ad0b9559
6,548
/* * 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.geode.management.internal.cli.parser.preprocessor; import java.util.ArrayList; import java.util.List; import org.apache.geode.management.internal.cli.parser.SyntaxConstants; /** * * <code><br></code> This Class will serve the same purpose as pre-processors do during compilation * of a program. * * It will act as pre-processor for jopt. * * It will split the user input into an array of strings as per the specifications of the command * for e.g; Different command might require different value separators, different value specifiers * and many more customizations * * @since GemFire 7.0 * */ public class Preprocessor { private static final String VALUE_SPECIFIER = SyntaxConstants.OPTION_VALUE_SPECIFIER; private static final String ARGUMENT_SEPARATOR = SyntaxConstants.ARGUMENT_SEPARATOR; private static final String OPTION_SEPARATOR = SyntaxConstants.OPTION_SEPARATOR; private static final String LONG_OPTION_SPECIFIER = SyntaxConstants.LONG_OPTION_SPECIFIER; private static final String OPTION_DELIMITER = OPTION_SEPARATOR + LONG_OPTION_SPECIFIER; public static String[] split(final String input) { if (input == null) { return null; } final String trimInput = PreprocessorUtils.trim(input).getString(); final int length = trimInput.length(); final List<String> returnStrings = new ArrayList<String>(); int index = 0; // Current location of the character(s) in the string being examined int startOfString = 0; // Starting index of the string we're currently parsing and preparing to // save // If this first string doesn't start with the long option specifier, then there are arguments. // Process the arguments first. if (!trimInput.regionMatches(index, LONG_OPTION_SPECIFIER, 0, LONG_OPTION_SPECIFIER.length())) { // Until we find the first occurrence of Option Delimiter (" --") while (index < length && !trimInput.regionMatches(index, OPTION_DELIMITER, 0, OPTION_DELIMITER.length())) { // Anything inside single or double quotes gets ignored if (trimInput.charAt(index) == '\'' || trimInput.charAt(index) == '\"') { char charToLookFor = trimInput.charAt(index++); // Look for the next single or double quote. Those preceded by a '\' character are // ignored. while (index < length && (trimInput.charAt(index) != charToLookFor || trimInput.charAt(index - 1) == '\\')) { index++; } } index++; // 1. There are only arguments & we've reached the end OR // 2. We are at index where option (" --") has started OR // 3. One argument has finished & we are now at the next argument - check for Argument // Separator (" ") if (index >= length || trimInput.regionMatches(index, OPTION_DELIMITER, 0, OPTION_DELIMITER.length()) || trimInput.regionMatches(index, ARGUMENT_SEPARATOR, 0, ARGUMENT_SEPARATOR.length())) { String stringToAdd = trimInput.substring(startOfString, (index > length ? length : index)).trim(); returnStrings.add(stringToAdd); if (trimInput.regionMatches(index, ARGUMENT_SEPARATOR, 0, ARGUMENT_SEPARATOR.length())) { index += ARGUMENT_SEPARATOR.length(); } startOfString = index; } } index += OPTION_SEPARATOR.length(); } // Process the options startOfString = index; while (index < length) { // Until we find the first occurrence of Option Separator (" ") or Value Specifier ("=") while (index < length && !trimInput.regionMatches(index, OPTION_SEPARATOR, 0, OPTION_SEPARATOR.length()) && !trimInput.regionMatches(index, VALUE_SPECIFIER, 0, VALUE_SPECIFIER.length())) { index++; } if (startOfString != index) { returnStrings.add(trimInput.substring(startOfString, index)); startOfString = index + 1; } // If value part (starting with "=") has started if (trimInput.regionMatches(index++, VALUE_SPECIFIER, 0, VALUE_SPECIFIER.length())) { startOfString = index; // Keep going over chars until we find the option separator ("--") while (index < length && !trimInput.regionMatches(index, OPTION_SEPARATOR, 0, OPTION_SEPARATOR.length())) { // Anything inside single or double quotes gets ignored if (index < length && (trimInput.charAt(index) == '\'' || trimInput.charAt(index) == '\"')) { char charToLookFor = trimInput.charAt(index++); // Look for the next single or double quote. Those preceded by a '\' character are // ignored. while (index < length && (trimInput.charAt(index) != charToLookFor || trimInput.charAt(index - 1) == '\\')) { index++; } } index++; } // 1. We are done & at the end OR // 2. There is another word which matches ("--") if (index >= length || trimInput.regionMatches(index, OPTION_SEPARATOR, 0, OPTION_SEPARATOR.length())) { if (startOfString == index) { // This place-holder value indicates to OptionParser that an option // was specified without a value. returnStrings.add("__NULL__"); } else { String stringToAdd = trimInput.substring(startOfString, (index > length ? length : index)); returnStrings.add(stringToAdd); } startOfString = index + 1; } index++; } } return returnStrings.toArray(new String[0]); } }
43.078947
100
0.647526
4a497348c88d0dd86292eaad5dc062ef5a18cc57
590
package com.trends.database; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; public class UserItemGroupingComparator extends WritableComparator { protected UserItemGroupingComparator() { super(UserItem.class, true); } @SuppressWarnings("rawtypes") @Override public int compare(WritableComparable w1, WritableComparable w2) { UserItem key1 = (UserItem) w1; UserItem key2 = (UserItem) w2; // (check on UserId) return key1.getUserId().compareTo(key2.getUserId()); } }
24.583333
70
0.69661
c323c358854e2994b37d3658463aa4143c4b643f
40
anyMethod(<selection>"asd");</selection>
40
40
0.75
d089bac02aa3263708059a6d3ce5a2e1ac29138f
925
package com.example.timetrakr; import android.os.Bundle; import com.example.timetrakr.view.activities.durations.ActivitiesDurationsFragment; import com.example.timetrakr.view.activities.started.ActivitiesStartedFragment; import com.gorolykmaxim.android.commons.bottomnavigation.BottomNavigationActivity; /** * Main activity of the application, that contains bottom navigation and a fragment container. */ public class MainActivity extends BottomNavigationActivity { public MainActivity() { super(R.menu.navigation, R.id.navigation_activity_start_events); } /** * {@inheritDoc} */ @Override protected void onCreate(Bundle savedInstanceState) { addFragment(R.id.navigation_activity_start_events, new ActivitiesStartedFragment()); addFragment(R.id.navigation_activity_durations, new ActivitiesDurationsFragment()); super.onCreate(savedInstanceState); } }
33.035714
94
0.770811
8017195cf98881c81022f38b5d8b924548afba01
1,316
package me.earth.phobos.features.notifications; import me.earth.phobos.Phobos; import me.earth.phobos.features.modules.client.HUD; import me.earth.phobos.util.RenderUtil; import me.earth.phobos.util.Timer; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; public class Notifications { private final String text; private final long disableTime; private final float width; private final Timer timer = new Timer(); public Notifications(String text, long disableTime) { this.text = text; this.disableTime = disableTime; this.width = Phobos.moduleManager.getModuleByClass(HUD.class).renderer.getStringWidth(text); timer.reset(); } public void onDraw(int y) { final ScaledResolution scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); if (timer.passedMs(disableTime)) Phobos.notificationManager.getNotifications().remove(this); RenderUtil.drawRect(scaledResolution.getScaledWidth() - 4 - width,y,scaledResolution.getScaledWidth() - 2,y + Phobos.moduleManager.getModuleByClass(HUD.class).renderer.getFontHeight() + 3,0x75000000); Phobos.moduleManager.getModuleByClass(HUD.class).renderer.drawString(text,scaledResolution.getScaledWidth() - width - 3,y + 2,-1,true); } }
45.37931
208
0.74848
8f608921cc87d7b76d777e50de11cde4f9db657c
1,384
// Copyright 2014 The Bazel Authors. 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.google.devtools.build.lib.buildtool; /** * Event that is raised when the action and artifact metadata caches are saved at the end of the * build. Contains statistics. */ public class CachesSavedEvent { /** Cache serialization statistics. */ private final long actionCacheSaveTimeInMillis; private final long actionCacheSizeInBytes; public CachesSavedEvent( long actionCacheSaveTimeInMillis, long actionCacheSizeInBytes) { this.actionCacheSaveTimeInMillis = actionCacheSaveTimeInMillis; this.actionCacheSizeInBytes = actionCacheSizeInBytes; } public long getActionCacheSaveTimeInMillis() { return actionCacheSaveTimeInMillis; } public long getActionCacheSizeInBytes() { return actionCacheSizeInBytes; } }
34.6
96
0.764451
01e03e03aacee996f8e9238f39865b6b3a186b53
1,045
public void solve(int testNumber, InputReader in, OutputWriter out) { int N = in.nextInt(); int M = in.nextInt(); Items[] items = new Items[N]; int sum = 0; ArrayList<String> ans = new ArrayList<>(); for (int i = 0; i < N; i++) { items[i] = new Items(i + 1, in.nextInt()); sum += items[i].value * 2; if (i < N - 1) { ans.add((i + 1) + " " + (i + 2)); } else { ans.add((i + 1) + " 1"); } } if (N == 2 || N > M) { out.printLine(-1); return; } Arrays.sort(items, new Comparator<Items>() { public int compare(Items o1, Items o2) { if (o1.value != o2.value) { return o1.value - o2.value; } return o1.index - o2.index; } }); for (int i = N + 1; i <= M; i++) { sum += items[0].value + items[1].value; ans.add(items[0].index + " " + items[1].index); } out.printLine(sum); for (String s : ans) { out.printLine(s); } }
28.243243
69
0.44689
24bb2101a1e1666bbb1e6be5176173f4d1bb1597
992
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution328 { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode oddEvenList(ListNode head) { ListNode odd = new ListNode(-1); ListNode even = new ListNode(-1); ListNode oddRoot = odd; ListNode evenRoot = even; boolean isOdd = false; while (head != null) { isOdd = !isOdd; if (isOdd) { odd.next = head; odd = odd.next; head = head.next; odd.next = null; } else { even.next = head; even = even.next; head = head.next; even.next = null; } } odd.next = evenRoot.next; return oddRoot.next; } }
22.545455
48
0.461694
66d82d09d6686d296ac0fcc10ffeeca53594c3fe
1,277
package edu.cmu.lti.tools.visualize.graphviz; /** * directed graph * @author nlao * */ public class Digraph extends Graph{ private static final long serialVersionUID = 2008042701L; // YYYYMMDD /* public Digraph( String graphName){ super("digraph", graphName); } public Digraph( ){ this( "G"); }*/ //common properties public LabeledObj g = new LabeledObj();//graph public LabeledObj n = new LabeledObj();//node public LabeledObj e = new LabeledObj();//edge //TODO: why we need a counter? to distinguish ids of subgraphs public static int counter=0;//counter to generate GUID public Digraph(){ counter=0; } public String toString(){ //update(); StringBuffer bf = new StringBuffer(); String sIndent=" "; bf.append("digraph G {\n"); if (g.ms.size()>0) bf.append(sIndent+"graph "+g.format()+";\n"); if (e.ms.size()>0) bf.append(sIndent+"edge "+e.format()+";\n"); if (n.ms.size()>0) bf.append(sIndent+"node "+n.format()+";\n"); bf.append(super.toString("")+"}\n"); return bf.toString(); } public static Digraph simpleGraph(){ Digraph g = new Digraph(); g.addNode("AA"); g.addNode("BB"); g.addLink(0,1); return g; } public static void main(String[] args) { System.out.println(simpleGraph()); return; } }
24.557692
70
0.649961
fea81e010e428d210fee5f35ed027788a9a335ad
2,091
package com.ucsc.mcs.test; import de.daslaboratorium.machinelearning.classifier.Classifier; import de.daslaboratorium.machinelearning.classifier.bayes.BayesClassifier; import java.util.Arrays; /** * Created by JagathA on 10/1/2017. */ public class SentimentAnalysisTest { public SentimentAnalysisTest() { analyse(); } public static void main(String[] args) { new SentimentAnalysisTest(); } private void analyse(){ // Create a new bayes classifier with string categories and string features. Classifier<String, String> bayes = new BayesClassifier<String, String>(); // Two examples to learn from. String[] positiveText = "I love sunny days".split("\\s"); String[] negativeText = "I hate will a days".split("\\s"); String[] neutralText = "I hate a days".split("\\s"); // Learn by classifying examples. // New categories can be added on the fly, when they are first used. // A classification consists of a category and a list of features // that resulted in the classification in that category. bayes.learn("positive", Arrays.asList(positiveText)); bayes.learn("negative", Arrays.asList(negativeText)); bayes.learn("neutral", Arrays.asList(neutralText)); // Here are two unknown sentences to classify. String[] unknownText1 = "today is a days".split(" "); String[] unknownText2 = "there will be hate rain days".split(" "); System.out.println( // will output "positive" bayes.classify(Arrays.asList(unknownText1)).getCategory()); System.out.println( // will output "negative" bayes.classify(Arrays.asList(unknownText2)).getCategory()); // Get more detailed classification result. ((BayesClassifier<String, String>) bayes).classifyDetailed( Arrays.asList(unknownText1)); // Change the memory capacity. New learned classifications (using // the learn method) are stored in a queue with the size given // here and used to classify unknown sentences. bayes.setMemoryCapacity(500); } }
36.684211
84
0.682927
d696466faffeb2d45a3052c3fa658429e1106739
1,572
package codeQuotient; import java.util.Scanner; class TimeSpan { // Write your code here private int hours,minutes; public TimeSpan(int hours,int minutes) { this.hours=hours; this.minutes=minutes; } public int getHours() { return hours; } public int getMinutes() { return minutes; } public void add(int hours,int minutes) { this.hours = this.hours+hours; this.minutes = this.minutes+minutes; } public void add(TimeSpan tp) { this.hours = this.hours+tp.hours; this.minutes = this.minutes+tp.minutes; } public double getTotalHours() { double minToHour = this.minutes/60.0; double totalHours = this.hours + minToHour; //return ((double)this.hours+(this.minutes/60.0)); return totalHours; } public String toString() { if(this.minutes==60){ this.hours+=1; return (this.hours+" Hours,"); } return (this.hours+" Hours, "+ this.minutes +" Minutes"); } } class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); TimeSpan t1=new TimeSpan(s.nextInt(),s.nextInt()); TimeSpan t2=new TimeSpan(s.nextInt(),s.nextInt()); System.out.println(t1.getHours()); System.out.println(t1.getMinutes()); System.out.println(t1.toString()); t1.add(s.nextInt(),s.nextInt()); System.out.println(t1.getHours()); System.out.println(t1.getMinutes()); t1.add(t2); System.out.println(t1.getHours()); System.out.println(t1.getMinutes()); System.out.println(t1.getTotalHours()); } }
21.243243
61
0.639949
c57aeb722ab744d365e925275b453a121e1ebaeb
2,939
package kr.co.programmers; import java.util.ArrayList; import java.util.List; public class P17679 { /** * @param m 판의 높이 * @param n 판의 폭 * @param board 판의 배치 정보 * @return 지워지는 블록의 갯수 */ public int solution(final int m, final int n, final String[] board) { int answer = 0; int[] arr = new int[m * n]; // 2차원 배열 → 1차원 배열 for (int y = 0; y < m; y++) { for (int x = 0; x < n; x++) { arr[x + (n * y)] = board[y].charAt(x); } } print(arr, n); while (true) { // 2x2가 완성되는 시작 위치를 기억한다. // [0] [1] 2 3 // [4] [5] 6 7 // 위와 같이 2x2를 찾았다면 기억되는 위치는 [0]이다. List<Integer> memo = new ArrayList<>(); for (int i = 0; i < arr.length - n; i++) { if (i % n == n - 1) { // 체크하지 않아야 할 인덱스 continue; } // 2x2 사각형의 [값]을 구한다. int[] r = new int[]{arr[i], arr[i + 1], arr[i + n], arr[i + n + 1]}; // 4개의 숫자가 모두 같으면 위치를 기억 if (r[0] != -1 // 마킹용 숫자 배제 && (r[0] == r[1] && r[0] == r[2] && r[0] == r[3])) { memo.add(i); } } if (memo.isEmpty()) { // 2x2가 하나도 없으면 끝 System.out.println(); System.out.println("not found 2x2"); break; } System.out.println(); System.out.println("find 2x2 = " + memo); for (int i : memo) { // 기억했던 위치의 2x2 사각형의 값을 -1로 바꿔주면서 점수+1 // 2x2 사각형의 [배열 인덱스]를 구한다. int[] r = new int[]{i, i + 1, i + n, i + n + 1}; for (int j : r) { // 여기서 겹치는 부분 배제 // 값이 -1이면 이미 처리된 블록이다. if (arr[j] != -1) { answer++; arr[j] = -1; } } } print(arr, n); // 블록을 아래로 떨어뜨린다. for (int i = arr.length - 1; i >= 0; i--) { if (arr[i] == -1) { for (int j = i - n; j >= 0; j -= n) { if (arr[j] != -1) { arr[i] = arr[j]; arr[j] = -1; break; } } } } System.out.println(); System.out.println("blocks fall down..."); print(arr, n); } return answer; } private void print(int[] arr, int n) { System.out.println(); for (int i = 0; i < arr.length; i++) { if (i > 0 && i % n == 0) { System.out.println(); } System.out.print(" " + arr[i]); } System.out.println(); } }
29.39
84
0.336509
7de307bbb2931c1e176d76bcf2ba9d2c07cd7209
2,997
package com.alibaba.rsocket.encoding.impl; import com.alibaba.rsocket.encoding.EncodingException; import com.alibaba.rsocket.encoding.ObjectEncodingHandler; import com.alibaba.rsocket.metadata.RSocketMimeType; import com.alibaba.rsocket.observability.RsocketErrorCode; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.buffer.PooledByteBufAllocator; import io.netty.util.ReferenceCountUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Java Object Serialization encoding * * @author leijuan */ public class ObjectEncodingHandlerSerializationImpl implements ObjectEncodingHandler { @NotNull @Override public RSocketMimeType mimeType() { return RSocketMimeType.Java_Object; } @Override public ByteBuf encodingParams(@Nullable Object[] args) throws EncodingException { if (isArrayEmpty(args)) { return EMPTY_BUFFER; } return objectToByteBuf(args); } @Override public Object decodeParams(ByteBuf data, @Nullable Class<?>... targetClasses) throws EncodingException { if (data.readableBytes() > 0 && !isArrayEmpty(targetClasses)) { return byteBufToObject(data); } return null; } @Override @NotNull public ByteBuf encodingResult(@Nullable Object result) throws EncodingException { if (result != null) { return objectToByteBuf(result); } return EMPTY_BUFFER; } @Override @Nullable public Object decodeResult(ByteBuf data, @Nullable Class<?> targetClass) throws EncodingException { if (data.readableBytes() > 0 && targetClass != null) { return byteBufToObject(data); } return null; } private ByteBuf objectToByteBuf(Object obj) throws EncodingException { ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer(); try { ByteBufOutputStream bos = new ByteBufOutputStream(byteBuf); ObjectOutputStream outputStream = new ObjectOutputStream(bos); outputStream.writeObject(obj); outputStream.close(); return byteBuf; } catch (Exception e) { ReferenceCountUtil.safeRelease(byteBuf); throw new EncodingException(RsocketErrorCode.message("RST-700500", obj.getClass().getName(), "byte[]"), e); } } private Object byteBufToObject(ByteBuf data) throws EncodingException { try { ObjectInputStream inputStream = new ObjectInputStream(new ByteBufInputStream(data)); Object object = inputStream.readObject(); inputStream.close(); return object; } catch (Exception e) { throw new EncodingException(RsocketErrorCode.message("RST-700501", "byte[]", "Object"), e); } } }
33.3
119
0.683684
3beec92ed881ea95fa3908a0bbb2d760c0a29635
170
package io.kimo.base.utils.domain.callback; import io.kimo.base.utils.domain.Callback; /** * SilentCallback. */ public interface SilentCallback extends Callback { }
15.454545
50
0.758824
d1b130a951b099a731e9a17abc042bc51586333e
4,251
package com.lswq.nio.rpc.rpc.handler; import com.lswq.nio.rpc.api.DemoI; import com.lswq.nio.rpc.demo.IDemoImpl; import com.lswq.nio.rpc.rpc.bean.RpcCommand; import com.lswq.nio.rpc.rpc.bean.RpcResponse; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class RpcServer { int port; public RpcServer(int port, RpcHandler handler) { this.port = port; this.handler = handler; } RpcHandler handler; ExecutorService executorService = Executors.newFixedThreadPool(20); public void start() { try { ServerSocket serverSocket = new ServerSocket(port); while (true) { Socket socket = serverSocket.accept(); executorService.submit(new WorkThread(socket)); } } catch (IOException e) { e.printStackTrace(); } } public class WorkThread implements Runnable { Socket socket; WorkThread(Socket socket) { this.socket = socket; } @Override public void run() { try { InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); while (true) { int magic = inputStream.read(); //魔数 if (magic == 0x5A) { //两个字节用来计算长度数据长度,服务传送的数据过大可能会出现截断问题 int length1 = inputStream.read(); int length2 = inputStream.read(); int length = (length1 << 8) + length2; ByteArrayOutputStream bout = new ByteArrayOutputStream(length); int sum = 0; byte[] bs = new byte[length]; while (true) { int readLength = inputStream.read(bs, 0, length - sum); if (readLength > 0) { bout.write(bs, 0, readLength); sum += readLength; } if (sum >= length) { break; } } ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray())); try { RpcCommand commond = (RpcCommand) objectInputStream.readObject(); RpcResponse response = handler.handler(commond); ByteArrayOutputStream objectout = new ByteArrayOutputStream(length); ObjectOutputStream objectOutputStream = new ObjectOutputStream(objectout); objectOutputStream.writeObject(response); objectOutputStream.flush(); byte[] commondBytes = objectout.toByteArray(); int len = commondBytes.length; outputStream.write(0x5A); outputStream.write(len >> 8); outputStream.write(len & 0x00FF); outputStream.write(commondBytes); outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); System.out.println("和客户端连接断开了"); } finally { if (socket != null) { try { socket.close(); } catch (Exception e) { e.printStackTrace(); } } } } } public static void main(String[] args) { RpcHandler rpcHandler = new RpcHandler(); rpcHandler.register(DemoI.class, new IDemoImpl()); RpcServer server = new RpcServer(8081, rpcHandler); server.start(); } }
37.289474
130
0.479181
2eeb379c53ec4b3248294943c30e4fcc6b50a880
729
package ca.zandercraft.doorknockerforge; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvent; public class KnockSounds { public static final ResourceLocation DOOR_KNOCK = new ResourceLocation("doorknockermod:door_knock"); public static SoundEvent DOOR_KNOCK_EVENT = new SoundEvent(DOOR_KNOCK); public static final ResourceLocation TRAPDOOR_KNOCK = new ResourceLocation("doorknockermod:trapdoor_knock"); public static SoundEvent TRAPDOOR_KNOCK_EVENT = new SoundEvent(TRAPDOOR_KNOCK); public static final ResourceLocation FBI_EASTER_EGG = new ResourceLocation("doorknockermod:fbi_easter_egg"); public static SoundEvent FBI_EASTER_EGG_EVENT = new SoundEvent(FBI_EASTER_EGG); }
52.071429
112
0.824417
cbabe1d48016e4bb86b63f1b013348dd2f3546cf
19,731
/* * ModeShape (http://www.modeshape.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.modeshape.sequencer.ddl.dialect.oracle; import java.util.Arrays; import java.util.List; import org.modeshape.sequencer.ddl.DdlConstants; import org.modeshape.sequencer.ddl.StandardDdlLexicon; /** * Oracle-specific constants including key words and statement start phrases. * * @author blafond */ public interface OracleDdlConstants extends DdlConstants { public static final String[] CUSTOM_KEYWORDS = {"ANALYZE", "ASSOCIATE", "TRUNCATE", "MATERIALIZED", "SAVEPOINT", "PURGE", "LOCK", "TRIGGER", "EXPLAIN", "PLAN", "DIMENSION", "DIRECTORY", "DATABASE", "CONTROLFILE", "DISKGROUP", "INDEXTYPE", "SYNONYM", "SEQUENCE", "LIBRARY", "CLUSTER", "OUTLINE", "PACKAGE", "SPFILE", "PFILE", "AUDIT", "COMMIT", "PURGE", "MERGE", "RENAME", "FLASHBACK", "NOAUDIT", "DISASSOCIATE", "NESTED", "REVOKE", "COMMENT", INDEX, "VARCHAR2", "NVARCHAR2", "NUMBER", "BINARY_FLOAT", "BINARY_DOUBLE", "LONG", "RAW", "BLOB", "CLOB", "NCLOB", "BFILE", "INTERVAL", "UNUSABLE"}; interface OracleStatementStartPhrases { static final String[] STMT_ALTER_CLUSTER = {ALTER, "CLUSTER"}; static final String[] STMT_ALTER_DATABASE = {ALTER, "DATABASE"}; static final String[] STMT_ALTER_DIMENSION = {ALTER, "DIMENSION"}; static final String[] STMT_ALTER_DISKGROUP = {ALTER, "DISKGROUP"}; static final String[] STMT_ALTER_FUNCTION = {ALTER, "FUNCTION"}; static final String[] STMT_ALTER_INDEX = {ALTER, INDEX}; static final String[] STMT_ALTER_INDEXTYPE = {ALTER, "INDEXTYPE"}; static final String[] STMT_ALTER_JAVA = {ALTER, "JAVA"}; static final String[] STMT_ALTER_MATERIALIZED = {ALTER, "MATERIALIZED"}; static final String[] STMT_ALTER_OPERATOR = {ALTER, "OPERATOR"}; static final String[] STMT_ALTER_OUTLINE = {ALTER, "OUTLINE"}; static final String[] STMT_ALTER_PACKAGE = {ALTER, "PACKAGE"}; static final String[] STMT_ALTER_PROCEDURE = {ALTER, "PROCEDURE"}; static final String[] STMT_ALTER_PROFILE = {ALTER, "PROFILE"}; static final String[] STMT_ALTER_RESOURCE = {ALTER, "RESOURCE"}; static final String[] STMT_ALTER_ROLE = {ALTER, "ROLE"}; static final String[] STMT_ALTER_ROLLBACK = {ALTER, "ROLLBACK"}; static final String[] STMT_ALTER_SEQUENCE = {ALTER, "SEQUENCE"}; static final String[] STMT_ALTER_SESSION = {ALTER, "SESSION"}; static final String[] STMT_ALTER_SYSTEM = {ALTER, "SYSTEM"}; static final String[] STMT_ALTER_TABLESPACE = {ALTER, "TABLESPACE"}; static final String[] STMT_ALTER_TRIGGER = {ALTER, "TRIGGER"}; static final String[] STMT_ALTER_TYPE = {ALTER, "TYPE"}; static final String[] STMT_ALTER_USER = {ALTER, "USER"}; static final String[] STMT_ALTER_VIEW = {ALTER, "VIEW"}; static final String[][] ALTER_PHRASES = {STMT_ALTER_CLUSTER, STMT_ALTER_DATABASE, STMT_ALTER_DIMENSION, STMT_ALTER_DISKGROUP, STMT_ALTER_FUNCTION, STMT_ALTER_INDEX, STMT_ALTER_INDEXTYPE, STMT_ALTER_JAVA, STMT_ALTER_MATERIALIZED, STMT_ALTER_OPERATOR, STMT_ALTER_OUTLINE, STMT_ALTER_PACKAGE, STMT_ALTER_PROCEDURE, STMT_ALTER_PROFILE, STMT_ALTER_RESOURCE, STMT_ALTER_ROLE, STMT_ALTER_ROLLBACK, STMT_ALTER_SEQUENCE, STMT_ALTER_SESSION, STMT_ALTER_SYSTEM, STMT_ALTER_TABLESPACE, STMT_ALTER_TRIGGER, STMT_ALTER_TYPE, STMT_ALTER_USER, STMT_ALTER_VIEW}; static final String[] STMT_ANALYZE = {"ANALYZE"}; static final String[] STMT_ASSOCIATE_STATISTICS = {"ASSOCIATE", "STATISTICS"}; static final String[] STMT_AUDIT = {"AUDIT"}; /* COMMIT [ WORK ] [ [ COMMENT string ] | [ WRITE [ IMMEDIATE | BATCH ] [ WAIT | NOWAIT ] ] | FORCE string [, integer ] ] ; COMMIT WORK COMMENT "some comment" COMMIT COMMENT "some comment" COMMIT WORK WRITE [ IMMEDIATE | BATCH ] [ WAIT | NOWAIT ] COMMIT WRITE IMMEDIATE NOWAIT; COMMIT WORK WRITE IMMEDIATE NOWAIT; COMMIT FORCE "some string", 10; */ static final String[] STMT_COMMIT_WORK = {"COMMIT", "WORK"}; static final String[] STMT_COMMIT_WRITE = {"COMMIT", "WRITE"}; static final String[] STMT_COMMIT_FORCE = {"COMMIT", "FORCE"}; static final String[] STMT_COMMIT = {"COMMIT"}; // DON"T REGISTER THIS STMT static final String[] STMT_COMMENT_ON = {"COMMENT", "ON"}; static final String[] STMT_CREATE_CLUSTER = {CREATE, "CLUSTER"}; static final String[] STMT_CREATE_CONTEXT = {CREATE, "CONTEXT"}; static final String[] STMT_CREATE_CONTROLFILE = {CREATE, "CONTROLFILE"}; static final String[] STMT_CREATE_DATABASE = {CREATE, "DATABASE"}; static final String[] STMT_CREATE_DIMENSION = {CREATE, "DIMENSION"}; static final String[] STMT_CREATE_DIRECTORY = {CREATE, "DIRECTORY"}; static final String[] STMT_CREATE_DISKGROUP = {CREATE, "DISKGROUP"}; static final String[] STMT_CREATE_FUNCTION = {CREATE, "FUNCTION"}; // PARSE UNTIL '/' static final String[] STMT_CREATE_INDEX = {CREATE, "INDEX"}; static final String[] STMT_CREATE_INDEXTYPE = {CREATE, "INDEXTYPE"}; static final String[] STMT_CREATE_JAVA = {CREATE, "JAVA"}; static final String[] STMT_CREATE_LIBRARY = {CREATE, "LIBRARY"}; // PARSE UNTIL '/' static final String[] STMT_CREATE_MATERIALIZED_VIEW = {CREATE, "MATERIALIZED", "VIEW"}; static final String[] STMT_CREATE_MATERIALIZED_VEIW_LOG = {CREATE, "MATERIALIZED", "VIEW", "LOG"}; static final String[] STMT_CREATE_OPERATOR = {CREATE, "OPERATOR"}; static final String[] STMT_CREATE_OR_REPLACE_DIRECTORY = {CREATE, "OR", "REPLACE", "DIRECTORY"}; // PARSE UNTIL '/' static final String[] STMT_CREATE_OR_REPLACE_FUNCTION = {CREATE, "OR", "REPLACE", "FUNCTION"}; // PARSE UNTIL '/' static final String[] STMT_CREATE_OR_REPLACE_LIBRARY = {CREATE, "OR", "REPLACE", "LIBRARY"}; // PARSE UNTIL '/' static final String[] STMT_CREATE_OR_REPLACE_OUTLINE = {CREATE, "OR", "REPLACE", "OUTLINE"}; static final String[] STMT_CREATE_OR_REPLACE_PUBLIC_OUTLINE = {CREATE, "OR", "REPLACE", "PUBLIC", "OUTLINE"}; // TODO: BML static final String[] STMT_CREATE_OR_REPLACE_PRIVATE_OUTLINE = {CREATE, "OR", "REPLACE", "PRIVATE", "OUTLINE"}; // TODO: // BML static final String[] STMT_CREATE_OR_REPLACE_PACKAGE = {CREATE, "OR", "REPLACE", "PACKAGE"}; static final String[] STMT_CREATE_OR_REPLACE_PROCEDURE = {CREATE, "OR", "REPLACE", "PROCEDURE"}; // PARSE UNTIL '/' static final String[] STMT_CREATE_OR_REPLACE_PUBLIC_SYNONYM = {CREATE, "OR", "REPLACE", "PUBLIC", "SYNONYM"}; static final String[] STMT_CREATE_OR_REPLACE_SYNONYM = {CREATE, "OR", "REPLACE", "SYNONYM"}; static final String[] STMT_CREATE_OR_REPLACE_TRIGGER = {CREATE, "OR", "REPLACE", "TRIGGER"}; // PARSE UNTIL '/ static final String[] STMT_CREATE_OR_REPLACE_TYPE = {CREATE, "OR", "REPLACE", "TYPE"}; static final String[] STMT_CREATE_OUTLINE = {CREATE, "OUTLINE"}; static final String[] STMT_CREATE_PACKAGE = {CREATE, "PACKAGE"}; // PARSE UNTIL '/' static final String[] STMT_CREATE_PFILE = {CREATE, "PFILE"}; static final String[] STMT_CREATE_PROCEDURE = {CREATE, "PROCEDURE"}; // PARSE UNTIL '/' static final String[] STMT_CREATE_PROFILE = {CREATE, "PROFILE"}; static final String[] STMT_CREATE_PUBLIC_DATABASE = {CREATE, "PUBLIC", "DATABASE"}; static final String[] STMT_CREATE_PUBLIC_ROLLBACK = {CREATE, "PUBLIC", "ROLLBACK"}; static final String[] STMT_CREATE_PUBLIC_SYNONYM = {CREATE, "PUBLIC", "SYNONYM"}; static final String[] STMT_CREATE_ROLE = {CREATE, "ROLE"}; static final String[] STMT_CREATE_ROLLBACK = {CREATE, "ROLLBACK"}; static final String[] STMT_CREATE_SEQUENCE = {CREATE, "SEQUENCE"}; static final String[] STMT_CREATE_SPFILE = {CREATE, "SPFILE"}; static final String[] STMT_CREATE_SYNONYM = {CREATE, "SYNONYM"}; static final String[] STMT_CREATE_TABLESPACE = {CREATE, "TABLESPACE"}; static final String[] STMT_CREATE_TRIGGER = {CREATE, "TRIGGER"}; static final String[] STMT_CREATE_TYPE = {CREATE, "TYPE"}; static final String[] STMT_CREATE_USER = {CREATE, "USER"}; static final String[] STMT_CREATE_UNIQUE_INDEX = {CREATE, "UNIQUE", "INDEX"}; static final String[] STMT_CREATE_BITMAP_INDEX = {CREATE, "BITMAP", "INDEX"}; public static final String[][] CREATE_PHRASES = {STMT_CREATE_CLUSTER, STMT_CREATE_CONTEXT, STMT_CREATE_CONTROLFILE, STMT_CREATE_DATABASE, STMT_CREATE_DIMENSION, STMT_CREATE_DIRECTORY, STMT_CREATE_DISKGROUP, STMT_CREATE_FUNCTION, STMT_CREATE_INDEX, STMT_CREATE_INDEXTYPE, STMT_CREATE_JAVA, STMT_CREATE_MATERIALIZED_VIEW, STMT_CREATE_MATERIALIZED_VEIW_LOG, STMT_CREATE_OPERATOR, STMT_CREATE_OR_REPLACE_DIRECTORY, STMT_CREATE_OR_REPLACE_FUNCTION, STMT_CREATE_LIBRARY, STMT_CREATE_OR_REPLACE_LIBRARY, STMT_CREATE_OR_REPLACE_OUTLINE, STMT_CREATE_OR_REPLACE_PROCEDURE, STMT_CREATE_OR_REPLACE_PUBLIC_SYNONYM, STMT_CREATE_OR_REPLACE_SYNONYM, STMT_CREATE_OR_REPLACE_PACKAGE, STMT_CREATE_OR_REPLACE_TRIGGER, STMT_CREATE_OR_REPLACE_TYPE, STMT_CREATE_OUTLINE, STMT_CREATE_PACKAGE, STMT_CREATE_PFILE, STMT_CREATE_PROCEDURE, STMT_CREATE_PROFILE, STMT_CREATE_PUBLIC_DATABASE, STMT_CREATE_PUBLIC_ROLLBACK, STMT_CREATE_PUBLIC_SYNONYM, STMT_CREATE_ROLE, STMT_CREATE_ROLLBACK, STMT_CREATE_SEQUENCE, STMT_CREATE_SPFILE, STMT_CREATE_SYNONYM, STMT_CREATE_TABLESPACE, STMT_CREATE_TRIGGER, STMT_CREATE_TYPE, STMT_CREATE_USER, STMT_CREATE_UNIQUE_INDEX, STMT_CREATE_BITMAP_INDEX, STMT_CREATE_TABLESPACE, STMT_CREATE_PROCEDURE}; static final String[][] SLASHED_STMT_PHRASES = {STMT_CREATE_FUNCTION, STMT_CREATE_LIBRARY, STMT_CREATE_OR_REPLACE_DIRECTORY, STMT_CREATE_OR_REPLACE_FUNCTION, STMT_CREATE_OR_REPLACE_LIBRARY, STMT_CREATE_OR_REPLACE_PROCEDURE, STMT_CREATE_OR_REPLACE_TRIGGER, STMT_CREATE_PACKAGE, STMT_CREATE_PROCEDURE}; static final String[] STMT_DISASSOCIATE_STATISTICS = {"DISASSOCIATE", "STATISTICS"}; static final String[] STMT_DROP_CLUSTER = {DROP, "CLUSTER"}; static final String[] STMT_DROP_CONTEXT = {DROP, "CONTEXT"}; static final String[] STMT_DROP_DATABASE = {DROP, "DATABASE"}; static final String[] STMT_DROP_DIMENSION = {DROP, "DIMENSION"}; static final String[] STMT_DROP_DIRECTORY = {DROP, "DIRECTORY"}; static final String[] STMT_DROP_DISKGROUP = {DROP, "DISKGROUP"}; static final String[] STMT_DROP_FUNCTION = {DROP, "FUNCTION"}; static final String[] STMT_DROP_INDEX = {DROP, "INDEX"}; static final String[] STMT_DROP_INDEXTYPE = {DROP, "INDEXTYPE"}; static final String[] STMT_DROP_JAVA = {DROP, "JAVA"}; static final String[] STMT_DROP_LIBRARY = {DROP, "LIBRARY"}; static final String[] STMT_DROP_MATERIALIZED = {DROP, "MATERIALIZED"}; static final String[] STMT_DROP_OPERATOR = {DROP, "OPERATOR"}; static final String[] STMT_DROP_OUTLINE = {DROP, "OUTLINE"}; static final String[] STMT_DROP_PACKAGE = {DROP, "PACKAGE"}; static final String[] STMT_DROP_PROCEDURE = {DROP, "PROCEDURE"}; static final String[] STMT_DROP_PROFILE = {DROP, "PROFILE"}; static final String[] STMT_DROP_ROLE = {DROP, "ROLE"}; static final String[] STMT_DROP_ROLLBACK = {DROP, "ROLLBACK"}; static final String[] STMT_DROP_SEQUENCE = {DROP, "SEQUENCE"}; static final String[] STMT_DROP_SYNONYM = {DROP, "SYNONYM"}; static final String[] STMT_DROP_TABLESPACE = {DROP, "TABLESPACE"}; static final String[] STMT_DROP_TRIGGER = {DROP, "TRIGGER"}; static final String[] STMT_DROP_TYPE = {DROP, "TYPE"}; static final String[] STMT_DROP_USER = {DROP, "USER"}; static final String[] STMT_DROP_PUBLIC_DATABASE = {DROP, "PUBLIC", "DATABASE"}; static final String[] STMT_DROP_PUBLIC_SYNONYM = {DROP, "PUBLIC", "SYNONYM"}; static final String[][] DROP_PHRASES = {STMT_DROP_CLUSTER, STMT_DROP_CONTEXT, STMT_DROP_DATABASE, STMT_DROP_DIMENSION, STMT_DROP_DIRECTORY, STMT_DROP_DISKGROUP, STMT_DROP_FUNCTION, STMT_DROP_INDEX, STMT_DROP_INDEXTYPE, STMT_DROP_JAVA, STMT_DROP_LIBRARY, STMT_DROP_MATERIALIZED, STMT_DROP_OPERATOR, STMT_DROP_OUTLINE, STMT_DROP_PACKAGE, STMT_DROP_PROCEDURE, STMT_DROP_PROFILE, STMT_DROP_ROLE, STMT_DROP_ROLLBACK, STMT_DROP_SEQUENCE, STMT_DROP_SYNONYM, STMT_DROP_TABLESPACE, STMT_DROP_TRIGGER, STMT_DROP_TYPE, STMT_DROP_USER, STMT_DROP_PUBLIC_DATABASE, STMT_DROP_PUBLIC_SYNONYM}; static final String[] STMT_EXPLAIN_PLAN = {"EXPLAIN", "PLAN"}; static final String[] STMT_FLASHBACK = {"FLASHBACK"}; static final String[] STMT_LOCK_TABLE = {"LOCK", "TABLE"}; static final String[] STMT_MERGE = {"MERGE"}; static final String[] STMT_NOAUDIT = {"NOAUDIT"}; static final String[] STMT_PURGE = {"PURGE"}; static final String[] STMT_RENAME = {"RENAME"}; static final String[] STMT_ROLLBACK_TO_SAVEPOINT = {"ROLLBACK", "TO", "SAVEPOINT"}; static final String[] STMT_ROLLBACK_WORK = {"ROLLBACK", "WORK"}; static final String[] STMT_ROLLBACK = {"ROLLBACK"}; static final String[] STMT_SAVEPOINT = {"SAVEPOINT"}; static final String[] STMT_SET_CONSTRAINT = {SET, "CONSTRAINT"}; static final String[] STMT_SET_CONSTRAINTS = {SET, "CONSTRAINTS"}; static final String[] STMT_SET_ROLE = {SET, "ROLE"}; static final String[] STMT_SET_TRANSACTION = {SET, "TRANSACTION"}; static final String[] STMT_TRUNCATE = {"TRUNCATE"}; static final String[][] SET_PHRASES = {STMT_SET_CONSTRAINT, STMT_SET_CONSTRAINTS, STMT_SET_ROLE, STMT_SET_TRANSACTION}; static final String[][] MISC_PHRASES = {STMT_ANALYZE, STMT_ASSOCIATE_STATISTICS, STMT_AUDIT, STMT_COMMIT_WORK, STMT_COMMIT_WRITE, STMT_COMMIT_FORCE, STMT_COMMENT_ON, STMT_DISASSOCIATE_STATISTICS, STMT_EXPLAIN_PLAN, STMT_FLASHBACK, STMT_LOCK_TABLE, STMT_MERGE, STMT_NOAUDIT, STMT_PURGE, STMT_RENAME, STMT_ROLLBACK_TO_SAVEPOINT, STMT_ROLLBACK_WORK, STMT_ROLLBACK, STMT_SAVEPOINT, STMT_TRUNCATE}; // CREATE TABLE, CREATE VIEW, and GRANT statements. public final static String[] VALID_SCHEMA_CHILD_STMTS = {StandardDdlLexicon.TYPE_CREATE_TABLE_STATEMENT, StandardDdlLexicon.TYPE_CREATE_VIEW_STATEMENT, StandardDdlLexicon.TYPE_GRANT_STATEMENT}; public final static String[] COMPLEX_STMT_TYPES = {OracleDdlLexicon.TYPE_CREATE_FUNCTION_STATEMENT}; } interface OracleDataTypes { static final String[] DTYPE_CHAR_ORACLE = {"CHAR"}; // CHAR(size [BYTE | CHAR]) static final String[] DTYPE_VARCHAR2 = {"VARCHAR2"}; // VARCHAR2(size [BYTE | CHAR]) static final String[] DTYPE_NVARCHAR2 = {"NVARCHAR2"}; // NVARCHAR2(size) static final String[] DTYPE_NUMBER = {"NUMBER"}; // NUMBER(p,s) static final String[] DTYPE_BINARY_FLOAT = {"BINARY_FLOAT "}; static final String[] DTYPE_BINARY_DOUBLE = {"BINARY_DOUBLE"}; static final String[] DTYPE_LONG = {"LONG"}; static final String[] DTYPE_LONG_RAW = {"LONG", "RAW"}; static final String[] DTYPE_RAW = {"RAW"}; // RAW(size) static final String[] DTYPE_BLOB = {"BLOB"}; static final String[] DTYPE_CLOB = {"CLOB"}; static final String[] DTYPE_NCLOB = {"NCLOB"}; static final String[] DTYPE_BFILE = {"BFILE"}; static final String[] DTYPE_INTERVAL_YEAR = {"INTERVAL", "YEAR"}; // INTERVAL YEAR (year_precision) TO MONTH static final String[] DTYPE_INTERVAL_DAY = {"INTERVAL", "DAY"}; // INTERVAL DAY (day_precision) TO SECOND // (fractional_seconds_precision) static final List<String[]> CUSTOM_DATATYPE_START_PHRASES = Arrays.asList(DTYPE_CHAR_ORACLE, DTYPE_VARCHAR2, DTYPE_NVARCHAR2, DTYPE_NUMBER, DTYPE_BINARY_FLOAT, DTYPE_BINARY_DOUBLE, DTYPE_LONG, DTYPE_LONG_RAW, DTYPE_RAW, DTYPE_BLOB, DTYPE_CLOB, DTYPE_NCLOB, DTYPE_BFILE, DTYPE_INTERVAL_YEAR, DTYPE_INTERVAL_DAY); static final List<String> CUSTOM_DATATYPE_START_WORDS = Arrays.asList("VARCHAR2", "NVARCHAR2", "NUMBER", "BINARY_FLOAT", "BINARY_DOUBLE", "LONG", "RAW", "BLOB", "CLOB", "NCLOB", "BFILE", "INTERVAL"); } interface IndexTypes { String BITMAP_JOIN = "BITMAP"; String CLUSTER = "CLUSTER"; String TABLE = "TABLE"; } }
69.231579
130
0.610815
9bbbee7860b4596bdb76a0b08b939fcca1115e92
466
package com.gracelogic.platform.survey.dto.admin; import java.util.UUID; public class ImportCatalogItemsDTO { private UUID catalogId; private String[] items; public UUID getCatalogId() { return catalogId; } public void setCatalogId(UUID catalogId) { this.catalogId = catalogId; } public String[] getItems() { return items; } public void setItems(String[] items) { this.items = items; } }
18.64
49
0.639485
07c11f7282df0d447dfd302e55c970af9a540412
3,113
package net.haesleinhuepf.clijx.morpholibj; import ij.ImagePlus; import ij.measure.ResultsTable; import inra.ijpb.plugins.AnalyzeRegions3D; import inra.ijpb.plugins.Watershed3DPlugin; import net.haesleinhuepf.clij.clearcl.ClearCLBuffer; import net.haesleinhuepf.clij.coremem.enums.NativeTypeEnum; import net.haesleinhuepf.clij.macro.CLIJMacroPlugin; import net.haesleinhuepf.clij.macro.CLIJOpenCLProcessor; import net.haesleinhuepf.clij.macro.documentation.OffersDocumentation; import net.haesleinhuepf.clij2.AbstractCLIJ2Plugin; import net.haesleinhuepf.clij2.CLIJ2; import net.haesleinhuepf.clij2.utilities.HasClassifiedInputOutput; import net.haesleinhuepf.clij2.utilities.IsCategorized; import org.scijava.plugin.Plugin; public abstract class AbstractMorphoLibJAnalyzeRegions3D extends AbstractCLIJ2Plugin implements CLIJMacroPlugin, CLIJOpenCLProcessor, OffersDocumentation, IsCategorized, HasClassifiedInputOutput { protected String property = null; protected AbstractMorphoLibJAnalyzeRegions3D(String property) { this.property = property; } @Override public boolean executeCL() { boolean result = morphoLibJAnalyzeRegions3D(getCLIJ2(), (ClearCLBuffer) (args[0]), (ClearCLBuffer) (args[1]), property); return result; } @Override public String getParameterHelpText() { return "Image labels_input, ByRef Image parametric_map_destination"; } protected static boolean morphoLibJAnalyzeRegions3D(CLIJ2 clij2, ClearCLBuffer labels, ClearCLBuffer parametric_map, String property) { // pull image from GPU ImagePlus labels_imp = clij2.pull(labels); ResultsTable table = new AnalyzeRegions3D().process(labels_imp); ClearCLBuffer vector = clij2.create(table.getCounter(), 1, 1); clij2.pushResultsTableColumn(vector, table, property); ClearCLBuffer vector_with_background = clij2.create(table.getCounter() + 1, 1, 1); clij2.setColumn(vector_with_background, 0, 0); clij2.paste(vector, vector_with_background, 1, 0, 0); clij2.replaceIntensities(labels, vector_with_background, parametric_map); // clean up vector.close(); vector_with_background.close(); return true; } @Override public String getDescription() { return "Applies MorphoLibJs Analyse Regions 3D to a label image an produces a parametric image visualizing " + property + ".\n\n" + "See also: https://imagej.net/MorphoLibJ.html#Region_analysis\n\n" + "Background is set to 0."; } @Override public ClearCLBuffer createOutputBufferFromSource(ClearCLBuffer input) { return getCLIJ2().create(input.getDimensions(), NativeTypeEnum.Float); } @Override public String getAvailableForDimensions() { return "3D"; } @Override public String getCategories() { return "Label,Measurement"; } @Override public String getInputType() { return "Label Image"; } @Override public String getOutputType() { return "Image"; } }
33.117021
194
0.724382
a83f401a7ff077457e1142d241fed50a818fbadf
502
package com.nxist.controller.home; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value="/admin") public class AdminIndexController { @RequestMapping(value="/index") public ModelAndView index() { ModelAndView mav = new ModelAndView(); mav.addObject("index","请在右侧选择项进行管理!" ); mav.setViewName("jsp/hint"); return mav; } }
23.904762
62
0.74502
fee5b9e77dc9688fdbb82587e423ada853148380
589
package com.emailclue.api.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class CreateAccountResponse { private final Clue clue; private final String apiToken; @JsonCreator public CreateAccountResponse( @JsonProperty("apiToken") String apiToken, @JsonProperty("clue") Clue clue) { this.apiToken = apiToken; this.clue = clue; } public Clue getClue() { return clue; } public String getApiToken() { return apiToken; } }
21.035714
54
0.662139
8e8f25bd72f316b0083ded4665aa781f410469cc
1,057
package com.lznby.jetpack.content.design.view; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; /** * 处理 ScrollView 与 RecyclerView 滑动冲突的RecyclerView * * @author Lznby */ public class ScrollRecyclerView extends RecyclerView { public ScrollRecyclerView(@NonNull Context context) { super(context); } public ScrollRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public ScrollRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,//右移运算符,相当于除于4 MeasureSpec.AT_MOST);//测量模式取最大值 super.onMeasure(widthMeasureSpec, heightMeasureSpec);//重新测量高度 } }
31.088235
101
0.737938
5e962d4b0c8bacfb44f18a06a36e8190989bb591
4,694
/* * Copyright 2021 MeshDynamics. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cube.spring.egress; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import java.util.Optional; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import io.md.logger.LogMgr; import org.slf4j.Logger; import org.springframework.core.annotation.Order; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.support.HttpRequestWrapper; import io.cube.agent.CommonConfig; import io.md.constants.Constants; import io.md.utils.CommonUtils; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.SpanContext; /** * Order is to specify in which order the filters are to be executed. Lower the order, early the * filter is executed. * Mock Filter should execute after Data Filter, so that in Mock mode, Data Filter can just * return without recording the request. Otherwise Mock Filter would change the URI and * the shouldMockService() will return false, as this would be evaluated on the changed URI. **/ @Order(3000) public class RestTemplateMockInterceptor implements ClientHttpRequestInterceptor { private static final Logger LOGGER = LogMgr.getLogger(RestTemplateMockInterceptor.class); @Override public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution execution) throws IOException { URI originalUri = httpRequest.getURI(); CommonConfig commonConfig = CommonConfig.getInstance(); String serviceName = CommonUtils.getEgressServiceName(originalUri); HttpRequestWrapper newRequest = null; Span[] clientSpan = {null}; Scope[] clientScope = {null}; try { newRequest = commonConfig.getMockingURI(originalUri, serviceName).map(mockURI -> { Optional<Span> ingressSpan = CommonUtils.getCurrentSpan(); //Empty ingress span pertains to DB initialization scenarios. SpanContext spanContext = ingressSpan.map(Span::context) .orElse(CommonUtils.createDefSpanContext()); clientSpan[0] = CommonUtils .startClientSpan(Constants.MD_CHILD_SPAN, spanContext, false); clientScope[0] = CommonUtils.activateSpan(clientSpan[0]); MyHttpRequestWrapper request = new MyHttpRequestWrapper(httpRequest, mockURI); commonConfig.authToken.ifPresent(auth -> { request.putHeader(io.cube.agent.Constants.AUTHORIZATION_HEADER, Arrays.asList(auth)); }); if (!commonConfig.authToken.isPresent()) { LOGGER.info("Auth token not present for Mocking service"); } return request; }).orElse(null); } catch (URISyntaxException e) { LOGGER.error("Mocking filter issue, exception during setting URI!", e); if (clientSpan[0] != null) { clientSpan[0].finish(); } if (clientScope[0] != null) { clientScope[0].close(); } return execution.execute(httpRequest, bytes); } ClientHttpResponse response = (newRequest == null) ? execution.execute(httpRequest, bytes) : execution.execute(newRequest, bytes); if (clientSpan[0] != null) { clientSpan[0].finish(); } if (clientScope[0] != null) { clientScope[0].close(); } return response; } public class MyHttpRequestWrapper extends HttpRequestWrapper { private URI mockURI; private final MultivaluedMap<String, String> customHeaders; public MyHttpRequestWrapper(HttpRequest httpRequest, URI mockURI) { super(httpRequest); this.mockURI = mockURI; this.customHeaders = new MultivaluedHashMap<>(); } public void putHeader(String name, List<String> value) { this.customHeaders.put(name, value); } @Override public URI getURI() { return mockURI; } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.putAll(super.getHeaders()); headers.putAll(customHeaders); return headers; } } }
31.716216
96
0.753515
5f234d3d70b39d025b8b029d681c056db07de125
1,792
/* * Copyright 2015-2017 GenerallyCloud.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. */ package com.generallycloud.baseio.container.jms; import com.alibaba.fastjson.JSON; public class TextMessage extends BasicMessage { private String text = null; public TextMessage(String messageId, String queueName, String text) { super(messageId, queueName); this.text = text; } public String getReadText() { return text; } @Override public int getMsgType() { return Message.TYPE_TEXT; } @Override public String toString() { return new StringBuilder(24).append("{\"msgType\":2,\"msgId\":\"").append(getMsgId()) .append("\",\"queueName\":\"").append(getQueueName()).append("\",\"timestamp\":") .append(getTimestamp()).append(",\"text\":\"").append(getText0()).append("\"}") .toString(); } protected String getText0() { if (text == null) { return ""; } return text; } public static void main(String[] args) { TextMessage message = new TextMessage("mid", "qname", null); System.out.println(JSON.toJSONString(message)); System.out.println(message.toString()); } }
29.377049
97
0.635045
00373a635216a4b5f9e7e6aebaa19c3f5ed2d49a
369
package de.twenty11.skysail.server.mgt.captures; import io.skysail.domain.Identifiable; import lombok.*; @Getter @Setter public class RequestCapture implements Identifiable { private String id; private Integer count; private String key; public RequestCapture(String key, Integer count) { this.key = key; this.count = count; } }
18.45
54
0.704607
5993d879bc3d5346830da0e34df1be89c5ab7721
1,170
package com.example.tenbillionfiles.startup; import com.example.tenbillionfiles.services.CounterService; import com.example.tenbillionfiles.services.FileStorageService; import com.example.tenbillionfiles.services.LuceneIndexService; import com.example.tenbillionfiles.services.RegexIndexService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class StartupApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Autowired private FileStorageService fileStorageService; @Autowired private RegexIndexService regexIndexService; @Autowired private LuceneIndexService luceneIndexService; @Autowired private CounterService counterService; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { fileStorageService.initStorage(); regexIndexService.initIndexes(); luceneIndexService.initIndexes(); counterService.initFileCounter(); } }
30.789474
95
0.815385
f448387e5a34a64a222b1c39b650769d1be583fa
1,219
package com.artesseum.popr; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; /** * Created by apoca on 30/12/2017. */ public class RedBubble extends Bubble { Bitmap[] bubble = new Bitmap[4]; public RedBubble(Context context) { super(context); bubble[0] = BitmapFactory.decodeResource(context.getResources(),R.drawable.bubble11); bubble[1] = BitmapFactory.decodeResource(context.getResources(),R.drawable.bubble11); bubble[2] = BitmapFactory.decodeResource(context.getResources(),R.drawable.bubble11); bubble[3] = BitmapFactory.decodeResource(context.getResources(),R.drawable.bubble11); resetPosition(); } @Override public Bitmap getBitmap() { return bubbles[bubbleFrame]; } @Override public int getHeight() { return bubbles[0].getHeight(); } @Override public int getWidth() { return bubbles[0].getWidth(); } @Override public void resetPosition() { bubbleY = -(200+random.nextInt(500)); bubbleX = random.nextInt(300); velocity = 8 + random.nextInt(21); } }
27.704545
94
0.637408
ce6466e5f891b025b28b49573bd65e8a6dc01edf
1,701
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.bpmn.client.forms.fields.notificationsEditor.converter; import org.junit.Assert; import org.junit.Test; import org.kie.workbench.common.stunner.bpmn.client.forms.fields.model.NotificationType; public class NotificationTypeDateConverterTest { private NotificationTypeDateConverter notificationTypeDateConverter = new NotificationTypeDateConverter(); @Test public void toModelValueTest() { Assert.assertEquals(NotificationType.NotStartedNotify, notificationTypeDateConverter.toModelValue("NotStartedNotify")); Assert.assertEquals(NotificationType.NotCompletedNotify, notificationTypeDateConverter.toModelValue("NotCompletedNotify")); } @Test public void toWidgetValueTest() { Assert.assertEquals(NotificationType.NotStartedNotify.getType(), notificationTypeDateConverter.toWidgetValue(NotificationType.NotStartedNotify)); Assert.assertEquals(NotificationType.NotCompletedNotify.getType(), notificationTypeDateConverter.toWidgetValue(NotificationType.NotCompletedNotify)); } }
43.615385
157
0.787772
64ba3c53ff4075799d62d0f77aea011e1ea17b4a
1,314
package org.apache.ode.bpel.extensions.comm.messages.engineOut; import java.io.Serializable; //@stmz: base class for all outgoing messages public class MessageBase implements Serializable { private static final long serialVersionUID = -1075592551376260168L; private Long MessageID; private Long TimeStamp; private Long GenericControllerID; private Boolean blocking; private String sceInstanceId; private String modelId; public Long getMessageID() { return MessageID; } public Long getTimeStamp() { return TimeStamp; } public Long getGenericControllerID() { return GenericControllerID; } public Boolean getBlocking() { return blocking; } public void setMessageID(Long messageID) { MessageID = messageID; } public void setTimeStamp(Long timeStamp) { TimeStamp = timeStamp; } public void setGenericControllerID(Long genericControllerID) { GenericControllerID = genericControllerID; } public void setBlocking(Boolean blocking) { this.blocking = blocking; } public String getSceInstanceId() { return sceInstanceId; } public void setSceInstanceId(String sceInstanceId) { this.sceInstanceId = sceInstanceId; } public String getProcessModelId() { return modelId; } public void setProcessModelId(String modelId) { this.modelId = modelId; } }
18.25
68
0.760274
ba71e268183c643c8ce6bfbe82d39b3c94928e1d
1,635
/** * Copyright (C) 2014 Xillio ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.xillio.xill.plugins.mongodb.constructs; import com.mongodb.client.MongoCollection; import nl.xillio.xill.api.components.MetaExpression; import nl.xillio.xill.api.construct.Argument; import nl.xillio.xill.api.construct.ConstructContext; import org.bson.Document; /** * This construct represents the count method on MongoDB. * * @author Thomas Biesaart * @see <a href="https://docs.mongodb.org/v3.0/reference/method/db.collection.count/#db.collection.count">db.collection.count</a> */ public class CountConstruct extends AbstractCollectionApiConstruct { @Override protected Argument[] getApiArguments() { return new Argument[]{ new Argument("query", emptyObject(), OBJECT) }; } @Override MetaExpression process(MetaExpression[] arguments, MongoCollection<Document> collection, ConstructContext context) { Document query = toDocument(arguments[0]); long count = collection.count(query); return fromValue(count); } }
34.0625
129
0.725994
e6729125056202918bfb58c96f5a00e0d19d77ff
277
package club.guanghao.service; import club.guanghao.entity.User; /** * @author 黄光昊 * @create 2019-09-23-15:17 */ public interface UserService { /** * 将前台拿到的 User到 dao 层查询,返回 User 对象 * @param user * @return */ public User getUser(User user); }
15.388889
38
0.620939
40ca399eee010745928f117a777e3b00479feefe
2,580
package com.stephenboyer.soapstore.domain; import com.stephenboyer.soapstore.util.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; import javax.sound.sampled.Line; import java.io.Serializable; import java.util.*; @Component @Scope(value="session") public class Cart { private static final Logger logger = LoggerFactory.getLogger(Cart.class.getSimpleName()); private List<LineItem> lineItems = new ArrayList<>(); private Long total; private Long sales_tax; private Long subtotal; private Boolean isEmpty = true; private Calendar created; public Cart(){ sales_tax = 0L; subtotal = 0L; total = 0L; created = Calendar.getInstance(); } public void addItem(String sku, Integer quantity){ if(!lineItems.contains(new LineItem(sku, quantity))){ LineItem item = new LineItem("", sku, "", quantity); lineItems.add(item); } else { for(LineItem item : lineItems){ if(item.getProductSku().equals(sku)){ logger.info(item.toString()); logger.info("quantity: " + quantity); Integer q = item.getQuantity(); q += quantity; item.setQuantity(q); logger.info(item.toString()); } } } isEmpty = false; } public Boolean isEmpty() { return isEmpty; } public void setEmpty(Boolean empty) { isEmpty = empty; } public void setCreated(Calendar created) { this.created = created; } public List<LineItem> getLineItems() { return lineItems; } public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; } public Long getTotal() { return total; } public void setTotal(Long total) { this.total = total; } public Long getSales_tax() { return sales_tax; } public void setSales_tax(Long sales_tax) { this.sales_tax = sales_tax; } public Long getSubtotal() { return subtotal; } public void setSubtotal(Long subtotal) { this.subtotal = subtotal; } public Calendar getCreated() { return created; } @Override public String toString() { return Strings.toString(this); } }
22.631579
93
0.602326
525b8a5dd28478de351834bd71493ccc48ac21ae
1,230
package kr.dogfoot.hwplib.reader.bodytext.paragraph.control.secd; import kr.dogfoot.hwplib.object.bodytext.control.sectiondefine.BatangPageInfo; import kr.dogfoot.hwplib.object.bodytext.control.sectiondefine.ListHeaderForBatangPage; import kr.dogfoot.hwplib.reader.bodytext.ForParagraphList; import kr.dogfoot.hwplib.util.compoundFile.reader.StreamReader; /** * 바탕쪽 정보를 읽기 위한 객체 * * @author neolord */ public class ForBatangPageInfo { /** * 바탕쪽 정보를 읽는다. * * @param bpi 바탕쪽 정보 * @param sr 스트림 리더 * @throws Exception */ public static void read(BatangPageInfo bpi, StreamReader sr) throws Exception { listHeader(bpi.getListHeader(), sr); ForParagraphList.read(bpi.getParagraphList(), sr); } /** * 바탕쪽의 문단 리스트 헤더 레코드를 읽는다. * * @param lh 바탕쪽의 문단 리스트 헤더 레코드 * @param sr 스트림 리더 * @throws Exception */ private static void listHeader(ListHeaderForBatangPage lh, StreamReader sr) throws Exception { lh.setParaCount(sr.readSInt4()); lh.getProperty().setValue(sr.readUInt4()); lh.setTextWidth(sr.readUInt4()); lh.setTextHeight(sr.readUInt4()); sr.skipToEndRecord(); } }
28.604651
87
0.665041
a60e7f916de7af2da43138f3d9aa8f3f2d383066
2,815
package com.example; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.google.common.base.Objects; import java.io.Serializable; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"bundleCreatedTimestamp", "loadJobSubmissionAttempts", "retryAttemptsAfterJobFailures", "previousFailedJobIds"}) public class LoadRequestAttributes implements Serializable { @JsonProperty("bundleCreatedTimestamp") private Long bundleCreatedTimestamp; @JsonProperty("loadJobSubmissionAttempts") private Integer loadJobSubmissionAttempts; @JsonProperty("retryAttemptsAfterJobFailures") private Integer retryAttemptsAfterJobFailures; @JsonProperty("previousFailedJobIds") private List<String> previousFailedJobIds; public Long getBundleCreatedTimestamp() { return bundleCreatedTimestamp; } public void setBundleCreatedTimestamp(Long bundleCreatedTimestamp) { this.bundleCreatedTimestamp = bundleCreatedTimestamp; } public Integer getLoadJobSubmissionAttempts() { return loadJobSubmissionAttempts; } public void setLoadJobSubmissionAttempts(Integer loadJobSubmissionAttempts) { this.loadJobSubmissionAttempts = loadJobSubmissionAttempts; } public Integer getRetryAttemptsAfterJobFailures() { return retryAttemptsAfterJobFailures; } public void setRetryAttemptsAfterJobFailures(Integer retryAttemptsAfterJobFailures) { this.retryAttemptsAfterJobFailures = retryAttemptsAfterJobFailures; } public List<String> getPreviousFailedJobIds() { return previousFailedJobIds; } public void setPreviousFailedJobIds(List<String> previousFailedJobIds) { this.previousFailedJobIds = previousFailedJobIds; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LoadRequestAttributes that = (LoadRequestAttributes) o; return Objects.equal(getBundleCreatedTimestamp(), that.getBundleCreatedTimestamp()) && Objects .equal(getLoadJobSubmissionAttempts(), that.getLoadJobSubmissionAttempts()) && Objects .equal(getRetryAttemptsAfterJobFailures(), that.getRetryAttemptsAfterJobFailures()); } @Override public int hashCode() { return Objects.hashCode(getBundleCreatedTimestamp(), getLoadJobSubmissionAttempts(), getRetryAttemptsAfterJobFailures()); } @Override public String toString() { return "LoadRequestAttributes{" + "bundleCreatedTimestamp='" + bundleCreatedTimestamp + '\'' + ", loadJobSubmissionAttempts='" + loadJobSubmissionAttempts + '\'' + ", retryAttemptsAfterJobFailures='" + retryAttemptsAfterJobFailures + '\'' + '}'; } }
35.1875
132
0.77833
af1136cdbb84fe2208456ca742de3ef9e4f8fc70
427
package com.libqa.web.repository; import com.libqa.web.domain.FeedThread; import com.libqa.web.domain.FeedReply; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface FeedReplyRepository extends JpaRepository<FeedReply, Integer> { List<FeedReply> findByFeedThreadFeedThreadId(Integer feedThreadId); Integer countByFeedThreadAndIsDeletedFalse(FeedThread feedThread); }
32.846154
80
0.833724
b5aca1a01219221509d9c2257b15c10a93a80f8b
12,087
package telekit.desktop.tools.apiclient; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.concurrent.Task; import telekit.base.domain.LineSeparator; import telekit.base.domain.security.UsernamePasswordCredentials; import telekit.base.net.ApacheHttpClient; import telekit.base.net.HttpClient; import telekit.base.net.HttpClient.Request; import telekit.base.net.HttpClient.Response; import telekit.base.net.HttpConstants; import telekit.base.net.HttpConstants.AuthScheme; import telekit.base.preferences.Proxy; import telekit.base.util.PlaceholderReplacer; import telekit.desktop.tools.apiclient.Template.BatchSeparator; import telekit.desktop.tools.common.Param; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; import java.util.*; import java.util.concurrent.TimeUnit; import static org.apache.commons.collections4.SetUtils.emptyIfNull; import static org.apache.commons.lang3.StringUtils.*; import static telekit.base.i18n.I18n.t; import static telekit.base.util.NumberUtils.ensureRange; import static telekit.base.util.PlaceholderReplacer.containsPlaceholders; import static telekit.base.util.PlaceholderReplacer.format; import static telekit.desktop.i18n.DesktopMessages.*; import static telekit.desktop.tools.common.ReplacementUtils.*; public class Executor extends Task<ObservableList<CompletedRequest>> { public static final String BATCH_PLACEHOLDER_NAME = "_batch"; public static final String HEADER_KV_SEPARATOR = ":"; public static final int MAX_CSV_SIZE = 100000; private final Template template; private final String[][] csv; private final ObservableList<CompletedRequest> log; private final ApacheHttpClient.Builder httpClientBuilder; private AuthScheme authScheme; private UsernamePasswordCredentials credentials; private Proxy proxy; private Duration timeoutBetweenRequests = Duration.ofMillis(200); public Executor(Template template, String[][] csv, ObservableList<CompletedRequest> log) { Objects.requireNonNull(template); Objects.requireNonNull(csv); this.template = new Template(template); this.csv = csv; this.log = log; this.httpClientBuilder = ApacheHttpClient.builder() .timeouts((int) TimeUnit.SECONDS.toMillis(template.getWaitTimeout())) .ignoreCookies() .trustAllCertificates(); } public void setTimeoutBetweenRequests(int timeoutBetweenRequests) { this.timeoutBetweenRequests = Duration.ofMillis(timeoutBetweenRequests); } public void setProxy(Proxy proxy) { this.proxy = proxy; } public void setPasswordBasedAuth(AuthScheme authScheme, UsernamePasswordCredentials credentials) { this.authScheme = authScheme; this.credentials = credentials; } public int getPlannedRequestCount() { int rowCount = csv.length; int batchSize = template.getBatchSize(); return batchSize == 0 ? rowCount : rowCount / batchSize + ((rowCount % batchSize > 0) ? 1 : 0); } @Override protected ObservableList<CompletedRequest> call() { Map<String, String> replacements = new HashMap<>(); Set<Param> params = emptyIfNull(template.getParams()); Map<String, String> origHeaders = new HashMap<>(parseHeaders(template.getHeaders())); configureAuth(origHeaders); configureProxy(); HttpClient httpClient = httpClientBuilder.build(); // batch size is limited by rows count int batchSize = ensureRange(template.getBatchSize(), 1, csv.length); // sequential index is always incremented by 1, it doesn't depend on loop step value int sequentialIndex = 0; for (int idx = 0; idx < csv.length & idx < MAX_CSV_SIZE; idx += batchSize) { // stop if task has been canceled if (isCancelled()) { break; } // template can contain generated params, that have to be updated on each iteration putTemplatePlaceholders(replacements, params); String uri, body, userData; SortedMap<String, String> headers = new TreeMap<>(origHeaders); int processedLines; if (batchSize == 1) { /* requests payload not merged (batch mode = off) */ String[] row = csv[idx]; // update replacement params putCsvPlaceholders(replacements, row); putIndexPlaceholders(replacements, sequentialIndex); // uri, headers and body can contain any placeholders uri = format(template.getUri(), replacements); body = format(template.getBody(), replacements); replaceHeadersPlaceholders(headers, replacements); userData = Arrays.toString(row) + " | " + uri; processedLines = 1; sequentialIndex++; } else { /* requests payload merged (batch mode = on) */ int endIdx = Math.min(idx + batchSize, csv.length); String[][] batchCsv = Arrays.copyOfRange(csv, idx, endIdx); String[] batchBody = new String[batchCsv.length]; // uri and headers can't contain CSV or index placeholders, // because they have to be identical for multiple CSV rows uri = format(template.getUri(), replacements); replaceHeadersPlaceholders(headers, replacements); // batch wrapper is allowed to contain params placeholders (e.g. API key) String batchWrapper = format(template.getBatchWrapper(), replacements); // only payload can contain CSV or index placeholders Map<String, String> batchReplacements = new HashMap<>(replacements); for (int batchIndex = 0; batchIndex < batchCsv.length; batchIndex++) { String[] row = batchCsv[batchIndex]; putCsvPlaceholders(batchReplacements, row); putIndexPlaceholders(batchReplacements, sequentialIndex); batchBody[batchIndex] = format(template.getBody(), batchReplacements); sequentialIndex++; } body = mergeBatchItems(batchBody, batchWrapper, template.getBatchSeparator()); userData = uri; processedLines = batchCsv.length; } // simulate unsuccessful requests //if (List.of(1, 3).contains(idx)) { body = "(*&^%^%$%"; } // perform request final Request request = new Request(template.getMethod(), URI.create(uri), headers, body); final Response response = httpClient.execute(request); final CompletedRequest result = new CompletedRequest(idx, processedLines, request, response, userData); // update progress property Platform.runLater(() -> log.add(result)); updateProgress(idx, csv.length); // timeout before sending next request if (idx < csv.length - 1) { sleepSilently(timeoutBetweenRequests); } } return log; } private void configureProxy() { if (proxy != null) { httpClientBuilder.proxy(proxy); } } private void configureAuth(Map<String, String> userHeaders) { if (authScheme == null || credentials == null) { return; } // we have to remove authorization header manually, because Apache HTTP won't override it userHeaders.entrySet().removeIf(e -> HttpConstants.Headers.AUTHORIZATION.equalsIgnoreCase(e.getKey())); // placeholders use % sign that makes whole URL invalid String safeUri = PlaceholderReplacer.removePlaceholders(template.getUri()); if (authScheme == AuthScheme.BASIC) { httpClientBuilder.basicAuth( credentials.toPasswordAuthentication(), cleanupURI(URI.create(safeUri)), true ); } } private void sleepSilently(Duration duration) { try { Thread.sleep(duration.toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } private static URI cleanupURI(URI uri) { try { return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), null, null, null); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public static List<String> validate(Template template, String[][] csv) { Set<Param> params = emptyIfNull(template.getParams()); Map<String, String> replacements = new HashMap<>(); List<String> warnings = new ArrayList<>(); // verify max size if (csv.length > MAX_CSV_SIZE) { warnings.add(t(TOOLS_MSG_VALIDATION_CSV_THRESHOLD_EXCEEDED, MAX_CSV_SIZE)); } // verify that all non-autogenerated params values has been specified boolean hasBlankValues = putTemplatePlaceholders(replacements, params); if (hasBlankValues) { warnings.add(t(TOOLS_MSG_VALIDATION_BLANK_PARAM_VALUES)); } int firstRowSize = 0, maxRowSize = 0; String payloadFormatted = ""; for (int rowIndex = 0; rowIndex < csv.length & rowIndex < MAX_CSV_SIZE; rowIndex++) { String[] row = csv[rowIndex]; if (rowIndex == 0) { firstRowSize = maxRowSize = row.length; // unresolved placeholders validation can be performed for the first line only if (template.getBatchSize() == 0) { putIndexPlaceholders(replacements, rowIndex); putCsvPlaceholders(replacements, row); payloadFormatted = format( template.getUri() + defaultString(template.getBody()) + defaultString(template.getHeaders()) , replacements); } else { Map<String, String> batchReplacements = new HashMap<>(replacements); putIndexPlaceholders(batchReplacements, rowIndex); putCsvPlaceholders(batchReplacements, row); payloadFormatted = format(template.getUri() + defaultString(template.getHeaders()), replacements) + format(defaultString(template.getBody()), batchReplacements); } } else { maxRowSize = row.length; } } // verify that all csv table rows has the same columns count if (firstRowSize != maxRowSize) { warnings.add(t(TOOLS_MSG_VALIDATION_MIXED_CSV)); } // verify that all placeholders has been replaced if (containsPlaceholders(payloadFormatted)) { warnings.add(t(TOOLS_MSG_VALIDATION_UNRESOLVED_PLACEHOLDERS)); } return warnings; } private static Map<String, String> parseHeaders(String text) { Map<String, String> headers = new LinkedHashMap<>(); if (isBlank(text)) { return headers; } for (String line : text.split(LineSeparator.LINE_SPLIT_PATTERN)) { if (isBlank(line)) { continue; } String[] kv = line.split(HEADER_KV_SEPARATOR); if (kv.length == 2) { headers.put(trim(kv[0]), trim(kv[1])); } } return headers; } private static void replaceHeadersPlaceholders(Map<String, String> headers, Map<String, String> replacements) { for (Map.Entry<String, String> entry : headers.entrySet()) { entry.setValue(format(entry.getValue(), replacements)); } } private static String mergeBatchItems(String[] items, String wrapper, BatchSeparator separator) { return format(wrapper, Map.of(BATCH_PLACEHOLDER_NAME, String.join(separator.getValue(), items))); } }
41.112245
119
0.632084
f4bb00361dc51efb1a3de2869d198c471541d614
2,799
package intro_to_statistics; import java.util.*; public class Warmup { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int arrayLength = sc.nextInt(); int[] arr = new int[arrayLength]; for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } Arrays.sort(arr); System.out.printf("%.1f%n", getMean(arr)); System.out.printf("%.1f%n", getMedian(arr)); System.out.println(getMode(arr)); System.out.printf("%.1f%n", getStandardDeviation(arr)); sc.close(); } private static double getMean(int[] arr) { double total = 0; for (int num : arr) { total += num; } return total / arr.length; } private static double getMedian(int[] arr) { if (arr.length % 2 == 1) { return (double) arr[arr.length / 2]; } else { return (double) (arr[arr.length / 2] + arr[(arr.length / 2) - 1]) / 2.0; } } public static int getMode(int[] input) { int returnVal = input[0]; // stores element to be returned int repeatCount = 0; // counts the record number of repeats int prevRepCnt = 0; // temporary count for repeats int lowerValue = Integer.MAX_VALUE; // initalize it with the highest integer value - 2147483647 for (int i=0; i<input.length; i++) { // goes through each elem for (int j=i; j<input.length; j++) { // compares to each elem after the first elem if (i != j && input[i] == input[j]) { // if matching values repeatCount++; // gets the repeat count if (repeatCount>prevRepCnt) { // a higher count of repeats than before returnVal=input[i]; // return that element lowerValue = returnVal; // set the variable lowerValue to be the lower value } else if ((repeatCount == prevRepCnt) && (input[i] < lowerValue)) { returnVal=input[i]; // return that element lowerValue = returnVal; // set the variable lowerValue to be the lower value } prevRepCnt = repeatCount; // Keeps the highest repeat record } repeatCount=0; // resets repeat Count for next comparison } } return returnVal; } private static double getStandardDeviation(int[] arr) { double mean = getMean(arr); double totalNumerator = 0; for (int num : arr) { double diff = num - mean; totalNumerator += diff * diff; } return Math.sqrt(totalNumerator / arr.length); } }
36.350649
103
0.53269
661408ba4149ca91811e5b9ff87e57d24c1dc3e5
913
package com.cloud.base.user.param; import com.cloud.base.common.core.entity.CommonEntity; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.Date; /** * 用户中心-岗位信息(SysPosition)实体类 * * @author lh0811 * @since 2021-08-10 21:55:23 */ @Setter @Getter public class SysPositionQueryParam implements Serializable { /** * 岗位编号 */ @ApiModelProperty(value="岗位编号") private String no; /** * 岗位名称 */ @ApiModelProperty(value="岗位名称") private String name; @ApiModelProperty(value = "最早创建时间") private Date createTimeLow; @ApiModelProperty(value = "最晚创建时间") private Date createTimeUp; @ApiModelProperty(value = "页码") private Integer pageNum = CommonEntity.pageNum; @ApiModelProperty(value = "每页数据条数") private Integer pageSize = CommonEntity.pageSize; }
19.425532
60
0.696605
026facf24bad08dcd599ebe0b70ae8d90414c724
1,065
package it.polimi.ingsw.message.viewMsg; import it.polimi.ingsw.message.ViewObserver; import java.util.ArrayList; /** * PPController ---> VV ---> CLI * * msg from the Production Power controller to the client after a request of activating * this ability so after found which one/ones can be activated ask it to the client * * availableCardSpace: * - 0 ---> base PP * - 1,2,3 ---> card Space * - 4,5 ---> Special */ public class VActivateProductionPowerRequestMsg extends ViewGameMsg{ private String username; private ArrayList<Integer> activatablePP; public VActivateProductionPowerRequestMsg(String msgContent, String username, ArrayList<Integer> activatablePP) { super(msgContent); this.username=username; this.activatablePP=activatablePP; } public String getUsername(){return username;} public ArrayList<Integer> getActivatablePP(){return activatablePP;} @Override public void notifyHandler(ViewObserver viewObserver) { viewObserver.receiveMsg(this); } }
28.783784
117
0.707042
301c6b68c0f5aae0f1f71236c3441c4ba03427ef
1,926
/* * Copyright 2019 ConsenSys AG. * * 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 tech.pegasys.pantheon.ethereum.graphql.internal.methods; public enum GraphQLRpcDataFetcherType { BLOCK("Query", "block"), BLOCKS("Query", "blocks"), PENDING("Query", "pending"), TRANSACTION("Query", "transaction"), LOGS("Query", "logs"), GAS_PRICE("Query", "gasPrice"), PROTOCOL_VERSION("Query", "protocolVersion"), SYNCING("Query", "syncing"), PARENT("Block", "parent"), OMMERS("Block", "ommers"), OMMER_AT("Block", "ommerAt"), TRANSACTIONS("Block", "transactions"), TRANSACTION_AT("Block", "transactionAt"), ACCOUNT("Block", "account"), CALL("Block", "call"), ESTIMATE_GAS("Block", "estimateGas"), MINER("Block", "miner"), BLOCK_LOG("Block", "logs"), STORAGE("Account", "storage"), SEND_RAW_TRANSACTION("Mutation", "sendRawTransaction"), TRANSACTION_FROM("Transaction", "from"), TRANSACTION_TO("Transaction", "to"), TRANSACTION_CREATED_CONTRACT("Transaction", "createdContract"), TRANSACTION_BLOCK("Transaction", "block"), TRANSACTION_LOGS("Transaction", "logs"), LOG_ACCOUNT("Log", "account"); private final String type; private final String field; GraphQLRpcDataFetcherType(final String type, final String field) { this.type = type; this.field = field; } public String getType() { return type; } public String getField() { return field; } }
32.644068
118
0.705088
0c595002efb73fe9608261987682c51ef113854e
3,229
package org.redquark.leetcode.challenge; import java.util.LinkedList; import java.util.Queue; /** * @author Anirudh Sharma * <p> * In an N by N square grid, each cell is either empty (0) or blocked (1). * <p> * A clear path from top-left to bottom-right has length k if and only if it is composed * of cells C_1, C_2, ..., C_k such that: * <p> * Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different * and share an edge or corner) * - C_1 is at location (0, 0) (ie. has value grid[0][0]) * - C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1]) * - If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0). * <p> * Return the length of the shortest such clear path from top-left to bottom-right. * If such a path does not exist, return -1. * <p> * Note: * <p> * 1 <= grid.length == grid[0].length <= 100 * grid[r][c] is 0 or 1 */ public class Problem13_ShortestPathInBinaryMatrix { /** * @param grid 2-D binary matrix * @return shortest path */ public int shortestPathBinaryMatrix(int[][] grid) { // Rows and columns of the grid int rows = grid.length; int columns = grid[0].length; // Special case if (grid[0][0] == 1 || grid[rows - 1][columns - 1] == 1) { return -1; } // Directions int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, -1}, {-1, 1}, {-1, -1}, {1, 1}}; // Visited array which keeps track of all the cells // that have been visited boolean[][] visited = new boolean[rows][columns]; // Update the source position visited[0][0] = true; // Queue to store coordinates of the cells Queue<int[]> coordinates = new LinkedList<>(); // Add the first cell to the queue coordinates.add(new int[]{0, 0}); // Shortest distance int distance = 0; // Loop until the queue is empty while (!coordinates.isEmpty()) { // Get the size of the queue int size = coordinates.size(); // Loop for all the cells stored in the queue for (int i = 0; i < size; i++) { // Get the element from the front int[] current = coordinates.remove(); // Check if we have reached to the end of the grid if (current[0] == rows - 1 && current[1] == columns - 1) { return distance + 1; } // Otherwise check for the eight directions for (int j = 0; j < 8; j++) { // Next coordinates int nextX = directions[j][0] + current[0]; int nextY = directions[j][1] + current[1]; // Visit this cell if not already if (nextX >= 0 && nextX < rows && nextY >= 0 && nextY < columns && !visited[nextX][nextY] && grid[nextX][nextY] == 0) { coordinates.add(new int[]{nextX, nextY}); visited[nextX][nextY] = true; } } } distance++; } return -1; } }
37.988235
100
0.518117