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
aeabdd058cc7d9ff7558ac46ead9006cb8e32d6b
1,298
package org.swingeasy; import java.awt.Component; import javax.swing.JCheckBox; import javax.swing.JTree; import javax.swing.tree.TreeCellRenderer; /** * @author Jurgen */ public class ECheckBoxTreeNodeRenderer implements TreeCellRenderer { private JCheckBox delegate; public ECheckBoxTreeNodeRenderer() { this(new JCheckBox()); } public ECheckBoxTreeNodeRenderer(JCheckBox delegate) { super(); this.delegate = delegate; this.delegate.setOpaque(false); } /** * * @see javax.swing.tree.TreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int, * boolean) */ @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { @SuppressWarnings("rawtypes") ECheckBoxTreeNode node = ECheckBoxTreeNode.class.cast(value); delegate.setToolTipText(node.getTooltip()); delegate.setText(node.getStringValue()); delegate.setSelected(node.isSelected()); delegate.setEnabled(tree.isEnabled()); delegate.setComponentOrientation(tree.getComponentOrientation()); return delegate; } }
28.844444
143
0.694915
6bb24b8b436b458cb7cfc40d01d11f3a6aa71505
3,798
package com.angelo.blackpearl; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.JsonObjectRequest; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import org.json.JSONObject; import androidx.annotation.NonNull; import eu.amirs.JSON; public class QueryUtils { private static final PostDatabase postDatabase = PostDatabase.getInstance(MainActivity.context); public static final String githubReleasesUrl = "https://api.github.com/repos/YahiaAngelo/BlackPearl/releases/latest"; private QueryUtils() { } public static void extractPosts() { FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("hamza"); String post = "post"; myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (int i = 0; i < dataSnapshot.getChildrenCount(); i++) { String title = (String) dataSnapshot.child(post + i).child("title").getValue(); String desc = (String) dataSnapshot.child(post + i).child("desc").getValue(); String link = (String) dataSnapshot.child(post + i).child("link").getValue(); String imgLink = (String) dataSnapshot.child(post + i).child("img").getValue(); Post post = new Post(); post.setTitle(title); post.setDesc(desc); post.setLink(link); post.setImg(imgLink); post.setId(i); postDatabase.postDao().save(post); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } public static void getLatestRelease(Context context){ RequestQueue mRequestQueue; Cache cache = new DiskBasedCache(MainActivity.context.getCacheDir(), 1024 * 1024); // 1MB cap Network network = new BasicNetwork(new HurlStack()); mRequestQueue = new RequestQueue(cache, network); mRequestQueue.start(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, githubReleasesUrl, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { SharedPreferences sharedPreferences = context.getSharedPreferences("sharedPreferences",Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); JSON json = new JSON(response.toString()); String version = json.key("tag_name").stringValue(); editor.putString("latestRelease", version); editor.apply(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.v("LatestVersion", "Something went wrong"+ error); } }); mRequestQueue.add(jsonObjectRequest); } }
33.315789
150
0.654292
884464abd145abe7b3e144a78296ee96cb59d520
1,463
package com.faforever.gw.model; import com.yahoo.elide.annotation.Include; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.io.Serializable; import java.util.UUID; @Entity @Table(name="gw_battle_participant") @Setter @Include @NoArgsConstructor public class BattleParticipant implements Serializable{ private UUID id; private Battle battle; private GwCharacter character; private BattleRole role; private BattleParticipantResult result; public BattleParticipant(Battle battle, GwCharacter gwCharacter, BattleRole role) { this.battle = battle; this.character = gwCharacter; this.role = role; } @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") public UUID getId() { return id; } @ManyToOne @JoinColumn(name = "fk_battle") public Battle getBattle() { return battle; } @ManyToOne @JoinColumn(name = "fk_character") public GwCharacter getCharacter() { return character; } @Column(name = "role", length = 1) public BattleRole getRole() { return role; } @Column(name = "result", length = 1) public BattleParticipantResult getResult() { return result; } @Transient public Faction getFaction() { return character.getFaction(); } }
22.859375
87
0.678059
507d28bfa871932e19231ff5b0bd1384a4e9a176
2,644
package net.voxelindustry.brokkcolor; import java.util.Objects; import static java.lang.Integer.max; import static java.lang.Math.floor; import static java.lang.Math.min; public class Color32 { public static final Color32 ALPHA = of(-128, -128, -128, -128); private final byte red; private final byte green; private final byte blue; private final byte alpha; public Color32(byte red, byte green, byte blue, byte alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } public Color32 interpolate(Color32 other, float delta) { if (delta >= 1) return other; if (delta <= 0) return this; return new Color32((byte) (red + (other.red - red) * delta), (byte) (green + (other.green - green) * delta), (byte) (blue + (other.blue - blue) * delta), (byte) (alpha + (other.alpha - alpha) * delta)); } public Color32 addAlpha(int alpha) { return new Color32(red, green, blue, (byte) (this.alpha + alpha)); } public static Color32 of(int red, int green, int blue, int alpha) { return new Color32((byte) red, (byte) green, (byte) blue, (byte) alpha); } public static Color32 fromColor128(Color color) { return new Color32( (byte) max(-128, min(127, (int) floor(color.getRed() * 256.0) - 128)), (byte) max(-128, min(127, (int) floor(color.getGreen() * 256.0) - 128)), (byte) max(-128, min(127, (int) floor(color.getBlue() * 256.0) - 128)), (byte) max(-128, min(127, (int) floor(color.getAlpha() * 256.0) - 128)) ); } public byte red() { return red; } public byte green() { return green; } public byte blue() { return blue; } public byte alpha() { return alpha; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Color32 color32 = (Color32) o; return red == color32.red && green == color32.green && blue == color32.blue && alpha == color32.alpha; } @Override public int hashCode() { return Objects.hash(red, green, blue, alpha); } @Override public String toString() { return "Color32{" + "red=" + red + ", green=" + green + ", blue=" + blue + ", alpha=" + alpha + '}'; } }
25.180952
110
0.527988
f7d6bfd9c9963315183b6e5ac4d1769972a3754d
793
import leetcode.LeetCode004; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LeetCode004Test { public static void sample1() { var sl = new LeetCode004.Solution(); var bufferedReader = new BufferedReader(new InputStreamReader(System.in)); try { var line = bufferedReader.readLine(); var res = sl.longestPalindrome(line); System.out.println(res); }catch (IOException e) { e.printStackTrace(); }finally { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String... args) { sample1(); } }
24.78125
82
0.571248
0d248d63b321a0a24c31b901ad9d8d727cd1aada
432
package org.unidal.cat.core.document; import org.unidal.web.mvc.AbstractModule; import org.unidal.web.mvc.annotation.ModuleMeta; import org.unidal.web.mvc.annotation.ModulePagesMeta; @ModuleMeta(name = "doc", defaultInboundAction = "home", defaultTransition = "default", defaultErrorAction = "default") @ModulePagesMeta({ org.unidal.cat.core.document.page.Handler.class }) public class DocumentModule extends AbstractModule { }
28.8
119
0.796296
a72d97f0e1ad60d8d405459f718f39b6b239e1f5
380
package net.kwmt27.codesearch.model; /** * https://developer.github.com/v3/repos/#list-your-repositories */ public enum SortType { Created("created"), Updated("updated"), Pushed("pushed"), FullName("full_name"); private String type; SortType(String type) { this.type = type; } public String getType() { return type; } }
15.833333
64
0.610526
acd0536aad71d8890c119b695b72c3c58b606614
3,291
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.xray.entities; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; /** * An empty {@link Map} which does nothing, but unlike {@link Collections#emptyList()} won't throw * {@link UnsupportedOperationException}. */ // We don't actually use the type parameter so nullness annotations would be ignored anyways so no need to annotate. @SuppressWarnings("all") class NoOpList implements List<Object> { static <T> List<T> get() { return (List<T>) INSTANCE; } private static final NoOpList INSTANCE = new NoOpList(); private static final Object[] EMPTY_ARRAY = new Object[0]; @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(Object o) { return false; } @Override public Iterator<Object> iterator() { return Collections.emptyIterator(); } @Override public Object[] toArray() { return EMPTY_ARRAY; } @Override public <T> T[] toArray(T[] a) { return a; } @Override public boolean add(Object o) { return true; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<?> c) { return false; } @Override public boolean addAll(int index, Collection<?> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } @Override public Object get(int index) { return null; } @Override public Object set(int index, Object element) { return null; } @Override public void add(int index, Object element) { } @Override public Object remove(int index) { return null; } @Override public int indexOf(Object o) { return -1; } @Override public int lastIndexOf(Object o) { return -1; } @Override public ListIterator<Object> listIterator() { return Collections.emptyListIterator(); } @Override public ListIterator<Object> listIterator(int index) { return Collections.emptyListIterator(); } @Override public List<Object> subList(int fromIndex, int toIndex) { return NoOpList.get(); } }
21.37013
116
0.632331
c1d1ecaa0dd58f4118605813151f361691411e44
1,500
package se.mickelus.tetra.craftingeffect.condition; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.ToolAction; import javax.annotation.ParametersAreNonnullByDefault; import java.util.Map; @ParametersAreNonnullByDefault public class CraftTypeCondition implements CraftingEffectCondition { CraftType craft; @Override public boolean test(ResourceLocation[] unlocks, ItemStack upgradedStack, String slot, boolean isReplacing, Player player, ItemStack[] materials, Map<ToolAction, Integer> tools, Level world, BlockPos pos, BlockState blockState) { switch (craft) { case module: return isReplacing; case improvement: return !isReplacing && !isEnchantment(materials); case enchantment: return !isReplacing && isEnchantment(materials); case repair: } return false; } private boolean isEnchantment(ItemStack[] materials) { return materials.length == 1 && !materials[0].isEmpty() && Items.ENCHANTED_BOOK.equals(materials[0].getItem()); } enum CraftType { module, improvement, enchantment, repair } }
33.333333
125
0.702
8d3a4cbec42f759f73c2cd2eb371f8370cc8e655
664
package test.gov.nih.nci.cacoresdk.domain.manytomany; import junit.framework.Test; import junit.framework.TestSuite; import test.gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.M2MBidirectionalTest; import test.gov.nih.nci.cacoresdk.domain.manytomany.unidirectional.M2MUnidirectionalTest; public class Many2ManySuite { public static Test suite() { TestSuite suite = new TestSuite("Test for Many to Many package"); suite.addTest(new TestSuite(M2MBidirectionalTest.class,M2MBidirectionalTest.getTestCaseName())); suite.addTest(new TestSuite(M2MUnidirectionalTest.class,M2MUnidirectionalTest.getTestCaseName())); return suite; } }
36.888889
101
0.799699
3483668431e96ed73397e86513f5de63e3842b5a
1,201
package ru.i_novus.ms.rdm.n2o.api.constant; import java.util.Arrays; import java.util.List; public class DataRecordConstants { public static final String DATA_ACTION_CREATE = "create"; public static final String DATA_ACTION_UPDATE = "update"; private static final List<String> DATA_ACTIONS = Arrays.asList(DATA_ACTION_CREATE, DATA_ACTION_UPDATE); public static final String FIELD_SYSTEM_ID = "id"; public static final String FIELD_VERSION_ID = "versionId"; public static final String FIELD_OPT_LOCK_VALUE = "optLockValue"; public static final int DEFAULT_OPT_LOCK_VALUE = 0; public static final String FIELD_LOCALE_CODE = "localeCode"; public static final String DEFAULT_LOCALE_CODE = ""; public static final String FIELD_DATA_ACTION = "dataAction"; public static final String REFERENCE_QUERY_ID = "reference"; public static final String REFERENCE_VALUE = "value"; public static final String REFERENCE_DISPLAY_VALUE = "displayValue"; private DataRecordConstants() { // Nothing to do. } // NB: Workaround to sonar issue "squid-S2386". public static List<String> getDataActions() { return DATA_ACTIONS; } }
35.323529
107
0.740216
f8a232207a071244dea05db7cc77708ea6b6bfab
2,393
package de.l3s.eventkg.nlp; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.HashSet; import java.util.Set; import de.l3s.eventkg.meta.Language; import jep.JepException; import opennlp.tools.util.Span; public class OpenNLPOrBreakIteratorNLPUtils implements NLPUtils { NLPUtils nlpUtils; public static void main(String[] args) throws JepException, FileNotFoundException { System.out.println( "res = ''\nfor sentence in sentencesDe :\n\tfor token in sentence:\n\t\tline += token.word + '\t'\n\t\tline += token.space_after\n\t\tres += line + '\\n'"); Set<String> sentences = new HashSet<String>(); // sentences.add("Dies ist ein Satz. Und hier ist noch ein Satz."); // sentences.add("Morgen ist's Wochenende. Ich weiß, das ist gut."); // sentences.add("Pius II. ging nach Hause. Das war in Rom."); sentences.add( "Die Skulpturenmeile in Hannover ist ein zwischen 1986 und 2000 geschaffener Skulpturenweg entlang der Straßen Brühlstraße und Leibnizufer in Hannover. Er besteht aus übergroßen Skulpturen und Plastiken im öffentlichen Straßenraum. Die Kunstwerke sind auf einer Länge von etwa 1.200 Meter zwischen dem Königsworther Platz und dem Niedersächsischen Landtag aufgestellt. Die sehr unterschiedlichen Arbeiten befinden sich überwiegend auf der grünen Mittelinsel des sechsspurigen, stark befahrenen Straßenzuges."); OpenNLPOrBreakIteratorNLPUtils nlpUtils = new OpenNLPOrBreakIteratorNLPUtils(Language.DE); for (String sentence : sentences) { for (Span span : nlpUtils.sentenceSplitterPositions(sentence)) { System.out.println(span.getCoveredText(sentence)); System.out.println(" " + span.getStart() + ", " + span.getEnd()); } } } public OpenNLPOrBreakIteratorNLPUtils(Language language) throws FileNotFoundException { InputStream modelIn = OpenNLPutils.class .getResourceAsStream("/resource/lang/" + language.getLanguage().toLowerCase() + "-sent.bin"); if (modelIn != null) { // System.out.println("Init OpenNLP for " + language.getLanguage() + // "."); this.nlpUtils = new OpenNLPutils(language); } else { // System.out.println("Init BreakIterator for " + // language.getLanguage() + "."); this.nlpUtils = new BreakIteratorUtils(language); } } public Span[] sentenceSplitterPositions(String text) { return this.nlpUtils.sentenceSplitterPositions(text); } }
39.883333
515
0.744254
4c900a72ec0715b58db14617ba1e892aab5028b4
183
package com.codegym.task.task19.task1904; import java.io.IOException; public interface PersonScanner { Person read() throws IOException; void close() throws IOException; }
18.3
41
0.759563
bba611715cd024d7117a30e43b0985b8b2d3ff43
1,409
// // (C) Copyright 2015 Martin E. Nordberg III // Apache 2.0 License // package org.barlom.domain.metamodel.spi.commands; import javax.json.JsonObject; import java.util.UUID; /** * Service provide callback interface for completing a command after it has been persisted. */ @FunctionalInterface public interface IMetamodelCommandSpi<R extends IMetamodelCommandSpi.CmdRecord> { /** * Minimal record for the attributes used by a command. */ class CmdRecord { protected CmdRecord( JsonObject jsonCmdArgsObj ) { this.cmdId = UUID.fromString( jsonCmdArgsObj.getString( "cmdId" ) ); this.jsonCmdArgs = jsonCmdArgsObj.toString(); } /** * Tests whether a JSON attribute has a value. * * @param jsonCmdArgsObj the JSON object to check. * @param key the key to look for. * * @return true if there is a non-null value for the key. */ protected boolean hasNoValue( JsonObject jsonCmdArgsObj, String key ) { return !jsonCmdArgsObj.containsKey( key ) || jsonCmdArgsObj.isNull( key ); } public final UUID cmdId; public final String jsonCmdArgs; } /** * Write the command's changes into the metamodel repository. * * @param record the JSON for the command's changes. */ void finish( R record ); }
27.096154
91
0.633073
88623acf1557590dd6499ec7688b99af3cdac64a
1,261
/** * Copyright 2020 Webank. * * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.webank.blockchain.data.export.db.entity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import lombok.experimental.Accessors; import java.util.Date; /** * @author wesleywang * @Description: * @date 2020/10/26 */ @EqualsAndHashCode(callSuper = true) @Data @Accessors(chain = true) @ToString(callSuper = true) public class ContractInfo extends IdEntity { protected String abiHash; private String contractABI; private String contractBinary; private short version = 1; private String contractName; /** @Fields updatetime : depot update time */ protected Date depotUpdatetime = new Date(); }
26.829787
99
0.739096
81ef430c3849d0ac6c13eee838374f7f4293fd2f
2,383
/* * Fabric3 * Copyright (c) 2009-2015 Metaform Systems * * 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. * Portions originally based on Apache Tuscany 2007 * licensed under the Apache 2.0 license. */ package org.fabric3.util.graph; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Default implementation of a depth first search. */ public class DepthFirstTraverserImpl<T> implements DepthFirstTraverser<T> { public List<Vertex<T>> traverse(DirectedGraph<T> graph, Vertex<T> start) { return traverse(graph, start, new TrueVisitor<T>()); } public List<Vertex<T>> traversePath(DirectedGraph<T> graph, Vertex<T> start, Vertex<T> end) { TerminatingVisitor<T> visitor = new TerminatingVisitor<>(end); List<Vertex<T>> path = traverse(graph, start, visitor); if (visitor.wasFound()) { return path; } return Collections.emptyList(); } private List<Vertex<T>> traverse(DirectedGraph<T> graph, Vertex<T> start, Visitor<T> visitor) { List<Vertex<T>> visited = new ArrayList<>(); List<Vertex<T>> stack = new ArrayList<>(); Set<Vertex<T>> seen = new HashSet<>(visited); stack.add(start); seen.add(start); do { // mark as visited Vertex<T> next = stack.remove(stack.size() - 1); visited.add(next); if (!visitor.visit(next)) { return visited; } // add all non-visited adjacent vertices to the stack Set<Vertex<T>> adjacentVertices = graph.getAdjacentVertices(next); for (Vertex<T> v : adjacentVertices) { seen.add(v); stack.add(v); } } while (!stack.isEmpty()); return visited; } }
32.643836
99
0.637851
22810fe2562ec3fbdee22fa323b2d1ac15ac9134
2,204
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.sdk.component.studio.ui.composite.controller; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.talend.core.model.process.IElementParameter; import org.talend.core.ui.properties.tab.IDynamicProperty; import org.talend.designer.core.ui.editor.properties.controllers.TableController; import org.talend.designer.core.ui.editor.properties.macrowidgets.tableeditor.AbstractPropertiesTableEditorView; import org.talend.designer.core.ui.editor.properties.macrowidgets.tableeditor.PropertiesTableEditorModel; import org.talend.sdk.component.studio.metadata.tableeditor.TaCoKitPropertiesTableEditorView; /** * created by hcyi on Mar 16, 2021 * Detailled comment * */ public class TaCoKitTableController extends TableController { public TaCoKitTableController(IDynamicProperty dp) { super(dp); } @Override public Control createControl(final Composite parentComposite, final IElementParameter param, final int numInRow, final int nbInRow, int top, final Control lastControlPrm) { return super.createControl(parentComposite, param, numInRow, nbInRow, top, lastControlPrm); } @Override protected AbstractPropertiesTableEditorView getPropertiesTableEditorView(Composite parentComposite, int mainCompositeStyle, PropertiesTableEditorModel tableEditorModel, IElementParameter param, boolean toolbarVisible, boolean labelVisible) { return new TaCoKitPropertiesTableEditorView<Map<String, Object>>(parentComposite, SWT.NONE, tableEditorModel, !param.isBasedOnSchema(), false); } }
43.215686
129
0.725953
8d04525289fc6871d8e5a73c23df9e9914b8cee2
348
package com.yk.dao; import com.yk.entity.SiteSetting; import java.util.List; public interface SiteSettingMapper { List<SiteSetting> getSiteSettingData(); Integer updateById(SiteSetting siteSetting); Integer deleteByIds(Long[] deleteIds); Integer addSetting(SiteSetting siteSetting); List<SiteSetting> getFriendInfo(); }
18.315789
48
0.755747
de6d03c084201af27e837ea773c4fdcfde06e413
2,033
package com.iov42.solutions.core.sdk.utils; import com.iov42.solutions.core.sdk.CryptoBackend; import java.lang.reflect.Constructor; /** * Sets the {@link CryptoBackend} to be used within the iov42 core library. * This class provides static access to an instance of {@link CryptoBackend} for convenience. * <p> * To specify a custom {@link CryptoBackend} you must specify either a fully qualified classname * to a concrete implementation of {@link CryptoBackend} or you can set it later with {@link #setBackend(CryptoBackend)}. */ public class CryptoBackendHolder { public static final String SYSTEM_PROPERTY = "iov42.core.sdk.crypto-backend"; private static String backendName = System.getProperty(SYSTEM_PROPERTY); private static CryptoBackend backend; static { initialize(); } private static void initialize() { if (StringUtils.isEmpty(backendName)) { // instantiate default backend backend = new DefaultCryptoBackend(); } else { // try to instantiate custom backend try { Class<?> clazz = Class.forName(backendName); Constructor<?> backendConstructor = clazz.getConstructor(); backend = (CryptoBackend) backendConstructor.newInstance(); } catch (Exception ex) { throw new RuntimeException("Could not instantiate custom CryptoBackend.", ex); } } } /** * Returns an instance of {@link CryptoBackend} used by the iov42 core library. * * @return an instance of {@link CryptoBackend} used by the iov42 core library */ public static CryptoBackend getBackend() { return backend; } /** * Sets an instance of {@link CryptoBackend} used by the iov42 core library. * * @param backend instance of {@link CryptoBackend} used by the iov42 core library */ public static void setBackend(CryptoBackend backend) { CryptoBackendHolder.backend = backend; } }
35.051724
121
0.662076
1c44b4403a2e5572aa6fd16b581628493569bb22
3,888
package com.diozero.remote.server.websocket; /*- * #%L * Organisation: mattjlewis * Project: Device I/O Zero - Remote Server * Filename: MessageWrapperTypes.java * * This file is part of the diozero project. More information about this project * can be found at http://www.diozero.com/ * %% * Copyright (C) 2016 - 2017 mattjlewis * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ public interface MessageWrapperTypes { static final String RESPONSE = "Response"; // GPIO Requests static final String PROVISION_DIGITAL_INPUT_DEVICE = "ProvisionDigitalInputDevice"; static final String PROVISION_DIGITAL_OUTPUT_DEVICE = "ProvisionDigitalOutputDevice"; static final String PROVISION_DIGITAL_INPUT_OUTPUT_DEVICE = "ProvisionDigitalInputOutputDevice"; static final String PROVISION_PWM_OUTPUT_DEVICE = "ProvisionPwmOutputDevice"; static final String PROVISION_ANALOG_INPUT_DEVICE = "ProvisionAnalogInputDevice"; static final String PROVISION_ANALOG_OUTPUT_DEVICE = "ProvisionAnalogOutputDevice"; static final String GPIO_DIGITAL_READ = "GpioDigitalRead"; static final String GPIO_DIGITAL_WRITE = "GpioDigitalWrite"; static final String GPIO_PWM_READ = "GpioPwmRead"; static final String GPIO_PWM_WRITE = "GpioPwmWrite"; static final String GPIO_ANALOG_READ = "GpioAnalogRead"; static final String GPIO_ANALOG_WRITE = "GpioAnalogWrite"; static final String GPIO_EVENTS = "GpioEvents"; static final String GPIO_CLOSE = "GpioClose"; // GPIO Responses static final String GPIO_DIGITAL_READ_RESPONSE = "GpioDigitalReadResponse"; static final String GPIO_PWM_READ_RESPONSE = "GpioPwmReadResponse"; static final String GPIO_ANALOG_READ_RESPONSE = "GpioAnalogReadResponse"; static final String DIGITAL_INPUT_EVENT = "DigitalInputEvent"; // I2C Requests static final String I2C_OPEN = "I2COpen"; static final String I2C_READ_BYTE = "I2CReadByte"; static final String I2C_WRITE_BYTE = "I2CWriteByte"; static final String I2C_READ = "I2CRead"; static final String I2C_WRITE = "I2CWrite"; static final String I2C_READ_BYTE_DATA = "I2CReadByteData"; static final String I2C_WRITE_BYTE_DATA = "I2CWriteByteData"; static final String I2C_READ_I2C_BLOCK_DATA = "I2CReadI2CBlockData"; static final String I2C_WRITE_I2C_BLOCK_DATA = "I2CWriteI2CBlockData"; static final String I2C_CLOSE = "I2CClose"; // I2C Responses static final String I2C_READ_BYTE_RESPONSE = "I2CReadByteResponse"; static final String I2C_READ_RESPONSE = "I2CReadResponse"; // SPI Requests static final String SPI_OPEN = "SpiOpen"; static final String SPI_WRITE = "SpiWrite"; static final String SPI_WRITE_AND_READ = "SpiWriteAndRead"; static final String SPI_CLOSE = "SpiClose"; // SPI Responses static final String SPI_RESPONSE = "SpiResponse"; }
48
98
0.769033
5e71c6fa66980cbd0c6d75c4cc52206a0d03ac63
4,953
/* * Copyright (c) 2008, Ueda Laboratory LMNtal Group <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the Ueda Laboratory LMNtal Group nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package lavit.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; @SuppressWarnings("serial") public class PathInputField extends JComponent { private JTextField textInput; private JButton buttonBrowse; private JFileChooser fileChooser; private boolean enabled; private boolean readOnly; public PathInputField(JFileChooser fileChooser, String buttonCaption, int columns) { this.fileChooser = fileChooser; GroupLayout gl = new GroupLayout(this); setLayout(gl); textInput = new JTextField(columns); add(textInput); buttonBrowse = new JButton(buttonCaption); buttonBrowse.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { browse(); } }); add(buttonBrowse); gl.setHorizontalGroup(gl.createSequentialGroup() .addComponent(textInput) .addComponent(buttonBrowse) ); gl.setVerticalGroup(gl.createParallelGroup(Alignment.BASELINE) .addComponent(textInput) .addComponent(buttonBrowse) ); setEnabled(true); setReadOnly(false); } public int getBaseline(int width, int height) { return textInput.getBaseline(width, height); } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; updateState(); } public boolean isReadOnly() { return readOnly; } public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; updateState(); } public String getPathText() { return textInput.getText(); } public void setPathText(String s) { textInput.setText(s); } public void addChangeListener(final ChangeListener l) { textInput.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { l.stateChanged(new ChangeEvent(textInput)); } @Override public void insertUpdate(DocumentEvent e) { l.stateChanged(new ChangeEvent(textInput)); } @Override public void changedUpdate(DocumentEvent e) { } }); } private void updateState() { textInput.setEnabled(enabled); textInput.setEditable(!readOnly); buttonBrowse.setEnabled(enabled && !readOnly); } private void browse() { initCurrentDirectory(); int ret = fileChooser.showOpenDialog(this); if (ret == JFileChooser.APPROVE_OPTION) { approved(); } } private void approved() { textInput.setText(fileChooser.getSelectedFile().getAbsolutePath()); } private void initCurrentDirectory() { File file = new File(getPathText()).getAbsoluteFile(); while (!file.exists() && file.getParentFile() != null) { file = file.getParentFile(); } File dir = null; if (file.exists()) { dir = file.getParentFile(); } if (dir == null) { dir = new File("").getAbsoluteFile(); } fileChooser.setCurrentDirectory(dir); } }
24.765
85
0.727842
cfa3533e1c45b6e4b5ffea9cd069bfac8862e16f
9,584
package me.varunon9.saathmetravel.ui.chat; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import com.google.firebase.firestore.DocumentChange; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.ListenerRegistration; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import me.varunon9.saathmetravel.ChatFragmentActivity; import me.varunon9.saathmetravel.R; import me.varunon9.saathmetravel.adapters.ChatMessageListRecyclerViewAdapter; import me.varunon9.saathmetravel.constants.AppConstants; import me.varunon9.saathmetravel.models.Chat; import me.varunon9.saathmetravel.models.Message; import me.varunon9.saathmetravel.models.User; import me.varunon9.saathmetravel.utils.FirestoreDbOperationCallback; public class ChatFragment extends Fragment { private ChatViewModel chatViewModel; private ChatFragmentActivity chatFragmentActivity; private ChatMessageListRecyclerViewAdapter chatMessageListRecyclerViewAdapter; private Button chatBoxSendButton; private EditText chatBoxEditText; private String conversationUrl; private String TAG = "ChatFragment"; private Chat currentChat; private List<Message> messageList = new ArrayList<>(); private ListenerRegistration listenerRegistration; private RecyclerView chatMessageListRecyclerView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.chat_fragment, container, false); chatFragmentActivity = (ChatFragmentActivity) getActivity(); chatMessageListRecyclerView = rootView.findViewById(R.id.chatMessageListRecyclerView); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(rootView.getContext()); linearLayoutManager.setStackFromEnd(true); chatMessageListRecyclerView.setLayoutManager(linearLayoutManager); chatMessageListRecyclerViewAdapter = new ChatMessageListRecyclerViewAdapter( messageList, chatFragmentActivity.chatInitiatorUid, chatFragmentActivity ); chatMessageListRecyclerView.setAdapter(chatMessageListRecyclerViewAdapter); chatBoxSendButton = rootView.findViewById(R.id.chatBoxSendButton); chatBoxEditText = rootView.findViewById(R.id.chatBoxEditText); chatBoxSendButton.setOnClickListener((view) -> { sendMessage(); }); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); chatViewModel = ViewModelProviders.of(getActivity()).get(ChatViewModel.class); chatViewModel.getSelectedChat().observe(this, chat -> { currentChat = chat; if (chat.getInitiatorUid().equals(chatFragmentActivity.chatInitiatorUid)) { getRecipientProfileFromFirestore(chat.getRecipientUid()); } else { getRecipientProfileFromFirestore(chat.getInitiatorUid()); } conversationUrl = AppConstants.Collections.CHAT_MESSAGES + "/" + chat.getId() + "/messages"; getChatMessages(conversationUrl); }); } private void getRecipientProfileFromFirestore(String recipientUid) { chatFragmentActivity.showProgressDialog("Fetching Recipient info", "Please wait", false); chatFragmentActivity.firestoreDbUtility.getOne(AppConstants.Collections.USERS, recipientUid, new FirestoreDbOperationCallback() { @Override public void onSuccess(Object object) { DocumentSnapshot documentSnapshot = (DocumentSnapshot) object; User recipientUser = documentSnapshot.toObject(User.class); chatFragmentActivity.dismissProgressDialog(); updateLastSeen(recipientUser); } @Override public void onFailure(Object object) { chatFragmentActivity.dismissProgressDialog(); chatFragmentActivity.showMessage("Failed to fetch recipient info"); } }); } private void updateLastSeen(User recipientUser) { if (recipientUser == null) { // deleted from firestore db? return; } // update online or last seen String title = recipientUser.getName(); if (title == null) { title = recipientUser.getEmail(); } if (title == null) { title = recipientUser.getMobile(); } String subtitle = "last seen at "; if (recipientUser.isOnline()) { subtitle = "online"; } else { subtitle += chatFragmentActivity.generalUtility .convertDateToChatDateFormat(recipientUser.getLastSeen()); } chatFragmentActivity.updateActionBarTitle(title, subtitle); } // send message as update lastMessage private void sendMessage() { String message = chatBoxEditText.getText().toString(); if (message != null) { chatBoxEditText.setText(""); Message messageToBeSent = new Message(); messageToBeSent.setMessage(message); messageToBeSent.setInitiatorUid(chatFragmentActivity.chatInitiatorUid); if (chatFragmentActivity.chatInitiatorUid.equals(currentChat.getInitiatorUid())) { messageToBeSent.setRecipientUid(currentChat.getRecipientUid()); } else { messageToBeSent.setRecipientUid(currentChat.getInitiatorUid()); } String documentName = chatFragmentActivity.generalUtility .getUniqueDocumentId(chatFragmentActivity.chatInitiatorUid); chatFragmentActivity.firestoreDbUtility.createOrMerge(conversationUrl, documentName, messageToBeSent, new FirestoreDbOperationCallback() { @Override public void onSuccess(Object object) { Log.i(TAG, message + " sent"); } @Override public void onFailure(Object object) { Log.e(TAG, "message '" + message + "' not sent"); } }); // silently update lastMessage Map<String, Object> hashMap = new HashMap<>(); hashMap.put("lastMessage", message); chatFragmentActivity.firestoreDbUtility.update(AppConstants.Collections.CHATS, currentChat.getId(), hashMap, new FirestoreDbOperationCallback() { @Override public void onSuccess(Object object) { Log.i(TAG, message + " lastMessage updated"); } @Override public void onFailure(Object object) { Log.e(TAG, "message '" + message + "' lastMessage not updated"); } }); } } private void getChatMessages(String conversationUrl) { // getting last 200 messages Query query = chatFragmentActivity.firestoreDbUtility.getDb().collection(conversationUrl) .orderBy("createdAt", Query.Direction.ASCENDING) .limit(200); listenerRegistration = query.addSnapshotListener( (queryDocumentSnapshots, e) -> { if (e != null) { Log.w(TAG, "listen:error", e); return; } for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) { switch (dc.getType()) { case ADDED: { Message message = dc.getDocument().toObject(Message.class); Log.d(TAG, "New message: " + message.getMessage()); messageList.add(message); chatMessageListRecyclerViewAdapter.notifyDataSetChanged(); chatMessageListRecyclerView.scrollToPosition(messageList.size() - 1); break; } } } } ); } @Override public void onDestroy() { super.onDestroy(); if (listenerRegistration != null) { listenerRegistration.remove(); } } }
41.851528
101
0.621244
b8e30a941850a098ae1aa45a42ef69907e319d4d
4,354
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import com.sun.j3d.utils.geometry.*; import com.sun.j3d.utils.universe.*; import com.sun.j3d.utils.image.*; import javax.media.j3d.*; import javax.vecmath.*; public class Tamagochi extends JFrame implements LeeRed { static String preguntas []= { "COMO TE LLAMAS","DONDE VIVES"}; static String respuestas []= {"MI NOMBRE ES TAMAGOCHI","EN LA COMPU"}; private Canvas3D canvas3D; private Appearance ap; private static Texture texture; private JPanel jp1, jp2; private JButton benfermo, bfeliz, blisto, bserio, bsonrisa; private EventHandler eh; private String nombres[][] = { {"bob-esponja.jpg", "bobEnf.jpg", "listo.jpg", "serio.jpg", "sonrisa.jpg"}, }; private int turno; //private Body body; private Red r; Body b; BodyZoey bz; BodyBob bb; Movible movi; Esfera e; int avatar=0; public Tamagochi(){ super("Tamagochi 3D"); turno=0; //setResizable(false); setSize(600, 500); GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); canvas3D = new Canvas3D(config); canvas3D.setSize(300, 400); eh = new EventHandler(); bfeliz=new JButton("Feliz"); benfermo=new JButton("Enfermo"); blisto=new JButton("Listo"); bsonrisa=new JButton("Sonrisa"); bserio=new JButton("Serio"); benfermo.addActionListener(eh); blisto.addActionListener(eh); bsonrisa.addActionListener(eh); bserio.addActionListener(eh); bfeliz.addActionListener(eh); jp1=new JPanel(); jp1.add(bfeliz); jp1.add(benfermo); jp1.add(blisto); jp1.add(bsonrisa); jp1.add(bserio); add("North", jp1); add("Center",canvas3D); setup3DGraphics(); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setVisible(true); r=new Red(this); } void setup3DGraphics(){ BranchGroup group=null; DirectionalLight light1; SimpleUniverse universe = new SimpleUniverse(canvas3D); universe.getViewingPlatform().setNominalViewingTransform(); if(avatar== 0){ movi=new Esfera(this); movi.changeTextureCab(texture, "Arizona.jpg"); group = movi.myBody(); } if(avatar== 1){ movi=new Esfera(this); movi.changeTextureCab(texture, "carafeliz.jpg"); group = movi.myBody(); } if(avatar== 2){ movi=new Body(-0.4f,0.0f,0.0f,"",true, this, "Avatar1"); movi.changeTextureCab(texture, "carafeliz.jpg"); group = movi.myBody(); } if(avatar== 3){ movi=new BodyBob(-0.4f,0.0f,0.0f,"",true, this, "bob-esponja.jpg"); group = movi.myBody(); } if(avatar== 4){ movi=new BodyZoey(-0.4f,0.0f,0.0f,"",true, this, "cabeza.png"); group = movi.myBody(); } if(avatar== 5){ movi=new Stan(-0.4f,0.0f,0.0f,"",true, this, "Avatar1", null); group= movi.myBody(); } BoundingSphere bounds =new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); Background fondo=new Background(); fondo.setColor(1.0f,1.0f,1.0f); fondo.setApplicationBounds(bounds); group.addChild(fondo); //SE DA LUZ A TODO EL ESCENARIO AmbientLight luz= new AmbientLight(); luz.setInfluencingBounds(bounds); group.addChild(luz); universe.addBranchGraph(group); } public static void main(String[] args) { new Tamagochi(); } class EventHandler implements ActionListener { public void actionPerformed(ActionEvent e1) { Object obj=e1.getSource(); if(obj instanceof JButton){ JButton btn=(JButton)e1.getSource(); if(btn==bfeliz){ turno=0; } if(btn==benfermo){turno=1;} if(btn==blisto){turno=2;} if(btn==bserio){turno=3;} if(btn==bsonrisa){turno=4;} } movi.changeTextureCab(texture, nombres[avatar][turno]); r.escribeRed(new Icono("Tamagochi", turno)); } } public void leeRed(Object obj){ if(obj instanceof Icono){ Icono i=(Icono)obj; int turno=i.getTurno(); System.out.println("Recibi"+i.getTurno()); movi.changeTextureCab(texture, nombres[avatar][turno]); } if(obj instanceof Mensaje){ System.out.println("Recibi "+(Mensaje)obj); } } static String findMatch(String str) { String result = ""; for(int i = 0; i < preguntas.length; ++i) { if(preguntas[i].equalsIgnoreCase(str)) { result = respuestas[i]; break; } } return result; } }
29.619048
80
0.658934
70b4cea882ce36d03c542ac700108eebaa0ed501
1,588
package top.lingkang.sessioncore.base.impl; import org.springframework.data.redis.core.RedisTemplate; import top.lingkang.sessioncore.base.FinalRepository; import top.lingkang.sessioncore.config.FinalSessionProperties; import top.lingkang.sessioncore.wrapper.FinalSession; import javax.servlet.http.HttpServletRequest; import java.util.concurrent.TimeUnit; /** * @author lingkang * Created by 2022/1/26 */ public class FinalRedisRepository implements FinalRepository { private RedisTemplate redisTemplate; private FinalSessionProperties properties; public FinalRedisRepository(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public RedisTemplate getRedisTemplate() { return redisTemplate; } public void setRedisTemplate(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } @Override public void deleteSession(String id, HttpServletRequest request) { redisTemplate.delete(id); } @Override public FinalSession getSession(String id) { Object o = redisTemplate.opsForValue().get(id); if (o != null) return (FinalSession) o; return null; } @Override public void setSession(String id, FinalSession session) { redisTemplate.opsForValue().set(id, session, properties.getMaxValidTime(), TimeUnit.MILLISECONDS); } @Override public void setFinalSessionProperties(FinalSessionProperties properties) { this.properties = properties; } @Override public void destroy() { } }
26.466667
106
0.721662
2a88b701d20f44a4339ef244c9656b3f79983ad8
738
package com.example.solid.ocp.negative; import org.junit.Before; import org.junit.Test; /** * Created by sbiliaiev on 09/02/2019. */ public class MoneyTransferTest { private MoneyTransfer transfer; @Before public void setup() { transfer = new MoneyTransfer(); } @Test public void wireTest() { transfer.setType(MoneyTransferType.WIRE); System.out.println(transfer.send()); } @Test public void payPalTest() { transfer.setType(MoneyTransferType.PAYPAL); System.out.println(transfer.send()); } @Test public void multChecksTest() { transfer.setType(MoneyTransferType.MULTIPLE_CHECKS); System.out.println(transfer.send()); } }
20.5
60
0.649051
46eb14aebda10166844bd4474ab59d2295dd08fb
3,651
/** * Copyright 2017-2019 The GreyCat Authors. All rights reserved. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package greycat.internal.task; import greycat.Callback; import greycat.Constants; import greycat.plugin.SchedulerAffinity; import greycat.Task; import greycat.TaskContext; import greycat.TaskResult; import greycat.struct.Buffer; import java.util.Map; class CF_PipeTo extends CF_Action { private final Task _subTask; private final String[] _targets; CF_PipeTo(final Task p_subTask, final String... p_targets) { super(); if (p_subTask == null) { throw new RuntimeException("subTask should not be null"); } _subTask = p_subTask; _targets = p_targets; } @Override public void eval(final TaskContext ctx) { final TaskResult previous = ctx.result(); _subTask.executeFrom(ctx, previous, SchedulerAffinity.SAME_THREAD, new Callback<TaskResult>() { @Override public void on(TaskResult result) { Exception exceptionDuringTask = null; if (result != null) { if (result.output() != null) { ctx.append(result.output()); } if (result.exception() != null) { exceptionDuringTask = result.exception(); } if (_targets != null && _targets.length > 0) { for (int i = 0; i < _targets.length; i++) { ctx.setVariable(_targets[i], result); } } else { result.free(); } } if (exceptionDuringTask != null) { ctx.endTask(previous, exceptionDuringTask); } else { ctx.continueWith(previous); } } }); } @Override public Task[] children() { Task[] children_tasks = new Task[1]; children_tasks[0] = _subTask; return children_tasks; } @Override public void cf_serialize(final Buffer builder, Map<Integer, Integer> dagIDS) { builder.writeString(CoreActionNames.PIPE_TO); builder.writeChar(Constants.TASK_PARAM_OPEN); final CoreTask castedAction = (CoreTask) _subTask; final int castedActionHash = castedAction.hashCode(); if (dagIDS == null || !dagIDS.containsKey(castedActionHash)) { builder.writeChar(Constants.SUB_TASK_OPEN); castedAction.serialize(builder, dagIDS); builder.writeChar(Constants.SUB_TASK_CLOSE); } else { builder.writeString("" + dagIDS.get(castedActionHash)); } if (_targets != null && _targets.length > 0) { builder.writeChar(Constants.TASK_PARAM_SEP); TaskHelper.serializeStringParams(_targets, builder); } builder.writeChar(Constants.TASK_PARAM_CLOSE); } @Override public final String name() { return CoreActionNames.PIPE_TO; } }
34.443396
103
0.592988
8e8a55c506e7569b8509718d9718eb81bf456e04
1,556
package com.yyu.fwk.formula.expression.calculate; import junit.framework.Assert; import org.junit.Ignore; import org.junit.Test; import com.yyu.fwk.formula.expression.OperatorTestBase; import com.yyu.fwk.formula.stackversion.OperatorEnum; import com.yyu.fwk.formula.stackversion.expression.Expression; import com.yyu.fwk.formula.stackversion.expression.calculate.Divide; import com.yyu.fwk.formula.stackversion.expression.variable.Literal; public class DivideTest extends OperatorTestBase { @Override public Expression getSymbol(Expression left, Expression right){ return new Divide(left, right); } @Test public void testDivideOperator(){ String leftStr = "10"; String rightStr = "4"; Expression left = new Literal(leftStr); Expression right = new Literal(rightStr); Divide divide = new Divide(left, right); Assert.assertEquals(OperatorEnum.DIVIDE, divide.getOperator()); } @Test public void testDivideSuccess(){ String leftStr = "10"; String rightStr = "4"; String expected = "2.50"; executeOperatorSuccess(leftStr, rightStr, expected); } @Test public void testDivideFailWithNonNumLeft(){ String leftStr = "aa"; String rightStr = "2.20"; String expected = "Cannot convert left variable [aa] to double."; executeOperatorFail(leftStr, rightStr, expected); } @Test public void testDivideFailWithNonNumRight(){ String leftStr = "1.10"; String rightStr = "aa"; String expected = "Cannot convert right variable [aa] to double."; executeOperatorFail(leftStr, rightStr, expected); } }
26.372881
68
0.749357
f68833dee22ff327df2a098a5707afeace8f7c2f
7,514
package seedu.address.model.occasion; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandOccasionTestUtil.VALID_OCCASIONLOCATION_TWO; import static seedu.address.logic.commands.CommandOccasionTestUtil.VALID_TAG_SLEEP; import static seedu.address.testutil.TypicalOccasions.OCCASION_ONE; import static seedu.address.testutil.TypicalOccasions.OCCASION_TWO; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.model.occasion.exceptions.DuplicateOccasionException; import seedu.address.model.occasion.exceptions.OccasionNotFoundException; import seedu.address.testutil.OccasionBuilder; public class UniqueOccasionListTest { @Rule public ExpectedException thrown = ExpectedException.none(); private final UniqueOccasionList uniqueOccasionList = new UniqueOccasionList(new ArrayList<>()); @Test public void contains_nullOccasion_throwsNullPointerException() { thrown.expect(NullPointerException.class); uniqueOccasionList.contains(null); } @Test public void contains_occasionNotInList_returnsFalse() { assertFalse(uniqueOccasionList.contains(OCCASION_ONE)); } @Test public void contains_occasionInList_returnsTrue() { uniqueOccasionList.add(OCCASION_ONE); assertTrue(uniqueOccasionList.contains(OCCASION_ONE)); } @Test public void contains_occasionWithSameIdentityFieldsInList_returnsTrue() { uniqueOccasionList.add(OCCASION_ONE); Occasion editedOccasionOne = new OccasionBuilder(OCCASION_ONE).withOccasionLocation(VALID_OCCASIONLOCATION_TWO) .withTags(VALID_TAG_SLEEP) .build(); assertTrue(uniqueOccasionList.contains(editedOccasionOne)); } @Test public void add_nullOccasion_throwsNullPointerException() { thrown.expect(NullPointerException.class); uniqueOccasionList.add(null); } @Test public void add_duplicateOccasion_throwsDuplicateOccasionException() { uniqueOccasionList.add(OCCASION_ONE); thrown.expect(DuplicateOccasionException.class); uniqueOccasionList.add(OCCASION_ONE); } @Test public void setOccasion_nullTargetOccasion_throwsNullPointerException() { thrown.expect(NullPointerException.class); uniqueOccasionList.setOccasion(null, OCCASION_ONE); } @Test public void setOccasion_nullEditedOccasion_throwsNullPointerException() { thrown.expect(NullPointerException.class); uniqueOccasionList.setOccasion(OCCASION_ONE, null); } @Test public void setOccasion_targetOccasionNotInList_throwsOccasionNotFoundException() { thrown.expect(OccasionNotFoundException.class); uniqueOccasionList.setOccasion(OCCASION_ONE, OCCASION_ONE); } @Test public void setOccasion_editedOccasionIsSameOccasion_success() { uniqueOccasionList.add(OCCASION_ONE); uniqueOccasionList.setOccasion(OCCASION_ONE, OCCASION_ONE); UniqueOccasionList expectedUniqueOccasionList = new UniqueOccasionList(new ArrayList<>()); expectedUniqueOccasionList.add(OCCASION_ONE); assertEquals(expectedUniqueOccasionList, uniqueOccasionList); } @Test public void setOccasion_editedOccasionHasSameIdentity_success() { uniqueOccasionList.add(OCCASION_ONE); Occasion editedOccasionOne = new OccasionBuilder(OCCASION_ONE).withOccasionLocation(VALID_OCCASIONLOCATION_TWO) .withTags(VALID_TAG_SLEEP) .build(); uniqueOccasionList.setOccasion(OCCASION_ONE, editedOccasionOne); UniqueOccasionList expectedUniqueOccasionList = new UniqueOccasionList(new ArrayList<>()); expectedUniqueOccasionList.add(editedOccasionOne); assertEquals(expectedUniqueOccasionList, uniqueOccasionList); } @Test public void setOccasion_editedOccasionHasDifferentIdentity_success() { uniqueOccasionList.add(OCCASION_ONE); uniqueOccasionList.setOccasion(OCCASION_ONE, OCCASION_TWO); UniqueOccasionList expectedUniqueOccasionList = new UniqueOccasionList(new ArrayList<>()); expectedUniqueOccasionList.add(OCCASION_TWO); assertEquals(expectedUniqueOccasionList, uniqueOccasionList); } @Test public void setOccasion_editedOccasionHasNonUniqueIdentity_throwsDuplicateOccasionException() { uniqueOccasionList.add(OCCASION_ONE); uniqueOccasionList.add(OCCASION_TWO); thrown.expect(DuplicateOccasionException.class); uniqueOccasionList.setOccasion(OCCASION_ONE, OCCASION_TWO); } @Test public void remove_nullOccasion_throwsNullPointerException() { thrown.expect(NullPointerException.class); uniqueOccasionList.remove(null); } @Test public void remove_occasionDoesNotExist_throwsOccasionNotFoundException() { thrown.expect(OccasionNotFoundException.class); uniqueOccasionList.remove(OCCASION_ONE); } @Test public void remove_existingOccasion_removesOccasion() { uniqueOccasionList.add(OCCASION_ONE); uniqueOccasionList.remove(OCCASION_ONE); UniqueOccasionList expectedUniqueOccasionList = new UniqueOccasionList(new ArrayList<>()); assertEquals(expectedUniqueOccasionList, uniqueOccasionList); } @Test public void setOccasions_nullUniqueOccasionList_throwsNullPointerException() { thrown.expect(NullPointerException.class); uniqueOccasionList.setOccasions((UniqueOccasionList) null); } @Test public void setOccasions_uniqueOccasionList_replacesOwnListWithProvidedUniqueOccasionList() { uniqueOccasionList.add(OCCASION_ONE); UniqueOccasionList expectedUniqueOccasionList = new UniqueOccasionList(new ArrayList<>()); expectedUniqueOccasionList.add(OCCASION_TWO); uniqueOccasionList.setOccasions(expectedUniqueOccasionList); assertEquals(expectedUniqueOccasionList, uniqueOccasionList); } @Test public void setOccasions_nullList_throwsNullPointerException() { thrown.expect(NullPointerException.class); uniqueOccasionList.setOccasions((List<Occasion>) null); } @Test public void setOccasions_list_replacesOwnListWithProvidedList() { uniqueOccasionList.add(OCCASION_ONE); List<Occasion> occasionList = Collections.singletonList(OCCASION_TWO); uniqueOccasionList.setOccasions(occasionList); UniqueOccasionList expectedUniqueOccasionList = new UniqueOccasionList(new ArrayList<>()); expectedUniqueOccasionList.add(OCCASION_TWO); assertEquals(expectedUniqueOccasionList, uniqueOccasionList); } @Test public void setOccasions_listWithDuplicateOccasions_throwsDuplicateOccasionException() { List<Occasion> listWithDuplicateOccasions = Arrays.asList(OCCASION_ONE, OCCASION_ONE); thrown.expect(DuplicateOccasionException.class); uniqueOccasionList.setOccasions(listWithDuplicateOccasions); } @Test public void asUnmodifiableObservableList_modifyList_throwsUnsupportedOperationException() { thrown.expect(UnsupportedOperationException.class); uniqueOccasionList.asUnmodifiableObservableList().remove(0); } }
39.547368
119
0.762577
dbbd87a5cd3a9961396ac1f1041f39d5ea978dc2
1,882
import java.util.Scanner; public class Question92{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); String input = sc.nextLine(); // Write code below... String num1=""; String num2=""; char op='a'; int equal=0; int flag=0; int j=0; int check=0; int ch=0; char[] charArray = input.toCharArray(); char[] numarray=new char[input.length()]; for(int i=0;i<input.length();i++){ if(charArray[i]<'a' || charArray[i]>'p'){ check=1; break; } if(charArray[i]=='c') ch=1; char out=gui_map(charArray[i]); numarray[i]=out; if(out=='+' || out=='-' || out=='X' || out=='/'){ flag=1; op=out; } if (flag==0){ num1=num1+String.valueOf(out); } else{ if(j==0){ j++; continue; } if (out=='='){ equal=1; break; } num2=num2+String.valueOf(out); } } if(ch==1 && check==0){ double a = Double.parseDouble(num1); double b=Double.parseDouble(num2); if(op=='+') System.out.print(a+b); else if(op=='-') System.out.print(a-b); else if(op=='X') System.out.print(a*b); else if(op=='/') System.out.print(a/b); } }// The main() method ends here. }// The main() method ends here. // A method that takes a character as input and returns the corresponding GUI character static char gui_map(char in){ char out = 'N';// N = Null/Empty char gm[][]={{'a','.'} ,{'b','0'} ,{'c','='} ,{'d','+'} ,{'e','1'} ,{'f','2'} ,{'g','3'} ,{'h','-'} ,{'i','4'} ,{'j','5'} ,{'k','6'} ,{'l','X'} ,{'m','7'} ,{'n','8'} ,{'o','9'} ,{'p','/'}}; // Checking for maps for(int i=0; i<gm.length; i++){ if(gm[i][0]==in){ out=gm[i][1]; break; } } return out; } }
19.402062
89
0.471307
40fefa12678975ed9c0a0bb4952a18a17813647c
5,404
package de.gerrygames.the5zig.clientviaversion.protocols.protocol1_8to1_7_6_10.chunks; import io.netty.buffer.ByteBuf; import us.myles.ViaVersion.api.PacketWrapper; import us.myles.ViaVersion.api.type.Type; import us.myles.ViaVersion.api.type.types.CustomByteType; import java.io.IOException; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.List; import java.util.zip.DataFormatException; import java.util.zip.Inflater; public class ChunkPacketTransformer { public static void transformChunk(PacketWrapper packetWrapper) throws Exception { int chunkX = packetWrapper.read(Type.INT); int chunkZ = packetWrapper.read(Type.INT); boolean groundUp = packetWrapper.read(Type.BOOLEAN); int primaryBitMask = packetWrapper.read(Type.SHORT); int addBitMask = packetWrapper.read(Type.SHORT); int compressedSize = packetWrapper.read(Type.INT); CustomByteType customByteType = new CustomByteType(compressedSize); byte[] data = packetWrapper.read(customByteType); int k = 0; int l = 0; for(int j = 0; j < 16; ++j) { k += primaryBitMask >> j & 1; l += addBitMask >> j & 1; } int uncompressedSize = 12288 * k; uncompressedSize += 2048 * l; if (groundUp) { uncompressedSize += 256; } byte[] uncompressedData = new byte[uncompressedSize]; Inflater inflater = new Inflater(); inflater.setInput(data, 0, compressedSize); try { inflater.inflate(uncompressedData); } catch (DataFormatException ex) { throw new IOException("Bad compressed data format"); } finally { inflater.end(); } Chunk1_8to1_7_6_10 chunk = new Chunk1_8to1_7_6_10(uncompressedData, primaryBitMask, addBitMask, true, groundUp); Field field = PacketWrapper.class.getDeclaredField("packetValues"); field.setAccessible(true); ((List)field.get(packetWrapper)).clear(); field = PacketWrapper.class.getDeclaredField("readableObjects"); field.setAccessible(true); ((LinkedList)field.get(packetWrapper)).clear(); field = PacketWrapper.class.getDeclaredField("inputBuffer"); field.setAccessible(true); ByteBuf buffer = (ByteBuf) field.get(packetWrapper); buffer.clear(); buffer.writeInt(chunkX); buffer.writeInt(chunkZ); buffer.writeBoolean(groundUp); buffer.writeShort(primaryBitMask); byte[] finaldata = chunk.get1_8Data(); Type.VAR_INT.write(buffer, finaldata.length); buffer.writeBytes(finaldata); } public static void transformChunkBulk(PacketWrapper packetWrapper) throws Exception { short columnCount = packetWrapper.read(Type.SHORT); //short1 int size = packetWrapper.read(Type.INT); //size boolean skyLightSent = packetWrapper.read(Type.BOOLEAN); //h int[] chunkX = new int[columnCount]; //a int[] chunkZ = new int[columnCount]; //b int[] primaryBitMask = new int[columnCount]; //c int[] addBitMask = new int[columnCount]; //d byte[][] inflatedBuffers = new byte[columnCount][]; //inflatedBuffers CustomByteType customByteType = new CustomByteType(size); byte[] buildBuffer = packetWrapper.read(customByteType); //buildBuffer byte[] data = new byte[196864 * columnCount]; //abyte Inflater inflater = new Inflater(); inflater.setInput(buildBuffer, 0, size); try { inflater.inflate(data); } catch (DataFormatException ex) { throw new IOException("Bad compressed data format"); } finally { inflater.end(); } int i = 0; for(int j = 0; j < columnCount; ++j) { chunkX[j] = packetWrapper.read(Type.INT); chunkZ[j] = packetWrapper.read(Type.INT); primaryBitMask[j] = packetWrapper.read(Type.SHORT); addBitMask[j] = packetWrapper.read(Type.SHORT); int k = 0; int l = 0; int i1; for(i1 = 0; i1 < 16; ++i1) { k += primaryBitMask[j] >> i1 & 1; l += addBitMask[j] >> i1 & 1; } i1 = 8192 * k + 256; i1 += 2048 * l; if (skyLightSent) { i1 += 2048 * k; } inflatedBuffers[j] = new byte[i1]; System.arraycopy(data, i, inflatedBuffers[j], 0, i1); i += i1; } Chunk1_8to1_7_6_10[] chunks = new Chunk1_8to1_7_6_10[columnCount]; for (i = 0; i<columnCount; i++) { chunks[i] = new Chunk1_8to1_7_6_10(inflatedBuffers[i], primaryBitMask[i], addBitMask[i], skyLightSent, true); } packetWrapper.write(Type.BOOLEAN, skyLightSent); packetWrapper.write(Type.VAR_INT, (int)columnCount); for(i = 0; i < columnCount; ++i) { packetWrapper.write(Type.INT, chunkX[i]); packetWrapper.write(Type.INT, chunkZ[i]); packetWrapper.write(Type.UNSIGNED_SHORT, primaryBitMask[i]); } for(i = 0; i < columnCount; ++i) { data = chunks[i].get1_8Data(); customByteType = new CustomByteType(data.length); packetWrapper.write(customByteType, data); } } public static void transformMultiBlockChange(PacketWrapper packetWrapper) throws Exception { int chunkX = packetWrapper.read(Type.INT); int chunkZ = packetWrapper.read(Type.INT); int size = packetWrapper.read(Type.SHORT); packetWrapper.read(Type.INT); short[] blocks = new short[size]; short[] positions = new short[size]; for (int i = 0; i<size; i++) { positions[i] = packetWrapper.read(Type.SHORT); blocks[i] = packetWrapper.read(Type.SHORT); } packetWrapper.write(Type.INT, chunkX); packetWrapper.write(Type.INT, chunkZ); packetWrapper.write(Type.VAR_INT, size); for (int i = 0; i<size; i++) { packetWrapper.write(Type.SHORT, positions[i]); packetWrapper.write(Type.VAR_INT, (int)blocks[i]); } } }
32.166667
114
0.707809
73fe14cf787c222dbe81b8f87894f530d371ac5b
1,153
/** * */ package com.github.reinert.jjschema.v1; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Set; import com.github.reinert.jjschema.ManagedReference; /** * @author guqk * */ public class DefaultBehaviorPropertyWrapper extends PropertyWrapper { public DefaultBehaviorPropertyWrapper(CustomSchemaWrapper ownerSchemaWrapper, Set<ManagedReference> managedReferences, Method method, Field field) { super(ownerSchemaWrapper, managedReferences, method, field); } @Override protected SchemaWrapper createWrapper(Set<ManagedReference> managedReferences, Type genericType, String relativeId1) { return DefaultSchemaWrapperFactory.createWrapper(genericType, managedReferences, relativeId1, shouldIgnoreProperties()); } @Override protected SchemaWrapper createArrayWrapper(Set<ManagedReference> managedReferences, Type propertyType, Class<?> collectionType, String relativeId1) { return DefaultSchemaWrapperFactory.createArrayWrapper(collectionType, propertyType, managedReferences, relativeId1, shouldIgnoreProperties()); } }
34.939394
153
0.789245
91ad3ef394d025889ffef4edfe585223d8627a74
1,733
package org.benetech.servicenet.adapter.healthleads.persistence; import org.benetech.servicenet.adapter.healthleads.model.HealthleadsBaseData; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; class Storage { private Map<Class<? extends HealthleadsBaseData>, Map<String, HealthleadsBaseData>> entitiesMap = new HashMap<>(); private Map<Class<? extends HealthleadsBaseData>, Map<String, Set<HealthleadsBaseData>>> entitiesSetsMap = new HashMap<>(); void addBaseData(Class<? extends HealthleadsBaseData> clazz, String id, HealthleadsBaseData data) { if (!entitiesMap.containsKey(clazz)) { entitiesMap.put(clazz, new HashMap<>()); } entitiesMap.get(clazz).put(id, data); } void addBaseDataToSet(Class<? extends HealthleadsBaseData> clazz, String id, HealthleadsBaseData data) { if (!entitiesSetsMap.containsKey(clazz)) { entitiesSetsMap.put(clazz, new HashMap<>()); } Map<String, Set<HealthleadsBaseData>> map = entitiesSetsMap.get(clazz); if (!map.containsKey(id)) { map.put(id, new HashSet<>()); } map.get(id).add(data); entitiesSetsMap.put(clazz, map); } <T extends HealthleadsBaseData> Collection<T> getValuesOfClass(Class<T> clazz) { return (Collection<T>) entitiesMap.get(clazz).values(); } <T extends HealthleadsBaseData> T getBaseData(Class<T> clazz, String id) { return (T) entitiesMap.get(clazz).get(id); } <T extends HealthleadsBaseData> Set<T> getBaseDataSet(Class<T> clazz, String id) { return (Set<T>) entitiesSetsMap.get(clazz).get(id); } }
36.104167
118
0.679746
048adca783c11af88c723c80a09d77a5ff51e342
9,761
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.models.map.storage.jpa.liquibase.extension; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import liquibase.change.AbstractChange; import liquibase.change.AddColumnConfig; import liquibase.change.Change; import liquibase.change.ChangeMetaData; import liquibase.change.ChangeStatus; import liquibase.change.ChangeWithColumns; import liquibase.change.ColumnConfig; import liquibase.change.DatabaseChange; import liquibase.change.DatabaseChangeProperty; import liquibase.change.core.AddColumnChange; import liquibase.database.Database; import liquibase.database.core.PostgresDatabase; import liquibase.exception.ValidationErrors; import liquibase.statement.SqlStatement; import liquibase.statement.core.AddColumnStatement; /** * Extension used to a column whose values are generated from a property of a JSON file stored in one of the table's columns. * <p/> * Example configuration in the changelog: * <pre> * &lt;databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" * xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" * xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog * http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd * http://www.liquibase.org/xml/ns/dbchangelog-ext * http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd"&gt; * * &lt;changeSet author="keycloak" id="some_id"&gt; * ... * &lt;ext:addGeneratedColumn tableName="test"&gt; * &lt;ext:column name="new_column" type="VARCHAR(36)" jsonColumn="metadata" jsonProperty="alias"/&gt; * &lt;/ext:addGeneratedColumn&gt; * &lt;/changeSet&gt; * </pre> * The above configuration is adding a new column, named {@code new_column}, whose values are generated from the {@code alias} property * of the JSON file stored in column {@code metadata}. If, for example, a particular entry in the table contains the JSON * {@code {"name":"duke","alias":"jduke"}} in column {@code metadata}, the value generated for the new column will be {@code jduke}. * * @author <a href="mailto:[email protected]">Stefan Guilhen</a> */ @DatabaseChange(name = "addGeneratedColumn", description = "Adds new generated columns to a table. The columns must reference a JSON property inside an existing JSON column.", priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "table") public class GeneratedColumnChange extends AbstractChange implements ChangeWithColumns<JsonEnabledColumnConfig> { private final ExtendedAddColumnChange delegate; private Map<String, JsonEnabledColumnConfig> configMap = new HashMap<>(); public GeneratedColumnChange() { this.delegate = new ExtendedAddColumnChange(); } @DatabaseChangeProperty(mustEqualExisting ="relation.catalog") public String getCatalogName() { return this.delegate.getCatalogName(); } public void setCatalogName(final String catalogName) { this.delegate.setCatalogName(catalogName); } @DatabaseChangeProperty(mustEqualExisting ="relation.schema") public String getSchemaName() { return this.delegate.getSchemaName(); } public void setSchemaName(final String schemaName) { this.delegate.setSchemaName(schemaName); } @DatabaseChangeProperty(mustEqualExisting ="table", description = "Name of the table to add the generated column to") public String getTableName() { return this.delegate.getTableName(); } public void setTableName(final String tableName) { this.delegate.setTableName(tableName); } @Override public void addColumn(final JsonEnabledColumnConfig column) { this.delegate.addColumn(column); this.configMap.put(column.getName(), column); } @Override @DatabaseChangeProperty(description = "Generated columns information", requiredForDatabase = "all") public List<JsonEnabledColumnConfig> getColumns() { return this.delegate.getColumns().stream().map(JsonEnabledColumnConfig.class::cast).collect(Collectors.toList()); } @Override public void setColumns(final List<JsonEnabledColumnConfig> columns) { columns.forEach(this.delegate::addColumn); this.configMap = this.getColumns().stream() .collect(Collectors.toMap(ColumnConfig::getName, Function.identity())); } @Override public SqlStatement[] generateStatements(Database database) { if (database instanceof PostgresDatabase) { for (AddColumnConfig config : delegate.getColumns()) { String columnType = config.getType(); // if postgres, change JSON type to JSONB before generating the statements as JSONB is more efficient. if (columnType.equalsIgnoreCase("JSON")) { config.setType("JSONB"); } } } // AddColumnChange always produces an AddColumnStatement in the first position of the returned array. AddColumnStatement delegateStatement = (AddColumnStatement) Arrays.stream(this.delegate.generateStatements(database)) .findFirst().get(); // convert the regular AddColumnStatements into GeneratedColumnStatements, adding the extension properties. if (!delegateStatement.isMultiple()) { // single statement - convert it directly. JsonEnabledColumnConfig config = configMap.get(delegateStatement.getColumnName()); if (config != null) { return new SqlStatement[] {new GeneratedColumnStatement(delegateStatement, config.getJsonColumn(), config.getJsonProperty())}; } } else { // multiple statement - convert all sub-statements. List<GeneratedColumnStatement> generatedColumnStatements = delegateStatement.getColumns().stream() .filter(c -> configMap.containsKey(c.getColumnName())) .map(c -> new GeneratedColumnStatement(c, configMap.get(c.getColumnName()).getJsonColumn(), configMap.get(c.getColumnName()).getJsonProperty())) .collect(Collectors.toList()); // add all GeneratedColumnStatements into a composite statement and return the composite. return new SqlStatement[]{new GeneratedColumnStatement(generatedColumnStatements)}; } return new SqlStatement[0]; } @Override protected Change[] createInverses() { return this.delegate.createInverses(); } @Override public ChangeStatus checkStatus(Database database) { return delegate.checkStatus(database); } @Override public String getConfirmationMessage() { return delegate.getConfirmationMessage(); } @Override public String getSerializedObjectNamespace() { return GENERIC_CHANGELOG_EXTENSION_NAMESPACE; } @Override public ValidationErrors validate(Database database) { ValidationErrors validationErrors = new ValidationErrors(); validationErrors.checkRequiredField("columns", this.delegate.getColumns()); // validate each generated column. this.delegate.getColumns().stream().map(JsonEnabledColumnConfig.class::cast).forEach( config -> { if (config.isAutoIncrement() != null && config.isAutoIncrement()) { validationErrors.addError("Generated column " + config.getName() + " cannot be auto-incremented"); } else if (config.getValueObject() != null) { validationErrors.addError("Generated column " + config.getName() + " cannot be configured with a value"); } else if (config.getDefaultValueObject() != null) { validationErrors.addError("Generated column " + config.getName() + " cannot be configured with a default value"); } // we can expand this check if we decide to allow other types of generated columns in the future - for now // ensure the column can be properly generated from a json property stored on a json column. validationErrors.checkRequiredField("jsonColumn", config.getJsonColumn()); validationErrors.checkRequiredField("jsonProperty", config.getJsonProperty()); }); validationErrors.addAll(super.validate(database)); return validationErrors; } /** * Simple extension that makes protected methods public so they can be accessed as a delegate. */ private static class ExtendedAddColumnChange extends AddColumnChange { @Override public Change[] createInverses() { return super.createInverses(); } } }
44.981567
175
0.683229
49e9c86b74bdc1efc6b9ccf42901d700f187c807
2,003
package amai.org.conventions.model; import java.io.Serializable; import java.util.Collections; import java.util.List; import amai.org.conventions.utils.Objects; public class StandsArea extends Place implements Serializable { private int id; private Integer imageResource; private float imageWidth; private float imageHeight; private List<Stand> stands = Collections.emptyList(); public StandsArea() { id = ObjectIDs.getNextID(); } public int getId() { return id; } @Override public StandsArea withName(String name) { super.withName(name); return this; } public boolean hasImageResource() { return imageResource != null; } public void setImageResource(int imageResource) { this.imageResource = imageResource; } public int getImageResource() { return imageResource; } public StandsArea withImageResource(int imageResource) { setImageResource(imageResource); return this; } public void setStands(List<Stand> stands) { this.stands = stands; for (Stand stand : stands) { stand.setStandsArea(this); } } public List<Stand> getStands() { return stands; } public StandsArea withStands(List<Stand> stands) { setStands(stands); return this; } @Override public boolean equals(Object o) { if (o instanceof StandsArea) { StandsArea other = (StandsArea) o; return Objects.equals(name, other.name) && Objects.equals(stands, other.stands); } return false; } @Override public int hashCode() { return Objects.hash(name, stands); } public float getImageWidth() { return imageWidth; } public void setImageWidth(float imageWidth) { this.imageWidth = imageWidth; } public StandsArea withImageWidth(float imageWidth) { setImageWidth(imageWidth); return this; } public float getImageHeight() { return imageHeight; } public void setImageHeight(float imageHeight) { this.imageHeight = imageHeight; } public StandsArea withImageHeight(float imageHeight) { setImageHeight(imageHeight); return this; } }
19.259615
83
0.732901
4a41805f1b0a566c3fa1501906ec7bd56026e025
2,389
package org.apache.spark.smstorage; //import org.apache.hadoop.mapred.datacache.JniShm; public class ShareMemTest { public static void main(String[] args) { // JniShm shm = JniShm.getInstance(); // // int mb = 1024*1024; // int gb = 1024*1024*1024; // //long size = 1024*mb; // long size = 128*mb; // int bufferSize = 8*1024;//1MB // // int shmId = shm.getCacheId(size); // // int shmgetId = shm.libshmat(shmId);// ¹ÒÔØ¹²ÏíÄÚ´æ // System.out.println("shmId: "+shmId+" readid: "+shmgetId); // // int currentPosn = 0; // byte[] buffer = new byte[bufferSize]; // for (int i = 0; i < buffer.length; i++) { // buffer[i] = 123; // } // // long writeStartTime = System.currentTimeMillis(); // int count = 0; // do { // //shm.writeData(id, buffer, bufferLength); // shm.writeCache(shmgetId, buffer, bufferSize); // ½«bufferÖеÄÊý¾ÝдÈëµ½¹²ÏíÄÚ´æ¿Õ¼äÖÐ // currentPosn += bufferSize; // // } while (currentPosn < size); // // long writeEndTime = System.currentTimeMillis(); // System.out.println(" len:"+size+",write len:"+currentPosn+", write time: "+(writeEndTime-writeStartTime)); // //shm.writeCache(id, buffer, bufferLength); // ½«bufferÖеÄÊý¾ÝдÈëµ½¹²ÏíÄÚ´æ¿Õ¼äÖÐ // shm.shmdt(shmgetId); // ¶Ï¿ª¹²ÏíÄÚ´æ // // // //-------------------------read--------------------------// // // if ((shmgetId = shm.shmat(shmId)) < 0) { // System.out.println("shmat error"); // return; // } // System.out.println("begin read shmid: "+shmId); // // long remainLength = size; // int readLength = 0; // long readTimeBegin = System.currentTimeMillis(); // // while (remainLength > 0) { // //System.out.println("remaining: "+remainLength); // if (remainLength > bufferSize) // readLength = bufferSize; // else // readLength = (int) remainLength; // // shm.readCache(shmgetId, readLength); // // //// while (readTime++ < 1000 && blockBuf.remaining() > 0) { //// System.out.print(blockBuf.get()); //// } // //System.out.println(); // // // Success // remainLength -= readLength; // } // // long readTimeEnd = System.currentTimeMillis(); // // System.out.println("read end, length: "+(size-remainLength)+", time spent: "+(readTimeEnd-readTimeBegin)); // //TimeUnit.MINUTES.SECONDS.sleep(30); // shm.releaseCache(shmId); } }
28.783133
110
0.587275
55fdd1676cce9f7fbf1691e5a82abaa33bcbce83
8,694
package org.yeshen.video.librtmp.unstable.net.sender.rtmp.packets; import org.yeshen.video.librtmp.unstable.net.sender.rtmp.Util; import org.yeshen.video.librtmp.unstable.net.sender.rtmp.io.SessionInfo; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; /** * User Control message, such as ping * * @author francois */ public class UserControl extends Chunk { /** * Control message type * Docstring adapted from the official Adobe RTMP spec, section 3.7 */ public static enum Type { /** * Type: 0 * The server sends this event to notify the client that a stream has become * functional and can be used for communication. By default, this event * is sent on ID 0 after the application connect command is successfully * received from the client. * * Event Data: * eventData[0] (int) the stream ID of the stream that became functional */ STREAM_BEGIN(0), /** * Type: 1 * The server sends this event to notify the client that the playback of * data is over as requested on this stream. No more data is sent without * issuing additional commands. The client discards the messages received * for the stream. * * Event Data: * eventData[0]: the ID of thestream on which playback has ended. */ STREAM_EOF(1), /** * Type: 2 * The server sends this event to notify the client that there is no * more data on the stream. If the server does not detect any message for * a time period, it can notify the subscribed clients that the stream is * dry. * * Event Data: * eventData[0]: the stream ID of the dry stream. */ STREAM_DRY(2), /** * Type: 3 * The client sends this event to inform the server of the buffer size * (in milliseconds) that is used to buffer any data coming over a stream. * This event is sent before the server starts processing the stream. * * Event Data: * eventData[0]: the stream ID and * eventData[1]: the buffer length, in milliseconds. */ SET_BUFFER_LENGTH(3), /** * Type: 4 * The server sends this event to notify the client that the stream is a * recorded stream. * * Event Data: * eventData[0]: the stream ID of the recorded stream. */ STREAM_IS_RECORDED(4), /** * Type: 6 * The server sends this event to test whether the client is reachable. * * Event Data: * eventData[0]: a timestamp representing the local server time when the server dispatched the command. * * The client responds with PING_RESPONSE on receiving PING_REQUEST. */ PING_REQUEST(6), /** * Type: 7 * The client sends this event to the server in response to the ping request. * * Event Data: * eventData[0]: the 4-byte timestamp which was received with the PING_REQUEST. */ PONG_REPLY(7), /** * Type: 31 (0x1F) * * This user control type is not specified in any official documentation, but * is sent by Flash Media Server 3.5. Thanks to the rtmpdump devs for their * explanation: * * Buffer Empty (unofficial name): After the server has sent a complete buffer, and * sends this Buffer Empty message, it will wait until the play * duration of that buffer has passed before sending a new buffer. * The Buffer Ready message will be sent when the new buffer starts. * * (see also: http://repo.or.cz/w/rtmpdump.git/blob/8880d1456b282ee79979adbe7b6a6eb8ad371081:/librtmp/rtmp.c#l2787) */ BUFFER_EMPTY(31), /** * Type: 32 (0x20) * * This user control type is not specified in any official documentation, but * is sent by Flash Media Server 3.5. Thanks to the rtmpdump devs for their * explanation: * * Buffer Ready (unofficial name): After the server has sent a complete buffer, and * sends a Buffer Empty message, it will wait until the play * duration of that buffer has passed before sending a new buffer. * The Buffer Ready message will be sent when the new buffer starts. * (There is no BufferReady message for the very first buffer; * presumably the Stream Begin message is sufficient for that * purpose.) * * (see also: http://repo.or.cz/w/rtmpdump.git/blob/8880d1456b282ee79979adbe7b6a6eb8ad371081:/librtmp/rtmp.c#l2787) */ BUFFER_READY(32); private int intValue; private static final Map<Integer, Type> quickLookupMap = new HashMap<Integer, Type>(); static { for (Type type : Type.values()) { quickLookupMap.put(type.getIntValue(), type); } } private Type(int intValue) { this.intValue = intValue; } public int getIntValue() { return intValue; } public static Type valueOf(int intValue) { return quickLookupMap.get(intValue); } } private Type type; private int[] eventData; public UserControl(ChunkHeader header) { super(header); } public UserControl() { super(new ChunkHeader(ChunkType.TYPE_0_FULL, SessionInfo.RTMP_CONTROL_CHANNEL, MessageType.USER_CONTROL_MESSAGE)); } /** Convenience construtor that creates a "pong" message for the specified ping */ public UserControl(UserControl replyToPing) { this(Type.PONG_REPLY); this.eventData = replyToPing.eventData; } public UserControl(Type type) { this(); this.type = type; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } /** * Convenience method for getting the first event data item, as most user control * message types only have one event data item anyway * This is equivalent to calling <code>getEventData()[0]</code> */ public int getFirstEventData() { return eventData[0]; } public int[] getEventData() { return eventData; } /** Used to set (a single) event data for most user control message types */ public void setEventData(int eventData) { if (type == Type.SET_BUFFER_LENGTH) { throw new IllegalStateException("SET_BUFFER_LENGTH requires two event data values; use setEventData(int, int) instead"); } this.eventData = new int[]{eventData}; } /** Used to set event data for the SET_BUFFER_LENGTH user control message types */ public void setEventData(int streamId, int bufferLength) { if (type != Type.SET_BUFFER_LENGTH) { throw new IllegalStateException("User control type " + type + " requires only one event data value; use setEventData(int) instead"); } this.eventData = new int[]{streamId, bufferLength}; } @Override public void readBody(InputStream in) throws IOException { // Bytes 0-1: first parameter: ping type (mandatory) type = Type.valueOf(Util.readUnsignedInt16(in)); int bytesRead = 2; // Event data (1 for most types, 2 for SET_BUFFER_LENGTH) if (type == Type.SET_BUFFER_LENGTH) { setEventData(Util.readUnsignedInt32(in), Util.readUnsignedInt32(in)); bytesRead += 8; } else { setEventData(Util.readUnsignedInt32(in)); bytesRead += 4; } // To ensure some strange non-specified UserControl/ping message does not slip through assert header.getPacketLength() == bytesRead; } @Override protected void writeBody(OutputStream out) throws IOException { // Write the user control message type Util.writeUnsignedInt16(out, type.getIntValue()); // Now write the event data Util.writeUnsignedInt32(out, eventData[0]); if (type == Type.SET_BUFFER_LENGTH) { Util.writeUnsignedInt32(out, eventData[1]); } } @Override public String toString() { return "RTMP User Control (type: " + type + ", event data: " + eventData + ")"; } }
35.777778
144
0.606855
d59f7a29e0c2ced89fa82d96dc50f2a744fa3269
2,082
package net.anschau.cnab.caixa.cnab240; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * @author Edenir Norberto Anschau ([email protected]) */ class HeaderArquivo { private final Beneficiario beneficiario; private final int nsa; private final LocalDateTime dataHoraGeracao; public HeaderArquivo(Beneficiario beneficiario, int nsa) { this.beneficiario = beneficiario; this.nsa = nsa; this.dataHoraGeracao = LocalDateTime.now(); } public HeaderArquivo(Beneficiario beneficiario, int nsa, LocalDateTime dataHoraGeracao) { this.beneficiario = beneficiario; this.nsa = nsa; this.dataHoraGeracao = dataHoraGeracao; } String get() { StringBuilder header = new StringBuilder(240); header.append("104");//1-3 header.append("0000");//4-7 header.append("0");//8-8 header.append(new CampoAlfaNumerico(" ", 9));//9-17 header.append(beneficiario.tipoInscricao()); //18-18 header.append(beneficiario.getDocumento()); //19-32 header.append(new CampoNumerico("0", 20)); //33-52 header.append(beneficiario.getAgencia()); //53-57 header.append(beneficiario.getDvAgencia()); //58-58 header.append(beneficiario.getContaCorrente()); //59-64 header.append(new CampoNumerico("0", 8)); //65-72 header.append(beneficiario.getNome()); //73-102 header.append(new CampoAlfaNumerico("CAIXA ECONOMICA FEDERAL", 30)); //103-132 header.append(new CampoAlfaNumerico(" ", 10));//133-142 header.append('1'); //143-143 DateTimeFormatter timeStamp = DateTimeFormatter.ofPattern("ddMMyyyyhhmmss"); header.append(dataHoraGeracao.format(timeStamp)); //144-157 header.append(new CampoNumerico(nsa, 6)); //158-163 header.append("050"); //164-166 header.append(new CampoNumerico(0, 5)); //167-171 header.append(new CampoAlfaNumerico(" ", 20));//172-191 header.append(new CampoAlfaNumerico("REMESSA-PRODUCAO", 20));//192-211 header.append(new CampoAlfaNumerico(" ", 29));//212-240 return header.toString(); } }
37.178571
82
0.695965
cc3345c55e4ad115ac3872467ebd1f0d89c5aea6
1,177
package com.christopher.enhancedcraft.item; import com.christopher.enhancedcraft.init.ItemInit; import net.minecraft.item.IItemTier; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.item.SwordItem; import net.minecraft.item.crafting.Ingredient; public class PlatinumSword extends SwordItem { public PlatinumSword() { super(new IItemTier() { @Override public int getMaxUses() { return 1843; } @Override public float getEfficiency() { return 12.0F; } @Override public float getAttackDamage() { return 4.0F; } @Override public int getHarvestLevel() { return 4; } @Override public int getEnchantability() { return 25; } @Override public Ingredient getRepairMaterial() { return Ingredient.fromItems(ItemInit.PLATINUM_INGOT.get()); } }, 4,-2.4F,(new Item.Properties()).group(ItemGroup.COMBAT)); } }
26.155556
75
0.5548
b092cef56ae0a386b65c1831142942cd25cdd9a9
4,741
/** * */ package com.athene.core.provider; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.athene.ParameterUtils; import com.athene.provider.api.Service; import Ice.Current; import Ice.DispatchStatus; import Ice.ObjectImpl; import IceInternal.BasicStream; import IceInternal.Incoming; /** * @author zhaochf * */ public abstract class AbstractService extends ObjectImpl implements Service { /** * */ private static final long serialVersionUID = -3010942133746398616L; private final String[] ids = new String[2]; private final Map<String, Method> operationMappings = Collections.synchronizedMap(new HashMap<>()); /** * */ public AbstractService() { // init distributed service ids and operations resolveServiceId(); resolveOperationMappings(); } /* (non-Javadoc) * @see Ice.ObjectImpl#__dispatch(IceInternal.Incoming, Ice.Current) */ @Override public DispatchStatus __dispatch(Incoming in, Current current) { if ("ice_id".equals(current.operation)) { return ___ice_id(this, in, current); } else if ("ice_ids".equals(current.operation)) { return ___ice_ids(this, in, current); } else if ("ice_isA".equals(current.operation)) { return ___ice_isA(this, in, current); } else if ("ice_ping".equals(current.operation)) { return ___ice_ping(this, in, current); } else if (!operationMappings.containsKey(current.operation)) { throw new Ice.OperationNotExistException(current.id, current.facet, current.operation); } return invoke(operationMappings.get(current.operation), in, current); } /** * * @param method * @param in * @param current * @return */ private Ice.DispatchStatus invoke(Method method, IceInternal.Incoming in, Ice.Current current) { Class<?>[] parameterTypes = method.getParameterTypes(); Object result = null; try { if (parameterTypes == null || parameterTypes.length == 0) { result = method.invoke(this); } else { Object[] parameterValues = new Object[parameterTypes.length]; IceInternal.BasicStream bs = in.startReadParams(); for (int i = 0; i < parameterTypes.length; i++) { parameterValues[i] = ParameterUtils.readParameter(bs, parameterTypes[i]); } in.endReadParams(); result = method.invoke(this, parameterValues); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } if (void.class.isAssignableFrom(method.getReturnType())) { in.__writeEmptyParams(); } else { IceInternal.BasicStream bs = in.__startWriteParams(Ice.FormatType.DefaultFormat); ParameterUtils.writeParameter(bs, method.getReturnType(), result); in.__endWriteParams(true); } return Ice.DispatchStatus.DispatchOK; } /* (non-Javadoc) * @see Ice.ObjectImpl#ice_isA(java.lang.String) */ @Override public boolean ice_isA(String s) { return Arrays.binarySearch(this.ids, s) > 0; } /* (non-Javadoc) * @see Ice.ObjectImpl#ice_isA(java.lang.String, Ice.Current) */ @Override public boolean ice_isA(String s, Current current) { return Arrays.binarySearch(this.ids, s) > 0; } /* (non-Javadoc) * @see Ice.ObjectImpl#ice_ids() */ @Override public String[] ice_ids() { return this.ids; } /* (non-Javadoc) * @see Ice.ObjectImpl#ice_ids(Ice.Current) */ @Override public String[] ice_ids(Current current) { return this.ids; } /* (non-Javadoc) * @see Ice.ObjectImpl#ice_id() */ @Override public String ice_id() { return this.ids[1]; } /* (non-Javadoc) * @see Ice.ObjectImpl#ice_id(Ice.Current) */ @Override public String ice_id(Current current) { return this.ids[1]; } /* (non-Javadoc) * @see Ice.ObjectImpl#__writeImpl(IceInternal.BasicStream) */ @Override protected void __writeImpl(BasicStream os) { os.startWriteSlice(ice_staticId(), -1, true); os.endWriteSlice(); } /* (non-Javadoc) * @see Ice.ObjectImpl#__readImpl(IceInternal.BasicStream) */ @Override protected void __readImpl(BasicStream is) { is.startReadSlice(); is.endReadSlice(); } private void resolveServiceId() { this.ids[0] = serviceDefaultId; this.ids[1] = getClass().getName().replace(".", "::"); } private void resolveOperationMappings() { List<Method> methods = Arrays.asList(getClass().getMethods()); methods.forEach((method) -> { this.operationMappings.put(method.getName(), method); }); } }
25.766304
101
0.67644
52ff8826a958e41d09547fa58337c6b0b2baed2c
4,980
/** * Copyright 2020 Smart Society Services B.V. * * 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 */ package org.opensmartgridplatform.adapter.protocol.iec60870.application.services; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import org.opensmartgridplatform.adapter.protocol.iec60870.domain.entities.Iec60870Device; import org.opensmartgridplatform.adapter.protocol.iec60870.domain.repositories.Iec60870DeviceRepository; import org.opensmartgridplatform.adapter.protocol.iec60870.domain.valueobjects.DeviceType; import org.opensmartgridplatform.adapter.protocol.iec60870.domain.valueobjects.ResponseMetadata; import org.opensmartgridplatform.dto.da.measurements.MeasurementReportDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; @Service public class LightMeasurementGatewayDeviceResponseService extends AbstractDeviceResponseService { private static final Logger LOGGER = LoggerFactory.getLogger(LightMeasurementGatewayDeviceResponseService.class); private static final String ERROR_PREFIX = "Error while processing measurement report for light measurement gateway: "; private static final DeviceType DEVICE_TYPE = DeviceType.LIGHT_MEASUREMENT_GATEWAY; @Autowired private Iec60870DeviceRepository iec60870DeviceRepository; @Autowired private LightMeasurementDeviceResponseService lightMeasurementDeviceResponseService; public LightMeasurementGatewayDeviceResponseService() { super(DEVICE_TYPE); } @Override public void process(final MeasurementReportDto measurementReport, final ResponseMetadata responseMetadata) { final String gatewayDeviceIdentification = responseMetadata.getDeviceIdentification(); LOGGER.info("Received measurement report {} for light measurement gateway {}.", measurementReport, gatewayDeviceIdentification); this.findLightMeasurementDevicesAndThen(gatewayDeviceIdentification, device -> this.processMeasurementReportForDevice(measurementReport, responseMetadata, device, gatewayDeviceIdentification)); } private void processMeasurementReportForDevice(final MeasurementReportDto measurementReport, final ResponseMetadata responseMetadata, final Iec60870Device device, final String gatewayDeviceIdentification) { LOGGER.info("Processing measurement report for light measurement device {} with gateway {}", device.getDeviceIdentification(), gatewayDeviceIdentification); this.lightMeasurementDeviceResponseService.sendLightSensorStatusResponse(measurementReport, device, responseMetadata, ERROR_PREFIX); } @Override public void processEvent(final MeasurementReportDto measurementReport, final ResponseMetadata responseMetadata) { final String gatewayDeviceIdentification = responseMetadata.getDeviceIdentification(); LOGGER.info("Received event {} for light measurement gateway {}.", measurementReport, gatewayDeviceIdentification); this.findLightMeasurementDevicesAndThen(gatewayDeviceIdentification, device -> this .processEventForDevice(measurementReport, responseMetadata, device, gatewayDeviceIdentification)); } private void processEventForDevice(final MeasurementReportDto measurementReport, final ResponseMetadata responseMetadata, final Iec60870Device device, final String gatewayDeviceIdentification) { LOGGER.info("Processing event for light measurement device {} with gateway {}", device.getDeviceIdentification(), gatewayDeviceIdentification); this.lightMeasurementDeviceResponseService.sendEvent(measurementReport, device, responseMetadata, ERROR_PREFIX); } private void findLightMeasurementDevicesAndThen(final String gatewayDeviceIdentification, final Consumer<? super Iec60870Device> actionPerDevice) { final List<Iec60870Device> lightMeasurementDevices = this.iec60870DeviceRepository .findByGatewayDeviceIdentification(gatewayDeviceIdentification) .stream() .filter(device -> DeviceType.LIGHT_MEASUREMENT_DEVICE == device.getDeviceType()) .collect(Collectors.toList()); if (CollectionUtils.isEmpty(lightMeasurementDevices)) { LOGGER.warn("No light measurement devices found for light measurement gateway {}", gatewayDeviceIdentification); return; } lightMeasurementDevices.forEach(actionPerDevice); } }
48.349515
172
0.766466
10b58acfa3cd89da967f328b903f47df6825d9e0
337
package com.design.designpattern.behavioral.chain; /** * 抽象处理者角色 */ public abstract class Producter { private Producter next; public void setNext(Producter next) { this.next = next; } public Producter getNext() { return next; } //处理请求的方法 public abstract void product(String request); }
16.047619
50
0.646884
12ff0055ea58f9d390a2f90bc919887a7b98f750
2,456
package org.jboss.resteasy.reactive.common.providers.serialisers; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; public class NumberMessageBodyHandler extends PrimitiveBodyHandler implements MessageBodyReader<Number> { public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Number.class.isAssignableFrom(type); } public Number readFrom(Class<Number> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { return doReadFrom(type, entityStream); } protected Number doReadFrom(Class<Number> type, InputStream entityStream) throws IOException { String text = readFrom(entityStream, false); // we initially had one provider per number type, but the TCK wants this Number provider to be overridable if ((Class<? extends Number>) type == Byte.class || (Class<? extends Number>) type == byte.class) return Byte.valueOf(text); if ((Class<? extends Number>) type == Short.class || (Class<? extends Number>) type == short.class) return Integer.valueOf(text); if ((Class<? extends Number>) type == Integer.class || (Class<? extends Number>) type == int.class) return Integer.valueOf(text); if ((Class<? extends Number>) type == Long.class || (Class<? extends Number>) type == long.class) return Long.valueOf(text); if ((Class<? extends Number>) type == Float.class || (Class<? extends Number>) type == float.class) return Float.valueOf(text); if ((Class<? extends Number>) type == Double.class || (Class<? extends Number>) type == double.class) return Double.valueOf(text); if ((Class<? extends Number>) type == BigDecimal.class) return new BigDecimal(text); if ((Class<? extends Number>) type == BigInteger.class) return new BigInteger(text); throw new RuntimeException("Don't know how to handle number class " + type); } }
52.255319
114
0.689739
40bc38ba9043c0c99268997997e6f725fdc039fa
3,745
package org.websync.utils; import org.websync.browserConnection.SessionWebSerializer; import org.websync.ember.EmberSerializer; import org.websync.sessionweb.PsiSessionWebProvider; import org.websync.sessionweb.models.SessionWeb; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ClassInheritorsSearch; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public class FileParser { public void parse(List<String> lines) { if (lines == null || lines.size() == 0) { System.out.println("File is empty."); return; } switch (lines.get(0)) { case "a": System.out.println("Command 'a'"); break; case "b": System.out.println("Command 'b'"); break; case "print": System.out.println("Print"); printClasses(); break; case "web": System.out.println("web..."); testSessionWebProvider(); break; case "ser": System.out.println("ser..."); testSerializer(); break; default: System.out.println(String.format("Any command '%s'", lines.get(0))); } } private void testSerializer() { ApplicationManager.getApplication().runReadAction(() -> { Project project = ProjectManager.getInstance().getOpenProjects()[0]; PsiSessionWebProvider webProvider = new PsiSessionWebProvider(project); Collection<SessionWeb> sessions = webProvider.getSessionWebs(false); SessionWebSerializer serializer = new EmberSerializer(); String json = serializer.serialize(sessions); sessions = serializer.deserialize(json); }); } private void testSessionWebProvider() { ApplicationManager.getApplication().runReadAction(() -> { Project project = ProjectManager.getInstance().getOpenProjects()[0]; PsiSessionWebProvider webProvider = new PsiSessionWebProvider(project); webProvider.getSessionWebs(true); }); } final public String JDI_WEBPAGE = "com.epam.jdi.light.elements.composite.WebPage"; private void printClasses() { Project[] projects = ProjectManager.getInstance().getOpenProjects(); if (projects.length == 0) { ApplicationManager.getApplication().runReadAction(() -> { System.out.println("None project has not been opened."); }); } Project project = projects[0]; if (!project.isInitialized()) { ApplicationManager.getApplication().runReadAction(() -> { System.out.println("Project has not been initialized."); }); } JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project); GlobalSearchScope allScope = GlobalSearchScope.allScope(project); ApplicationManager.getApplication().runReadAction(() -> { PsiClass webPagePsiClass = javaPsiFacade.findClass(JDI_WEBPAGE, allScope); List<PsiClass> classes = ClassInheritorsSearch.search(webPagePsiClass).findAll() .stream().collect(Collectors.toList()); System.out.println("Classes:"); classes.forEach(c -> System.out.println("*" + c.getQualifiedName())); }); } }
37.079208
92
0.619226
96ef27b8361dc61f3b47854d7c5911fe8baa0b78
11,260
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.legacy; import ij.Macro; import ij.gui.DialogListener; import ij.plugin.filter.PlugInFilterRunner; import java.awt.Button; import java.awt.Checkbox; import java.awt.Component; import java.awt.Font; import java.awt.Insets; import java.awt.Panel; import java.awt.TextArea; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * Limited headless support for ImageJ 1.x. * * <p> * <i>Headless operation</i> means: does not require a graphical user interface * (GUI). Due to some limitations in Java on Linux and Unix, it is impossible to * instantiate GUI elements when there is no way to display them (i.e. when * there is no desktop environment) -- even if they are never to be displayed. * </p> * * <p> * Therefore, even when running in batch mode, we have to prevent GUI elements * -- such as dialogs -- to be instantiated. * </p> * * <p> * Unfortunately, ImageJ 1.x' macro handling works exclusively by instantiating * dialogs (but not displaying them). Macros are executed by overriding the * dialog methods to extract the user-specified values. * </p> * * <p> * The limited legacy headless support overrides {@link ij.gui.GenericDialog} to * <b>not</b> be a subclass of {@link java.awt.Dialog}. This will always be a * fragile solution, especially with plugins trying to add additional GUI * elements to the dialog: when those GUI elements are instantiated, Java will * throw a {@link java.awt.HeadlessException}. Hence the legacy headless support * only works with standard (i.e. non-fancy) plugins; this could only be fixed * by overriding the plugin class loader with a version inspecting every plugin * class and using Javassist to override such instantiations. Given that * ImageJ2's architecture handles headless operation much more gracefully, that * enormous effort would have little to gain. * </p> * * @author Johannes Schindelin */ public class LegacyHeadless { private final CodeHacker hacker; public LegacyHeadless(final CodeHacker hacker) { this.hacker = hacker; } public void patch() { if (hacker.hasSuperclass("ij.gui.GenericDialog", GenericDialog.class.getName())) { // if we already applied the headless patches, let's not do it again return; } hacker.replaceWithStubMethods("ij.gui.GenericDialog", "paint", "getInsets", "showHelp"); hacker.replaceSuperclass("ij.gui.GenericDialog", GenericDialog.class.getName()); hacker.skipAWTInstantiations("ij.gui.GenericDialog"); hacker.insertAtTopOfMethod("ij.Menus", "void installJarPlugin(java.lang.String jarName, java.lang.String pluginsConfigLine)", "int quote = $2.indexOf('\"');" + "if (quote >= 0)" + " addPluginItem(null, $2.substring(quote));"); hacker.skipAWTInstantiations("ij.Menus"); hacker.skipAWTInstantiations("ij.plugin.HyperStackConverter"); hacker.skipAWTInstantiations("ij.plugin.Duplicator"); hacker.insertAtTopOfMethod("ij.plugin.filter.ScaleDialog", "java.awt.Panel makeButtonPanel(ij.plugin.filter.SetScaleDialog gd)", "return null;"); } private static boolean getMacroParameter(String label, boolean defaultValue) { return getMacroParameter(label) != null || defaultValue; } private static double getMacroParameter(String label, double defaultValue) { String value = Macro.getValue(Macro.getOptions(), label, null); return value != null ? Double.parseDouble(value) : defaultValue; } private static String getMacroParameter(String label, String defaultValue) { return Macro.getValue(Macro.getOptions(), label, defaultValue); } private static String getMacroParameter(String label) { return Macro.getValue(Macro.getOptions(), label, null); } public static class GenericDialog { protected List<Double> numbers; protected List<String> strings; protected List<Boolean> checkboxes; protected List<String> choices; protected List<Integer> choiceIndices; protected String textArea1, textArea2; protected int numberfieldIndex = 0, stringfieldIndex = 0, checkboxIndex = 0, choiceIndex = 0, textAreaIndex = 0; protected boolean invalidNumber; protected String errorMessage; public GenericDialog() { if (Macro.getOptions() == null) throw new RuntimeException("Cannot instantiate headless dialog except in macro mode"); numbers = new ArrayList<Double>(); strings = new ArrayList<String>(); checkboxes = new ArrayList<Boolean>(); choices = new ArrayList<String>(); choiceIndices = new ArrayList<Integer>(); } public void addCheckbox(String label, boolean defaultValue) { checkboxes.add(getMacroParameter(label, defaultValue)); } @SuppressWarnings("unused") public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues) { for (int i = 0; i < labels.length; i++) addCheckbox(labels[i], defaultValues[i]); } @SuppressWarnings("unused") public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues, String[] headings) { addCheckboxGroup(rows, columns, labels, defaultValues); } public void addChoice(String label, String[] items, String defaultItem) { String item = getMacroParameter(label, defaultItem); int index = 0; for (int i = 0; i < items.length; i++) if (items[i].equals(item)) { index = i; break; } choiceIndices.add(index); choices.add(items[index]); } @SuppressWarnings("unused") public void addNumericField(String label, double defaultValue, int digits) { numbers.add(getMacroParameter(label, defaultValue)); } @SuppressWarnings("unused") public void addNumericField(String label, double defaultValue, int digits, int columns, String units) { addNumericField(label, defaultValue, digits); } @SuppressWarnings("unused") public void addSlider(String label, double minValue, double maxValue, double defaultValue) { numbers.add(getMacroParameter(label, defaultValue)); } public void addStringField(String label, String defaultText) { strings.add(getMacroParameter(label, defaultText)); } @SuppressWarnings("unused") public void addStringField(String label, String defaultText, int columns) { addStringField(label, defaultText); } @SuppressWarnings("unused") public void addTextAreas(String text1, String text2, int rows, int columns) { textArea1 = text1; textArea2 = text2; } public boolean getNextBoolean() { return checkboxes.get(checkboxIndex++); } public String getNextChoice() { return choices.get(choiceIndex++); } public int getNextChoiceIndex() { return choiceIndices.get(choiceIndex++); } public double getNextNumber() { return numbers.get(numberfieldIndex++); } /** Returns the contents of the next text field. */ public String getNextString() { return strings.get(stringfieldIndex++); } public String getNextText() { switch (textAreaIndex++) { case 0: return textArea1; case 1: return textArea2; } return null; } public boolean invalidNumber() { boolean wasInvalid = invalidNumber; invalidNumber = false; return wasInvalid; } public void showDialog() { if (Macro.getOptions() == null) throw new RuntimeException("Cannot run dialog headlessly"); numberfieldIndex = 0; stringfieldIndex = 0; checkboxIndex = 0; choiceIndex = 0; textAreaIndex = 0; } public boolean wasCanceled() { return false; } public boolean wasOKed() { return true; } public void dispose() {} @SuppressWarnings("unused") public void addDialogListener(DialogListener dl) {} @SuppressWarnings("unused") public void addHelp(String url) {} @SuppressWarnings("unused") public void addMessage(String text) {} @SuppressWarnings("unused") public void addMessage(String text, Font font) {} @SuppressWarnings("unused") public void addPanel(Panel panel) {} @SuppressWarnings("unused") public void addPanel(Panel panel, int contraints, Insets insets) {} @SuppressWarnings("unused") public void addPreviewCheckbox(PlugInFilterRunner pfr) {} @SuppressWarnings("unused") public void addPreviewCheckbox(PlugInFilterRunner pfr, String label) {} @SuppressWarnings("unused") public void centerDialog(boolean b) {} public void enableYesNoCancel() {} @SuppressWarnings("unused") public void enableYesNoCancel(String yesLabel, String noLabel) {} public Button[] getButtons() { return null; } public Vector<?> getCheckboxes() { return null; } public Vector<?> getChoices() { return null; } public String getErrorMessage() { return errorMessage; } public Insets getInsets() { return null; } public Component getMessage() { return null; } public Vector<?> getNumericFields() { return null; } public Checkbox getPreviewCheckbox() { return null; } public Vector<?> getSliders() { return null; } public Vector<?> getStringFields() { return null; } public TextArea getTextArea1() { return null; } public TextArea getTextArea2() { return null; } public void hideCancelButton() {} @SuppressWarnings("unused") public void previewRunning(boolean isRunning) {} @SuppressWarnings("unused") public void setEchoChar(char echoChar) {} @SuppressWarnings("unused") public void setHelpLabel(String label) {} @SuppressWarnings("unused") public void setInsets(int top, int left, int bottom) {} @SuppressWarnings("unused") public void setOKLabel(String label) {} protected void setup() {} } }
35.077882
127
0.733037
36a0dfb24d458729c320a353902633c5b41a2103
498
package test; import org.apache.log4j.Logger; import org.junit.Test; public class Log4jTest { private Logger log = Logger.getLogger(Log4jTest.class); @Test public void logtest() { log.debug("===========debug Level============="); log.info("===========info Level============="); log.warn("============warn Level============"); log.error("===========error Level============="); log.error("hello {}, now time is {}. "); } }
22.636364
58
0.463855
bd33bc377d562abc611c884e1eb4d95abfba973a
1,563
/** * Copyright (c) 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v2.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v20.html * * Contributors: * IBM - Initial API and implementation */ package org.eclipse.emf.examples.extlibrary; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Employee</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.eclipse.emf.examples.extlibrary.Employee#getManager <em>Manager</em>}</li> * </ul> * * @see org.eclipse.emf.examples.extlibrary.EXTLibraryPackage#getEmployee() * @model * @generated */ public interface Employee extends Person { /** * Returns the value of the '<em><b>Manager</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Manager</em>' reference. * @see #setManager(Employee) * @see org.eclipse.emf.examples.extlibrary.EXTLibraryPackage#getEmployee_Manager() * @model * @generated */ Employee getManager(); /** * Sets the value of the '{@link org.eclipse.emf.examples.extlibrary.Employee#getManager <em>Manager</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Manager</em>' reference. * @see #getManager() * @generated */ void setManager(Employee value); } // Employee
28.418182
119
0.662188
a7bd8358c3891eab225c4523e7a648dca4473d59
182
package models; import java.util.List; //ViewModels public class HomeViewModel { //List of Symptoms public List<String> symptoms; //Patient info //public Patient patient; }
12.133333
30
0.736264
2e19181c4e1c74cf063358d5c3492e7c1d2e221a
3,390
/* * Copyright 2020 Jakob Hjelm (Komposten) * * This file is part of LeapJna. * * LeapJna is a free Java library: you can use, redistribute it and/or modify * it under the terms of the MIT license as written in the LICENSE file in the root * of this project. */ package komposten.leapjna.leapc.data; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.Structure.FieldOrder; /** * <p> * Holds an image from one of the Leap Motion Controller's cameras and related * information. * </p> */ @FieldOrder({ "properties", "matrix_version", "distortion_matrix", "data", "offset" }) public class LEAP_IMAGE extends Structure { /** The properties of the received image. */ public LEAP_IMAGE_PROPERTIES properties; /** * <p> * A version number for the distortion matrix. When the distortion matrix changes, this * number is updated. This number is guaranteed not to repeat for the lifetime of the * connection. This version number is also guaranteed to be distinct for each * perspective of an image. * </p> * <p> * This value is guaranteed to be nonzero if it is valid. * </p> * <p> * The distortion matrix only changes when the streaming device changes or when the * device orientation flips -- inverting the image and the distortion grid. Since * building a matrix to undistort an image can be a time-consuming task, you can * optimise the process by only rebuilding this matrix (or whatever data type you use to * correct image distortion) when the grid actually changes. * </p> */ public long matrix_version; /** * A pointer to the camera's distortion matrix. Use {@link #getMatrix()} to obtain the * actual matrix. */ public Pointer distortion_matrix; /** A pointer to the image data. Use {@link #getData()} to obtain the actual data. */ public Pointer data; /** * Offset, in bytes, from the beginning of the data pointer to the actual beginning of * the image data. */ public int offset; private byte[] imageData; private LEAP_DISTORTION_MATRIX matrixData; public LEAP_IMAGE() { super(ALIGN_NONE); } /** * <p> * The image data is not loaded from native memory until this method is called. This * means that the data might overridden or freed if this method is not called * immediately after receiving the <code>LEAP_IMAGE</code>. * </p> * <p> * After {@link #getData()} has been called once, successive calls will return * a cached array rather than load the data from native memory every time. * </p> * * @return The image data as a byte array. */ public byte[] getData() { if (imageData == null) { imageData = data.getByteArray(offset, properties.width * properties.height * properties.bpp); } return imageData; } /** * <p> * The first call to this method on a <code>LEAP_IMAGE</code> instance reads the * distortion matrix from memory and creates a {@link LEAP_DISTORTION_MATRIX} instance. * </p> * <p> * <b>NOTE</b>: For performance reasons it is best to only use this method if * {@link #matrix_version} has changed since you last read a distortion matrix! * </p> * * @return A {@link LEAP_DISTORTION_MATRIX} containing the matrix. */ public LEAP_DISTORTION_MATRIX getMatrix() { if (matrixData == null) { matrixData = new LEAP_DISTORTION_MATRIX(distortion_matrix); } return matrixData; } }
28.25
89
0.702655
b5c36dfa30528efed808e6f7d50f95264f9e3249
607
package com.jeeplus.weixin.mapper; import com.jeeplus.weixin.entities.UserInfoModel; public interface UserInfoModelMapper { int deleteByPrimaryKey(Integer recordid); int insert(UserInfoModel record); int insertSelective(UserInfoModel record); UserInfoModel selectByPrimaryKey(Integer recordid); int updateByPrimaryKeySelective(UserInfoModel record); int updateByPrimaryKeyWithBLOBs(UserInfoModel record); int updateByPrimaryKey(UserInfoModel record); UserInfoModel selectByPhoneNo(String phoneNo); UserInfoModel selectByOpenid(String openid); }
22.481481
58
0.775947
0c614e5d21aa175a110f1e4bd48eefbb168512db
612
package br.pucminas.periodo2.Grafica; /** * Impressora */ public class Impressora { protected final Tanque tanqueColorido; protected final Tanque tanquePB; public Impressora() { tanqueColorido = new TanqueColorido(); tanquePB = new TanquePretoBranco(); } public void imprimir(Documento d, Grafica g) { d.imprimir(g); } /** * @return the tanqueColorido */ public Tanque getTanqueColorido() { return tanqueColorido; } /** * @return the tanquePB */ public Tanque getTanquePB() { return tanquePB; } }
18.545455
50
0.607843
a1ed7cf23f0dacb00012385794284a52908c832e
19,332
/** * (c) 2016 uchicom */ package com.uchicom.tm.window; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GraphicsConfiguration; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.HeadlessException; import java.awt.Insets; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.swing.DefaultCellEditor; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import com.uchicom.tm.Constants; import com.uchicom.tm.action.AddProjectAction; import com.uchicom.tm.action.EditProjectAction; import com.uchicom.tm.action.RemoveProjectAction; import com.uchicom.tm.action.StartAction; import com.uchicom.tm.action.StopAction; import com.uchicom.tm.action.TaskConfigAction; import com.uchicom.tm.entity.Project; import com.uchicom.tm.entity.Record; import com.uchicom.tm.runnable.ScreenCaptureRunnable; import com.uchicom.tm.table.ListTableModel; import com.uchicom.tm.util.TimeUtil; /** * ファイルの保管場所を、案件名をキーにして保管することができる。 * 案件のフォルダを決定して、日付のフォルダを作成して、その中に、画像を格納する。 * 最初は一分後にキャプチャして、その後は指定時間毎にキャプチャを実行する。 * 新規作成や修正ようにダイアログを表示したほうがいいな * @author uchicom: Shigeki Uchiyama * */ public class TmFrame extends JFrame { private static SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // 画面コンポーネント private JComboBox<Project> projectComboBox = new JComboBox<>(); private JTextField taskTextField = new JTextField(); private JLabel startLabel = new JLabel("----/--/-- --:--"); private JLabel endLabel = new JLabel("----/--/-- --:--"); private JLabel timeLabel = new JLabel("--:--:--"); private JButton startButton = new JButton(new StartAction(this)); private JButton stopButton = new JButton(new StopAction(this)); private JLabel sumLabel = new JLabel(); private JLabel selectedSumLabel = new JLabel(); private JTable table; //データオブジェクト private Map<Project, Project> projectMap = new HashMap<>(); private Date start; private Date end; private DefaultComboBoxModel<Project> comboBoxModel = new DefaultComboBoxModel<>(); private List<Project> projectList = new ArrayList<>(); private List<Record> rowList = new ArrayList<>(); private ListTableModel model = new ListTableModel(rowList, 4); private ScreenCaptureRunnable runnable = new ScreenCaptureRunnable(1 * 1000); private Properties properties = new Properties(); private NotifyFrame frame; private File baseDir; /** * @throws HeadlessException */ public TmFrame() { super("作業時間管理"); initComponents(); } /** * */ private void initComponents() { setDefaultCloseOperation(DISPOSE_ON_CLOSE); initProperties(); initJMenuBar(); initProject(); setWindowPosition(this, Constants.PROP_KEY_WINDOW_TM_POSITION); setWindowState(this, Constants.PROP_KEY_WINDOW_TM_STATE); //案件リスト JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.insets = new Insets(10,5,10,5); panel.add(new JLabel("案件"), constraints); constraints.gridx = 1; constraints.gridwidth = 2; constraints.fill = GridBagConstraints.HORIZONTAL; panel.add(projectComboBox, constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridwidth = 1; constraints.gridx = 0; constraints.gridy = 1; panel.add(new JLabel("作業"), constraints); constraints.gridx = 1; constraints.gridwidth = 2; constraints.fill = GridBagConstraints.HORIZONTAL; panel.add(taskTextField, constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridy = 2; constraints.gridx = 0; constraints.gridwidth = 1; panel.add(new JLabel("開始"), constraints); constraints.gridx = 1; constraints.gridwidth = 2; panel.add(startLabel, constraints); constraints.gridy = 3; constraints.gridx = 0; constraints.gridwidth = 1; panel.add(new JLabel("終了"), constraints); constraints.gridx = 1; constraints.gridwidth = 2; panel.add(endLabel, constraints); constraints.gridy = 4; constraints.gridx = 0; constraints.gridwidth = 1; panel.add(new JLabel("時間"), constraints); constraints.gridx = 1; constraints.gridwidth = 2; panel.add(timeLabel, constraints); constraints.gridx = 1; constraints.gridy = 5; constraints.gridwidth = 1; panel.add(startButton, constraints); constraints.gridx = 2; panel.add(stopButton, constraints); TableColumnModel columnModel = new DefaultTableColumnModel(); TableColumn tableColumn = new TableColumn(0); tableColumn.setIdentifier(0); tableColumn.setHeaderValue("タスク"); tableColumn.setPreferredWidth(150); columnModel.addColumn(tableColumn); tableColumn = new TableColumn(1); tableColumn.setIdentifier(1); tableColumn.setHeaderValue("開始"); tableColumn.setPreferredWidth(120); columnModel.addColumn(tableColumn); tableColumn = new TableColumn(2); tableColumn.setIdentifier(2); tableColumn.setHeaderValue("終了"); tableColumn.setPreferredWidth(120); columnModel.addColumn(tableColumn); tableColumn = new TableColumn(3); tableColumn.setIdentifier(3); tableColumn.setHeaderValue("作業時間"); tableColumn.setPreferredWidth(60); JTextField textField = new JTextField(); textField.setEditable(false); tableColumn.setCellEditor(new DefaultCellEditor(textField)); columnModel.addColumn(tableColumn); table = new JTable(model, columnModel); table.getSelectionModel().addListSelectionListener((e) -> { System.out.println(e); if (!e.getValueIsAdjusting()) { select(); } }); table.getTableHeader().setReorderingAllowed(false); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); getContentPane().setLayout(new BorderLayout()); getContentPane().add(panel, BorderLayout.NORTH); getContentPane().add(new JScrollPane(table), BorderLayout.CENTER); JPanel southPanel = new JPanel(new GridLayout(1, 2)); southPanel.add(sumLabel); southPanel.add(selectedSumLabel); getContentPane().add(southPanel, BorderLayout.SOUTH); //開始、終了ボタン //画面撮影 stopButton.setEnabled(false); initView(getSelectedProject()); addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent we) { if (start != null) { stop(); } } @Override public void windowClosing(WindowEvent we) { if (TmFrame.this.getExtendedState() == JFrame.NORMAL) { // 画面の位置を保持する storeWindowPosition(TmFrame.this, Constants.PROP_KEY_WINDOW_TM_POSITION); } else { storeWindowState(TmFrame.this, Constants.PROP_KEY_WINDOW_TM_STATE); } storeProperties(); } }); addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent ce) { if (getExtendedState() == JFrame.NORMAL) { storeWindowPosition(TmFrame.this, Constants.PROP_KEY_WINDOW_TM_POSITION); } } @Override public void componentResized(ComponentEvent ce) { if (getExtendedState() == JFrame.NORMAL) { storeWindowPosition(TmFrame.this, Constants.PROP_KEY_WINDOW_TM_POSITION); } } }); projectComboBox.addItemListener(new ItemListener(){ @Override public void itemStateChanged(ItemEvent ie) { if (ie.getItem() != null) { Project project = (Project) ie.getItem(); initView(project); } } }); setAlwaysOnTop(true); //常に全面に表示 pack(); } private void select() { System.out.println("select"); int[] rows = table.getSelectedRows(); List<Record> recordList = model.getRowList(); long sum = 0; for (int i : rows) { sum += recordList.get(i).getTime(); } selectedSumLabel.setText(TimeUtil.getDispElapsedTime(sum)); System.out.println(selectedSumLabel.getText()); } private void initView(Project project) { if (project == null) return; startLabel.setText("----/--/-- --:--"); endLabel.setText("----/--/-- --:--"); timeLabel.setText("--:--:--"); model.setRowList(project.getRecordList()); if (project.getRecordList() != null && project.getRecordList().size() > 0) { taskTextField.setText(project.getRecordList().get(project.getRecordList().size() - 1).getTaskName()); } else { taskTextField.setText(""); } sumLabel.setText(TimeUtil.getDispElapsedTime(project.calculateSum())); } private void initJMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("案件"); menu.add(new JMenuItem(new AddProjectAction(this))); menu.add(new JMenuItem(new RemoveProjectAction(this))); menu.add(new JMenuItem(new EditProjectAction(this))); menu.addSeparator(); menu.add(new JMenuItem(new TaskConfigAction(this))); menuBar.add(menu); setJMenuBar(menuBar); } private void initProject() { baseDir = new File(properties.getProperty("dir")); File[] projectDirs = baseDir.listFiles(); projectList.clear(); for (File projectDir : projectDirs) { Project project = new Project(projectDir); initHistory(project, projectDir); projectMap.put(project, project); projectList.add(project); } projectList.sort(new Comparator<Project>() { @Override public int compare(Project arg0, Project arg1) { long ret = arg0.getFile().lastModified() - arg1.getFile().lastModified(); if (ret > 0) { return -1; } else if (ret < 0) { return 1; } else { return 0; } } }); comboBoxModel.removeAllElements(); projectList.forEach((p)->{ comboBoxModel.addElement(p); }); projectComboBox.setModel(comboBoxModel); } /** * 過去の作業データ生成. * @param project * @param projectDir */ private void initHistory(Project project, File projectDir) { for (File file : projectDir.listFiles()) { String name = file.getName(); int splitIndex = name.indexOf("_"); if (splitIndex < 0) { continue; } String taskName = name.substring(0, splitIndex); int splitIndex2 = name.indexOf("_", splitIndex + 1); if (splitIndex2 < 0) { continue; } String start = name.substring(splitIndex + 1, splitIndex2); Date startDate = null; if (!"".equals(start)) { startDate = new Date(Long.valueOf(start)); } String end = name.substring(splitIndex2 + 1); Date endDate = null; if (!"".equals(end)) { endDate = new Date(Long.valueOf(end)); } Record record = new Record(startDate, endDate, taskName); project.add(record); } project.getRecordList().sort(new Comparator<Record>() { @Override public int compare(Record arg0, Record arg1) { return arg0.compareTo(arg1); } }); } /** * @param gc */ public TmFrame(GraphicsConfiguration gc) { super(gc); } /** * @param title * @throws HeadlessException */ public TmFrame(String title) throws HeadlessException { super(title); } /** * @param title * @param gc */ public TmFrame(String title, GraphicsConfiguration gc) { super(title, gc); } /** * 測定停止 */ public void stop() { try { end = new Date(); endLabel.setText(format.format(end)); Project project = getSelectedProject(); String taskName = getTaskName(); Record record = new Record(start, end, taskName); project.add(record); sumLabel.setText(TimeUtil.getDispElapsedTime(project.calculateSum())); timeLabel.setText(record.getDispTime()); frame.dispose(); frame = null; model.fileRow(); // runnable.setAlive(false); File recordDir = new File(baseDir, project.getId() + "_" + project.getName() + "/" + taskName + "_" + start.getTime()); File renameDir = new File(baseDir, project.getId() + "_" + project.getName() + "/" + taskName + "_" + start.getTime() + "_" + end.getTime()); recordDir.renameTo(renameDir); } finally { projectComboBox.setEnabled(true); taskTextField.setEnabled(true); stopButton.setEnabled(false); startButton.setEnabled(true); start = null; end = null; setAlwaysOnTop(true); //常に全面に表示 } } /** * 測定開始 */ public void start() { if ("".equals(getTaskName())) { JOptionPane.showMessageDialog(this, "タスクを入力してください."); return; } try { start = new Date(); endLabel.setText("----/--/-- --:--"); timeLabel.setText("--:--:--"); startLabel.setText(format.format(start)); runnable.setAlive(true); Project project = getSelectedProject(); runnable.setProject(project); File imageDir = new File(baseDir, project.getId() + "_" + project.getName() + "/" + getTaskName() + "_" + start.getTime()); runnable.setImageDir(imageDir); frame = new NotifyFrame(); frame.startNotify(); // Thread thread = new Thread(runnable); // thread.setDaemon(true); // thread.start(); } finally { projectComboBox.setEnabled(false); taskTextField.setEnabled(false); stopButton.setEnabled(true); startButton.setEnabled(false); setAlwaysOnTop(false); //常に全面に表示 } } /** * 案件を追加します */ public void add() { String projectName = JOptionPane.showInputDialog("案件名"); Project project = createProject(projectName); projectMap.put(project, project); projectList.add(project); projectList.sort(new Comparator<Project>() { @Override public int compare(Project arg0, Project arg1) { long ret = arg0.getFile().lastModified() - arg1.getFile().lastModified(); if (ret > 0) { return -1; } else if (ret < 0) { return 1; } else { return 0; } } }); comboBoxModel.removeAllElements(); projectList.forEach((p)->{ comboBoxModel.addElement(p); }); taskTextField.setText(""); } private File createDir(String dirName) { File dir = new File(properties.getProperty("dir"), dirName); if (!dir.exists()) { dir.mkdirs(); } return dir; } public void edit() { Project project = getSelectedProject(); File dir = new File(properties.getProperty("dir"), project.getId() + "_" + project.getName()); String projectName = JOptionPane.showInputDialog(this, "案件名", project.getName()); if (projectName != null) { if ("".equals(projectName)) { JOptionPane.showMessageDialog(this, "案件名を入力してください"); } else { File renameDir = new File(properties.getProperty("dir"), project.getId() + "_" + projectName); if (dir.renameTo(renameDir)) { project.setName(projectName); } } } } /** * 案件名を登録します * @param projectName */ private Project createProject(String projectName) { return new Project(createDir(System.currentTimeMillis() + "_" + projectName)); } public void remove() { Project project = getSelectedProject(); removeProject(project); } public void config() { Project task = comboBoxModel.getElementAt(projectComboBox.getSelectedIndex()); TaskConfigDialog dialog = new TaskConfigDialog(this, task); dialog.pack(); dialog.setVisible(true); } /** * 案件を削除します、データは削除されます。 */ private void removeProject(Project project) { int result = JOptionPane.showConfirmDialog(this, project.getName() + "案件を削除してもよろしいですか?\n削除したものは復元できません。", "情報", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.OK_OPTION) { File projectDir = new File(baseDir, project.getId() + "_" + project.getName()); deleteDir(projectDir); comboBoxModel.removeElement(project); } } private Project getSelectedProject() { return comboBoxModel.getElementAt(projectComboBox.getSelectedIndex()); } private String getTaskName() { return taskTextField.getText(); } private void deleteDir(File file) { File[] files = file.listFiles(); for (File child : files) { if (child.isDirectory()) { deleteDir(child); } else { child.delete(); } } file.delete(); } /** * 画面の位置をプロパティに設定する。 * * @param frame * @param key */ private void storeWindowPosition(JFrame frame, String key) { String value = frame.getLocation().x + Constants.PROP_SPLIT_CHAR + frame.getLocation().y + Constants.PROP_SPLIT_CHAR + frame.getWidth() + Constants.PROP_SPLIT_CHAR + frame.getHeight() + Constants.PROP_SPLIT_CHAR; properties.setProperty(key, value); } /** * 画面の位置をプロパティに設定する。 * * @param frame * @param key */ private void storeWindowState(JFrame frame, String key) { String value = frame.getState() + Constants.PROP_SPLIT_CHAR + frame.getExtendedState(); properties.setProperty(key, value); } /** * 画面のサイズをプロパティから設定する。 * * @param frame * @param key */ public void setWindowPosition(JFrame frame, String key) { if (properties.containsKey(key)) { String initPoint = properties.getProperty(key); String[] points = initPoint.split(Constants.PROP_SPLIT_CHAR); if (points.length > 3) { frame.setLocation(Integer.parseInt(points[0]), Integer.parseInt(points[1])); frame.setPreferredSize(new Dimension(Integer.parseInt(points[2]), Integer.parseInt(points[3]))); } } } public void setWindowState(JFrame frame, String key) { if (properties.containsKey(key)) { String initPoint = properties.getProperty(key); String[] points = initPoint.split(Constants.PROP_SPLIT_CHAR); if (points.length > 1) { frame.setState(Integer.parseInt(points[0])); frame.setExtendedState(Integer.parseInt(points[1])); } } } /** * */ private void initProperties() { if (Constants.CONF_FILE.exists() && Constants.CONF_FILE.isFile()) { try (FileInputStream fis = new FileInputStream(Constants.CONF_FILE);) { properties.load(fis); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } private void storeProperties() { try { if (!Constants.CONF_FILE.exists()) { Constants.CONF_FILE.getParentFile().mkdirs(); Constants.CONF_FILE.createNewFile(); } try (FileOutputStream fos = new FileOutputStream(Constants.CONF_FILE);) { properties.store(fos, Constants.APP_NAME + " Ver" + Constants.VERSION); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } }
29.741538
145
0.681513
7d7a7e7acab74d03928cd09d9b6115fe7bdc36af
360
package com.codingdojo.authentication.repositories; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.codingdojo.authentication.models.Team; @Repository public interface TeamRepository extends CrudRepository<Team, Long> { List<Team> findAllByOrderByIdAsc(); }
30
68
0.833333
d0ee8a9c9dc252a2c0c6c4c5c1768ff8c5ad1fcc
1,455
/* * Copyright 2015 The SageTV 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 sage; /* * This represents a user interface instance which may be remote or local. This is implemented * by the UIManaged for local UIs and by an inner class of SageTVConnection for remote UIs */ public interface UIClient { public static final int LOCAL = 1; public static final int REMOTE_CLIENT = 2; public static final int REMOTE_UI = 3; public String getFullUIClientName(); public String getLocalUIClientName(); // Hooks processed through here are NOT rethreaded public Object processUIClientHook(String hookName, Object[] hookVars); public int getUIClientType(); // This is the original clientName we used to use and is specific to a SageTVClient connection public String getUIClientHostname(); // Allows to query the client for capabilities public String getCapability(String capability); }
38.289474
96
0.760137
14d145cbdd86165c8c820976c257f275d3057b3f
709
package io.smallrye.stork.test; import io.smallrye.stork.api.ServiceDiscovery; import io.smallrye.stork.api.config.ServiceConfig; import io.smallrye.stork.api.config.ServiceDiscoveryType; import io.smallrye.stork.spi.ServiceDiscoveryProvider; import io.smallrye.stork.spi.StorkInfrastructure; @ServiceDiscoveryType("empty") public class EmptyServiceDiscoveryProvider implements ServiceDiscoveryProvider<EmptyServiceDiscoveryProviderConfiguration> { @Override public ServiceDiscovery createServiceDiscovery(EmptyServiceDiscoveryProviderConfiguration config, String serviceName, ServiceConfig serviceConfig, StorkInfrastructure storkInfrastructure) { return null; } }
37.315789
121
0.820874
460484d9c97131df0649f72ab7f0a8613cea2bfd
3,873
package io.smartlogic.smartchat.api; import android.content.Context; import android.util.Base64; import android.webkit.MimeTypeMap; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class SmartChatDownloader { private Context context; private String encodedPrivateKey; private String fileUrl; public SmartChatDownloader(Context context, String encodedPrivateKey, String fileUrl) { this.context = context; this.encodedPrivateKey = encodedPrivateKey; this.fileUrl = fileUrl; } public File download() { PrivateKey privateKey = RSAEncryption.loadPrivateKeyFromString(encodedPrivateKey); try { HttpClient client = new DefaultHttpClient(); HttpGet s3File = new HttpGet(fileUrl); HttpResponse response = client.execute(s3File); String base64EncryptedAesKey = null; String base64EncryptedAesIv = null; for (Header header : response.getAllHeaders()) { if (header.getName().equals("Encrypted-Aes-Key")) { base64EncryptedAesKey = header.getValue(); } else if (header.getName().equals("Encrypted-Aes-Iv")) { base64EncryptedAesIv = header.getValue(); } } byte[] encryptedAesKey = Base64.decode(base64EncryptedAesKey, Base64.DEFAULT); byte[] encryptedAesIv = Base64.decode(base64EncryptedAesIv, Base64.DEFAULT); // ECB is there for java's sake, it doesn't actually get used. Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsa.init(Cipher.DECRYPT_MODE, privateKey); SecretKey aesKey = new SecretKeySpec(rsa.doFinal(encryptedAesKey), "AES"); IvParameterSpec ips = new IvParameterSpec(rsa.doFinal(encryptedAesIv)); Cipher aes = Cipher.getInstance("AES/CBC/NoPadding"); aes.init(Cipher.DECRYPT_MODE, aesKey, ips); byte[] data = EntityUtils.toByteArray(response.getEntity()); byte[] decrypted_data = aes.doFinal(data); String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl); File pictureFile = File.createTempFile("smartchat", "." + extension, context.getExternalCacheDir()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pictureFile)); bos.write(decrypted_data); bos.flush(); bos.close(); return pictureFile; } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } return null; } }
36.885714
112
0.674671
5d46abfb0fef6759302dabdaaed615de4caeb8d8
1,261
package com.atguigu.gulimall.product.config; import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author dengzhiming * @date 2020/10/18 14:59 */ @Configuration public class MybatisConfig { /** * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 关闭缓存 避免缓存出现问题 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(); // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false paginationInnerInterceptor.setOverflow(true); // 设置最大单页限制数量,默认 500 条,-1 不受限制 paginationInnerInterceptor.setMaxLimit(500L); interceptor.addInnerInterceptor(paginationInnerInterceptor); return interceptor; } @Bean public ConfigurationCustomizer configurationCustomizer() { return configuration -> configuration.setCacheEnabled(false); } }
36.028571
97
0.767645
a0ff4fd69e57c6f13de7c81455203f25c9fa5337
737
/* ###################################################################################### ## ## ## (c) 2006-2012 Cable Television Laboratories, Inc. All rights reserved. Any use ## ## of this documentation/package is subject to the terms and conditions of the ## ## CableLabs License provided to you on download of the documentation/package. ## ## ## ###################################################################################### */ package com.cablelabs.stun; public interface RTPListener { public void processEvent(RawData rawData); }
46.0625
87
0.371777
f9ac74fcc8d2cb2e777aaf620a4a6b4afcf4f55a
1,389
package com.example.control_panel; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MoveCalculatorTest { @Test public void testScrollTable() { int[][] moveTable = new int[][]{ {0, -100, -200, -300, -400}, // i = 0 {100, 0, -100, -200, -300}, // i = 1 {200, 100, -200, -100, -200}, // i = 2 {300, 200, 100, 0, -100}, // i = 3 {400, 300, 200, 100, 0} // i = 4 }; int[][] scrollTable = new int[][] { {0, -100, 0, 100, 200}, // i = 0 {-200, 0, 0, 100, 200}, // i = 1 {-200, -100, 0, 100, 200}, // i = 2 {-200, -100, 0, 0, 200}, // i = 3 {-200, -100, 0, 100, 200} // i = 4 }; for (int i=0; i<5; i++) { for (int j=0; j<5; j++) { if (i != j) { ModeSwitchScrollView.MoveCalculator calculator = new ModeSwitchScrollView.MoveCalculator(i, j, 100); calculator.invoke(); String message = String.format("i=%d j=%d", i, j); assertEquals("Move = " + message, moveTable[i][j], calculator.getMoveSize()); assertEquals("Scroll = " + message,scrollTable[i][j], calculator.getScrollX()); } } } } }
37.540541
120
0.431965
b4072ecf6fab6c5d743870f3df292d6b7eb8d803
9,978
package ch.swaechter.libreshare.web.components.account; import ch.swaechter.libreshare.web.components.Converter; import ch.swaechter.libreshare.web.components.account.dto.*; import ch.swaechter.libreshare.web.components.account.table.Account; import ch.swaechter.libreshare.web.components.settings.SettingsService; import ch.swaechter.libreshare.web.configuration.exceptionhandling.ServerException; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import io.micronaut.context.annotation.Context; import org.mindrot.jbcrypt.BCrypt; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.UUID; /** * Manage all accounts and issue/check JWT tokens. * * @author Simon Wächter */ @Context public class AccountService { /** * Name used to issue JWT tokens. */ private static final String JWT_ISSUER = "LibreShare"; /** * Validity duration of a JWT token in milliseconds. */ private static final long JWT_VALIDITY_IN_MS = 120 * 60 * 1000; /** * Settings service used to get the settings and the server secret. */ private final SettingsService settingsService; /** * Account repository to interact with the SQL database. */ private final AccountRepository accountRepository; /** * Converter to convert DTO classes. */ private final Converter converter; /** * Create a new account service. * * @param settingsService Settings service used to get the settings and the server secret * @param accountRepository Account repository to interact with the SQL database * @param converter Converter to convert DTO classes */ public AccountService(SettingsService settingsService, AccountRepository accountRepository, Converter converter) { this.settingsService = settingsService; this.accountRepository = accountRepository; this.converter = converter; } /** * Create a new account. * * @param createAccountDto Account to create * @return Created account * @throws ServerException Exception in case of a validation/database problem */ public ReadAccountDto createAccount(CreateAccountDto createAccountDto) throws ServerException { Optional<Account> optionalAccount = accountRepository.findByUsername(createAccountDto.username()); if (optionalAccount.isPresent()) { throw new RuntimeException("An account with this name does already exist"); } UUID id = UUID.randomUUID(); String username = createAccountDto.username(); String emailAddress = createAccountDto.emailAddress(); String passwordHash = getPasswordHash(createAccountDto.plaintextPassword()); Account account = new Account(id, username, emailAddress, passwordHash); accountRepository.save(account); return new ReadAccountDto(id, username, emailAddress); } /** * Get all accounts. * * @return All accounts */ public List<ReadAccountDto> getAccounts() { List<Account> accountList = accountRepository.findAllOrderByUsername(); return converter.accountsToReadAccountDtos(accountList); } /** * Get an account by ID. * * @param id ID of the account * @return Optional account * @throws ServerException Exception in case the account was not found or a database problem */ public ReadAccountDto getAccountById(UUID id) throws ServerException { Optional<Account> optionalAccount = accountRepository.findById(id); if (optionalAccount.isEmpty()) { throw new ServerException("Unable to find an account for the given ID"); } Account account = optionalAccount.get(); return converter.accountToReadAccountDto(account); } /** * Update an account by ID: * * @param id ID of the account * @param updateAccountDto Updated account * @throws ServerException Exception in case the account was not found or a database problem */ public void updateAccount(UUID id, UpdateAccountDto updateAccountDto) throws ServerException { Optional<Account> optionalAccountById = accountRepository.findById(id); if (optionalAccountById.isEmpty()) { throw new ServerException("Unable to find an account for the given ID"); } Optional<Account> optionalAccountByUserName = accountRepository.findByUsername(updateAccountDto.username()); if (optionalAccountByUserName.isPresent() && !id.equals(optionalAccountByUserName.get().getId())) { throw new ServerException("Another account with this name already exists"); } Account existingAccount = optionalAccountById.get(); Account account = converter.updateAccountDtoToAccount(updateAccountDto); account.setId(existingAccount.getId()); account.setPasswordHash(existingAccount.getPasswordHash()); accountRepository.update(account); } /** * Change the password of an account. * * @param id ID of the account * @param changePasswordDto Changed password * @throws ServerException Exception in case the account was not found or a database problem */ public void changeAccountPassword(UUID id, ChangePasswordDto changePasswordDto) throws ServerException { Optional<Account> optionalAccount = accountRepository.findById(id); if (optionalAccount.isEmpty()) { throw new ServerException("Unable to find an account for the given ID"); } Account account = optionalAccount.get(); account.setPasswordHash(getPasswordHash(changePasswordDto.plaintextPassword())); accountRepository.update(account); } /** * Delete an account by ID: * * @param id ID of the account * @throws ServerException Exception in case the account was not found or a database problem */ public void deleteAccountById(UUID id) throws ServerException { Optional<Account> optionalAccount = accountRepository.findById(id); if (optionalAccount.isEmpty()) { throw new ServerException("Unable to find an account for the given ID"); } List<Account> accountList = accountRepository.findAllOrderByUsername(); if (accountList.size() == 1) { throw new ServerException("Unable to delete the last account"); } accountRepository.deleteById(id); } /** * Get the number of accounts. * * @return Number of accounts */ public long getNumberOfAccounts() { return accountRepository.count(); } /** * Perform a login via username and password to get a new JWT token. * * @param authenticationDto Username and password * @return Optional JWT token if the login was successful */ public Optional<TokenDto> login(AuthenticationDto authenticationDto) { // Get the account Optional<Account> optionalAccount = accountRepository.findByUsername(authenticationDto.username()); if (optionalAccount.isEmpty()) { return Optional.empty(); } Account account = optionalAccount.get(); // Check the password hash if (!isPasswordHashMatching(authenticationDto.password(), account.getPasswordHash())) { return Optional.empty(); } // Calculate the expiration date Date nowDate = new Date(); Date expirationDate = new Date(nowDate.getTime() + JWT_VALIDITY_IN_MS); // Issue the token String secret = settingsService.getSettings().getServer().getSecret(); Algorithm algorithm = Algorithm.HMAC512(secret.getBytes(StandardCharsets.UTF_8)); String token = JWT.create().withIssuer(JWT_ISSUER).withSubject(account.getId().toString()).withExpiresAt(expirationDate).sign(algorithm); return Optional.of(new TokenDto(token)); } /** * Check if a JWT token is valid (Cryptographically and not expired). * * @param token JWT token * @return Status of the action or false in case of an exception */ public boolean isValidToken(String token) { try { String secret = settingsService.getSettings().getServer().getSecret(); Algorithm algorithm = Algorithm.HMAC512(secret); JWTVerifier verifier = JWT.require(algorithm).withIssuer(JWT_ISSUER).build(); verifier.verify(token); return true; } catch (Exception exception) { return false; } } /** * Get the subject from a JWT token. * * @param token JWT token * @return JWT subject */ public String getSubject(String token) { String secret = settingsService.getSettings().getServer().getSecret(); Algorithm algorithm = Algorithm.HMAC512(secret); JWTVerifier verifier = JWT.require(algorithm).withIssuer(JWT_ISSUER).build(); DecodedJWT decodedJwt = verifier.verify(token); return decodedJwt.getSubject(); } /** * Generate a password hash of the raw password. * * @param rawPassword Raw password to hash * @return Hashed output value */ public String getPasswordHash(String rawPassword) { return BCrypt.hashpw(rawPassword, BCrypt.gensalt()); } /** * Check if the hashing of a raw password results in the password hash * * @param rawPassword Raw password * @param hashedPassword Hash of the password the value is compared against * @return Status of the check */ private boolean isPasswordHashMatching(String rawPassword, String hashedPassword) { return BCrypt.checkpw(rawPassword, hashedPassword); } }
35.763441
145
0.678693
1db77b9b5e4cced18542473fe76492b7c28e40cd
3,515
package de.pascaldierich.watchdog.ui.adapter; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import de.pascaldierich.model.domainmodels.Observable; import de.pascaldierich.watchdog.R; import de.pascaldierich.watchdog.ui.Converter; /** * Adapter for RecyclerView to present the Observables */ public class ObservablesContainerAdapter extends RecyclerView.Adapter<ObservablesContainerAdapter.ViewHolder> { private Context mContext; private ArrayList<Observable> mItems; private ObservablesContainerAdapter.AdapterCallback mCallback; public ObservablesContainerAdapter(Context context, ArrayList<Observable> items, ObservablesContainerAdapter.AdapterCallback callback) { mContext = context; mItems = items; mCallback = callback; } public void setItems(ArrayList<Observable> items) { mItems = items; notifyDataSetChanged(); } public void addItems(ArrayList<Observable> items) { mItems.addAll(items); notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_observable_big, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { Observable item = mItems.get(position); holder.vDisplayName.setText(item.getDisplayName()); holder.vIconYouTube.setImageDrawable(mContext.getDrawable(R.drawable.icon_youtube_small)); if (item.getGotThumbnail()) { try { holder.vThumbnail.setImageBitmap( Converter.getBitmap(item.getThumbnail())); } catch (NullPointerException npe) { // just in case there is no boolean set } } holder.vLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Callback to MainActivity mCallback.onCardViewClick(holder.getAdapterPosition()); } }); } @Override public int getItemCount() { if (mItems == null) return -1; else return mItems.size(); } static class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.layout_observable_big) CardView vLayout; @BindView(R.id.layoutObservable_thumbnail) ImageView vThumbnail; @BindView(R.id.layoutObservable_displayName) TextView vDisplayName; @BindView(R.id.layoutObservable_iconPreview_youtube) ImageView vIconYouTube; ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } /** * Interface which got implemented by fragment.main.Presenter (ObservableListFragment's Presenter). */ public interface AdapterCallback { void onCardViewClick(int position); } }
31.666667
111
0.652347
a017194c685a80ece8c904a1d24cc92752881a04
828
package ru.parsentev.models; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO: comment * * @author parsentev * @since 08.07.2016 */ public class User { private int id; private String name; public User(int id, String name) { this.id = id; this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (id != user.id) return false; if (name != null ? !name.equals(user.name) : user.name != null) return false; return true; } @Override public int hashCode() { int result = id; result = 31 * result + (name != null ? name.hashCode() : 0); return result; } }
20.195122
85
0.559179
ee225cab1b3e555f7527730a3ee3e01ef6ca9184
573
package com.github.grantjforrester.uservice.starter.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Service; @Service public class HelloService { private static final Logger LOG = LoggerFactory.getLogger(HelloService.class); @Secured("ROLE_HelloRole") public String readHello() { LOG.trace("Parameters: none"); String hello = "Hello from service"; LOG.trace("Returning: {}", hello); return hello; } }
26.045455
82
0.726003
f2f1daad5159eadc060dffd1d05c9e295ebab1b9
4,217
package com.qi.richtexteditor.controller; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import com.qi.richtexteditor.common.result.FileUploadErrorInfoEnum; import com.qi.richtexteditor.common.result.GlobalErrorInfoException; import com.qi.richtexteditor.common.result.UploadResultBody; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author :qixianchuan * @date :Created in 2019-08-20 10:43 * @description:WangEditorController <br/> * github: https://github.com/wangfupeng1988/wangEditor/ * 用户手册:https://www.kancloud.cn/wangfupeng/wangeditor3 * @modified By: * @version: $version$ */ @Controller public class WangEditorController { @Value("${web.upload.path}") private String UPLOADED_FOLDER; @GetMapping("/") public String index() { return "wangEditor"; } @GetMapping("/getContent") public String getContent() { return "getContent"; } /** * 上传文件到服务器 **/ @GetMapping("/uploadPicturesToServer") public String uploadPicturesToServer() { return "uploadPicturesToServer"; } @PostMapping("/upload") @ResponseBody public UploadResultBody upload(@RequestParam("photo") List<MultipartFile> list) throws GlobalErrorInfoException { Integer errno = 0; List<String> urls = new ArrayList<>(); UploadResultBody uploadResultBody = new UploadResultBody(); if (list.isEmpty()) { errno = 1; throw new GlobalErrorInfoException(FileUploadErrorInfoEnum.PARAMS_NO_COMPLETE); } for (MultipartFile file : list) { try { String now = DateUtil.format(new Date(), "yyyyMMddHHmmss"); //为防止图片名称一样产生的覆盖问题,对图片重新命名 boolean exist = FileUtil.exist(UPLOADED_FOLDER); if (!exist) { FileUtil.mkdir(UPLOADED_FOLDER); } String newFileName = now + file.getOriginalFilename(); File targetFile = new File(UPLOADED_FOLDER, newFileName); BufferedOutputStream out1 = new BufferedOutputStream(new FileOutputStream(targetFile)); out1.write(file.getBytes()); out1.flush(); out1.close(); if (targetFile.exists()) { System.out.println("文件已经存在"); } String url = newFileName; urls.add(url); } catch (IOException e) { e.printStackTrace(); } } uploadResultBody.setErrno(errno); uploadResultBody.setData(urls); return uploadResultBody; } } // /** // * 富文本编辑器中上传图片功能 // * @param list // * @return // */ // @PostMapping(value = "/editor/upload") // public Map<String, Object> upload(@RequestParam("file") List<MultipartFile> list) { // // Integer errno = 0; // List<String> urls = new ArrayList<>(); // Map<String, Object> map = new HashMap<>(2); // // if (list.size() == 0) { // errno = 1; // } // // for (MultipartFile file : list) { // // 此处调用自己的上传文件方法 // String url = fileService.putObjectToOss(file); // if(Strings.notEmpty(url)) { // logger.debug("富文本编辑器上传图片成功,文件名:{},url:{}", file.getOriginalFilename(), url); // urls.add(url); // } else { // logger.debug("富文本编辑器上传图片失败,文件名:{}", file.getOriginalFilename()); // errno = 2; // } // } // // map.put("errno", errno); // map.put("data", urls); // return map; // }
32.945313
117
0.611809
7c4530f7760187050838f35e4395173fdd60c023
4,366
/* * Copyright 2020 Daniele Moro <[email protected]> * Davide Sanvito <[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 org.polimi.flowblaze.cli; import com.google.common.collect.Lists; import org.apache.karaf.shell.api.action.Argument; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.onosproject.cli.AbstractShellCommand; import org.polimi.flowblaze.EfsmCondition; import org.polimi.flowblaze.FlowblazeService; import java.util.List; @Service @Command(scope = "flowblaze", name = "set-conditions", description = "Setup EFSM conditions") public class SetConditions extends AbstractShellCommand { @Argument(index = 0, name = "operation1", description = "1st Operation") String operation0 = null; @Argument(index = 1, name = "op1_1", description = "1st Operand 1") String op10 = null; @Argument(index = 2, name = "op2_1", description = "1st Operand 2") String op20 = null; @Argument(index = 3, name = "const_op1_1", description = "1st Const Operand 1") int constOp10 = -1; @Argument(index = 4, name = "const_op2_1", description = "1st Const Operand 2") int constOp20 = -1; @Argument(index = 5, name = "operation1", description = "2nd Operation") String operation1 = null; @Argument(index = 6, name = "op1_1", description = "2nd Operand 1") String op11 = null; @Argument(index = 7, name = "op2_1", description = "2nd Operand 2") String op21 = null; @Argument(index = 8, name = "const_op1_1", description = "2nd Const Operand 1") int constOp11 = -1; @Argument(index = 9, name = "const_op2_1", description = "2nd Const Operand 2") int constOp21 = -1; @Argument(index = 10, name = "operation1", description = "3rd Operation") String operation2 = null; @Argument(index = 11, name = "op1_1", description = "3rd Operand 1") String op12 = null; @Argument(index = 12, name = "op2_1", description = "3rd Operand 2") String op22 = null; @Argument(index = 13, name = "const_op1_1", description = "3rd Const Operand 1") int constOp12 = -1; @Argument(index = 14, name = "const_op2_1", description = "3rd Const Operand 2") int constOp22 = -1; @Argument(index = 15, name = "operation1", description = "4th Operation") String operation3 = null; @Argument(index = 16, name = "op1_1", description = "4th Operand 1") String op13 = null; @Argument(index = 17, name = "op2_1", description = "4th Operand 2") String op23 = null; @Argument(index = 18, name = "const_op1_1", description = "4th Const Operand 1") int constOp13 = -1; @Argument(index = 19, name = "const_op2_1", description = "4th Const Operand 2") int constOp23 = -1; @Override protected void doExecute() throws Exception { List<EfsmCondition> conditions = Lists.newArrayList(); conditions.add(getEfsmCondition(operation0, op10, op20, constOp10, constOp20)); conditions.add(getEfsmCondition(operation1, op11, op21, constOp11, constOp21)); conditions.add(getEfsmCondition(operation2, op12, op22, constOp12, constOp22)); conditions.add(getEfsmCondition(operation3, op13, op23, constOp13, constOp23)); FlowblazeService flowblazeService = get(FlowblazeService.class); flowblazeService.setupConditions(conditions); } private EfsmCondition getEfsmCondition( String operation, String op1, String op2, int constOp1, int constOp2) { if (operation == null || op1 == null || op2 == null) { return EfsmCondition.defaultEfsmCondition(); } return new EfsmCondition(EfsmCondition.Operation.valueOf(operation), op1, op2, constOp1, constOp2); } }
36.383333
87
0.67705
8de85a7e32a4f5c1a835fe2661da34fa1f9a654b
2,608
package gui.dialogitems; import gui.I_ContainerView; import gui.I_SimpleView; import gui.renders.I_Render; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Point2D; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.CheckBox; import javafx.scene.control.TextField; import javafx.scene.paint.Color; import javafx.scene.text.Font; public class OmCheckbox extends CheckBox implements I_Widget { public OmCheckbox (String text, boolean ckecked, EventHandler<ActionEvent> fun) { setText(text); setSelected(ckecked); setOnAction(fun); } @Override public void omSetEnabled(boolean bool){ setDisable (bool); } @Override public boolean omGetEnabled(){ return isDisabled (); } @Override public Point2D omViewSize() { return new Point2D (prefWidth(-1), prefHeight(-1)); } @Override public void omSetViewSize(double w, double h) { setPrefWidth(w); setPrefHeight(h); } @Override public Point2D omViewPosition() { return new Point2D (getLayoutX(), getLayoutY()); } @Override public void omSetViewPosition(double x, double y) { relocate (x,y); } @Override public void callAction() { } @Override public Color omGetBackground() { // TODO Auto-generated method stub return null; } @Override public void omSetBackground(Color color) { // TODO Auto-generated method stub } @Override public Font omGetFont() { // TODO Auto-generated method stub return null; } @Override public void omSetFont(Font font) { // TODO Auto-generated method stub } @Override public Cursor omGetCursor() { // TODO Auto-generated method stub return null; } @Override public void omSetCursor(Cursor cursor) { // TODO Auto-generated method stub } @Override public I_ContainerView omViewContainer() { // TODO Auto-generated method stub return (I_ContainerView) getParent(); } ////////////////////////////////////////////// public void omSetCheck (boolean val) { setSelected(val); } public boolean omIsSelected () { return isSelected(); } public void omSetText (String str) { setText(str); } public String omGetText () { return getText(); } @Override public void omUpdateView(boolean changedObject_p) { // TODO Auto-generated method stub } @Override public void omViewDrawContents(I_Render r) { // TODO Auto-generated method stub } @Override public I_SimpleView getPaneWithPoint(double x, double y) { // TODO Auto-generated method stub return null; } }
18.237762
83
0.706672
3ac75425442085e14ddb27807c48b698ea4f664e
1,858
/** * */ package com.cloudibpm.core.organization; //import com.cloudibpm.core.CornerMark; /** * @author TKuser * @created on 2008-07 * @modified on 2016-07-27 14:36pm */ public class AbstractOrganizationComponent extends AbstractOrganization { /** * serialVersionUID */ private static final long serialVersionUID = 3478425993691715306L; private String abbrName = "general abbr"; // short name private int rank = 1;// private double x0 = 0; // top left corner X private double y0 = 0; // top left corner Y private double x1 = 0; // bottom right corner X private double y1 = 0; // bottom right corner X // private boolean selected = false; // is selected on canvas // private boolean isnewparent = false; // temp property // private CornerMark[] marks = null; // eight corner marks // private Relationship input = null; // top/left relationships private String classtypename = "AbstractOrganizationComponent"; /** * */ public AbstractOrganizationComponent() { } /** * @param id */ public AbstractOrganizationComponent(String id) { super(id); } public String getAbbrName() { return abbrName; } public void setAbbrName(String abbrName) { this.abbrName = abbrName; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public double getX0() { return x0; } public void setX0(double x0) { this.x0 = x0; } public double getY0() { return y0; } public void setY0(double y0) { this.y0 = y0; } public double getX1() { return x1; } public void setX1(double x1) { this.x1 = x1; } public double getY1() { return y1; } public void setY1(double y1) { this.y1 = y1; } public String getClasstypename() { return classtypename; } public void setClasstypename(String classtypename) { this.classtypename = classtypename; } }
18.215686
73
0.681916
aa71551b4eee7547828c646b5199dae40bcaf75e
2,324
package io.noties.markwon.sample; import android.text.Spanned; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import io.noties.adapt.Item; import io.noties.markwon.Markwon; import io.noties.markwon.utils.NoCopySpannableFactory; class SampleItem extends Item<SampleItem.SampleHolder> { interface OnClickListener { void onClick(@NonNull Sample sample); } private final Sample sample; private final Markwon markwon; private final OnClickListener onClickListener; // instance specific cache private Spanned cache; SampleItem(@NonNull Sample sample, @NonNull Markwon markwon, @NonNull OnClickListener onClickListener) { super(sample.ordinal()); this.sample = sample; this.markwon = markwon; this.onClickListener = onClickListener; } @NonNull @Override public SampleHolder createHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) { final SampleHolder holder = new SampleHolder(inflater.inflate( R.layout.adapt_sample_item, parent, false)); // set Spannable.Factory so when TextView will receive a new content // it won't create new Spannable and copy all the spans but instead // re-use existing Spannable thus improving performance holder.textView.setSpannableFactory(NoCopySpannableFactory.getInstance()); return holder; } @Override public void render(@NonNull SampleHolder holder) { // retrieve an item from cache or create new one // simple lazy loading pattern (cache on first call then re-use) Spanned spanned = this.cache; if (spanned == null) { spanned = cache = markwon.toMarkdown( holder.textView.getResources().getString(sample.textResId())); } holder.textView.setText(spanned); holder.itemView.setOnClickListener(v -> onClickListener.onClick(sample)); } static class SampleHolder extends Item.Holder { final TextView textView; SampleHolder(@NonNull View view) { super(view); this.textView = requireView(R.id.text); } } }
28.691358
108
0.677711
37ffdadf3dc281cc99e69684fe09cab2b31f74e7
1,784
package poker.domain; import java.util.Arrays; import java.util.Comparator; import java.util.List; import lombok.AccessLevel; import lombok.AllArgsConstructor; import poker.checker.CheckerFactory; import poker.checker.api.HandValueChecker; import poker.domain.card.Card; @AllArgsConstructor(access = AccessLevel.PRIVATE) public enum HandValue { HIGHEST_CARD(CheckerFactory.forHighestCard()), ONE_PAIR(CheckerFactory.forOnePair()), TWO_PAIRS(CheckerFactory.forTwoPairs()), THREE_OF_A_KIND(CheckerFactory.forThreeOfAKind()), STRAIGHT(CheckerFactory.forStraight()), FLUSH(CheckerFactory.forFlush()), FULL_HOUSE(CheckerFactory.forFullHouse()), FOUR_OF_A_KIND(CheckerFactory.forFourOfAKind()), STRAIGHT_FLUSH(CheckerFactory.forStraightFlush()); private static final HandValue[] valuesInDescendingOrder; static { valuesInDescendingOrder = Arrays.stream(HandValue.values()) .sorted(Comparator.reverseOrder()) .toArray(HandValue[]::new); } private final HandValueChecker checker; public static HandValue of(List<Card> cards) { if (cards == null || cards.size() != Hand.CARDS_IN_HAND) { String message = String.format("To calculate hand value the list must have %d cards", Hand.CARDS_IN_HAND); throw new IllegalArgumentException(message); } for (HandValue value : valuesInDescendingOrder) { if (value.checker.checkRulesFor(cards)) { return value; } } throw new IllegalStateException("Non expected state exception, at least highest card checker should have returned true"); } public boolean isGreaterThan(HandValue other) { return compareTo(other) > 0; } @Override public String toString() { return super.toString().toLowerCase().replaceAll("_", "-"); } }
27.030303
125
0.738229
0e513515caeac7567d3702af93ba331e76e700e6
13,921
package com.filesystem; import java.util.ArrayList; import java.util.Arrays; import java.util.List; class CommandTest { private FileSystem fs = new FileSystem(64,24,4); private static int passed = 0; private static int failed = 0; void runAllTests() { // create try { Create_23Files_Pass(); Create_ExistingFile_Error(); Create_ExceedFileDescriptors_Error(); System.out.println(); } catch (Exception e) { System.out.println("Something wrong with create"); System.out.println(); } // destroy try { Destroy_1File_Pass(); Destroy_AllFiles_Pass(); Destroy_MissingFile_Error(); Destroy_OpenFile_Pass(); System.out.println(); } catch (Exception e) { System.out.println("Something wrong with destroy"); System.out.println(); } // open try { Open_3Files_Pass(); Open_4Files_Error(); Open_MissingFile_Error(); System.out.println(); } catch (Exception e) { System.out.println("Something wrong with open"); System.out.println(); } // close try { Close_File_Pass(); Close_NotOpenFile_Error(); Close_OutOfBoundsIndex_Error(); Close_Directory_Error(); System.out.println(); } catch (Exception e) { System.out.println("Something wrong with close"); System.out.println(); } // read try { Read_NotOpenFile_Error(); Read_PastEndOfFile_Pass(); System.out.println(); } catch (Exception e) { System.out.println("Something wrong with Read"); System.out.println(); } // write try { Write_All3Blocks_Pass(); Write_NotOpenFile_Error(); Write_PastAll3Blocks_Error(); //TODO----THE PROBLEM IS HERE System.out.println(); } catch (Exception e) { System.out.println("Something wrong with write"); System.out.println(); } // seek try { Seek_Negative_Error(); Seek_PastEndOfFile_Error(); Seek_ToEndOfFile_Pass(); System.out.println(); } catch (Exception e) { System.out.println("Something wrong with seek"); System.out.println(); } System.out.println("Passed " + passed + " out of " + (passed + failed) + " total tests"); } void cleanup() { fs = new FileSystem(64,24,4); } void Create_23Files_Pass() { System.out.print("Running Create_23Files_Pass... "); List<String> files = new ArrayList<>(); String name = "fo"; for (int i = 1; i < 24; i++) { files.add(name + i); } boolean result; for (String file : files) { try { fs.create(file); result = true; } catch(Throwable t) { t.printStackTrace(); result = false; } if (!result) { System.out.println("Failed test"); failed++; return; } } System.out.println("Passed test"); passed++; cleanup(); } void Create_ExistingFile_Error() { System.out.print("Running Create_ExistingFile_Error... "); String file = "foo"; fs.create(file); boolean result; try { fs.create(file); result = true; } catch(Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Create_ExceedFileDescriptors_Error() { System.out.print("Running Create_ExceedFileDescriptors_Error... "); List<String> files = new ArrayList<>(); String name = "fo"; for (int i = 1; i < 24; i++) { files.add(name + i); } for (String file : files) { fs.create(file); } boolean result; try { fs.create("fo24"); result = true; } catch(Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Destroy_MissingFile_Error() { System.out.print("Running Destroy_MissingFile_Error... "); boolean result; try { fs.destroy("foo"); result = true; } catch (Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Destroy_1File_Pass() { System.out.print("Running Destroy_1File_Pass... "); String file = "foo"; fs.create(file); boolean result; try { fs.destroy(file); result = true; } catch(Throwable t) { t.printStackTrace(); result = false; } updateShouldPass(result); cleanup(); } void Destroy_AllFiles_Pass() { System.out.print("Running Destroy_AllFiles_Pass... "); List<String> files = new ArrayList<>(); String foo = "fo"; for (int i = 1; i < 24; i++) files.add(foo + i); for (String file : files) fs.create(file); for (String file : files) { boolean result; try{ fs.destroy(file); result = true; } catch(Throwable t) { t.printStackTrace(); result = false; } if (!result) { System.out.println("Failed test"); failed++; return; } } System.out.println("Passed test"); passed++; cleanup(); } void Destroy_OpenFile_Pass() { System.out.print("Running Destroy_OpenFile_Pass... "); fs.create("foo"); fs.open("foo"); boolean result; try { fs.destroy("foo"); result = true; } catch(Throwable t) { t.printStackTrace(); result = false; } updateShouldPass(result); cleanup(); } void Open_MissingFile_Error() { System.out.print("Running Open_MissingFile_Error... "); boolean result; try { int handle = fs.open("bar"); result = true; if(handle == -1) result = false; } catch (Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Open_3Files_Pass() { System.out.print("Running Open_3Files_Pass... "); String[] files = {"foo", "foo1" , "foo2"}; for (String file : files) fs.create(file); for (String file : files) { boolean result; try{ int handle = fs.open(file); result = true; if(handle == -1) result = false; } catch (Throwable t) { t.printStackTrace(); result = false; } if (!result) { System.out.println("Failed test"); failed++; return; } } System.out.println("Passed test"); passed++; cleanup(); } void Open_4Files_Error() { System.out.print("Running Open_4Files_Error... "); String[] files = {"foo", "foo1", "foo2", "foo3"}; for (String file : files) fs.create(file); for (int i = 0; i < files.length; i++) { boolean result; try{ fs.open(files[i]); result = true; } catch (Throwable t) { result = false; } if (i == 3) // attempting to open a 4th file { updateShouldFail(result); } } cleanup(); } void Close_NotOpenFile_Error() { System.out.print("Running Close_NotOpenFile_Error... "); boolean result; try { fs.close(1); result = true; } catch(Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Close_OutOfBoundsIndex_Error() { System.out.print("Running Close_OutOfBoundsIndex_Error... "); boolean result; try { fs.close(-1); result = true; } catch(Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Close_File_Pass() { System.out.print("Running Close_File_Pass... "); fs.create("foo"); int index = fs.open("foo"); boolean result; try { fs.close(index); result = true; } catch(Throwable t) { t.printStackTrace(); result = false; } updateShouldPass(result); cleanup(); } void Close_Directory_Error() { System.out.print("Running Close_Directory_Error... "); boolean result; try { fs.close(0); result = true; } catch(Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Read_NotOpenFile_Error() { System.out.print("Running Read_NotOpenFile_Error... "); boolean result; try { fs.read(1, new byte[4], 4); result = true; } catch (Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Read_PastEndOfFile_Pass() { System.out.print("Running Read_PastEndOfFile_Pass... "); fs.create("foo"); int index = fs.open("foo"); boolean result; try { byte[] b = new byte[60]; fs.read(index, b, 60); result = true; } catch(Throwable t){ t.printStackTrace(); result = false; } updateShouldPass(result); cleanup(); } void Write_NotOpenFile_Error() { System.out.print("Running Write_NotOpenFile_Error... "); boolean result; try { byte[] b = new byte[10]; Arrays.fill(b,(byte)'x'); fs.write(1, b, 10); result = true; } catch(Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Write_All3Blocks_Pass() { System.out.print("Running Write_All3Blocks_Pass... "); fs.create("foo"); int index = fs.open("foo"); boolean result; try{ byte[] b = new byte[192]; Arrays.fill(b,(byte)'x'); fs.write(index, b, 192); result = true; } catch(Throwable t){ t.printStackTrace(); result = false; } updateShouldPass(result); cleanup(); } void Write_PastAll3Blocks_Error() { System.out.print("Running Write_PastAll3Blocks_Error... "); fs.create("foo"); int index = fs.open("foo"); boolean result; try{ byte[] b = new byte[193]; Arrays.fill(b,(byte)'x'); int bytesWritten = fs.write(index, b, 193); result = true; if(bytesWritten != 193) result = false; } catch(Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Seek_Negative_Error() { System.out.print("Running Seek_Negative_Error... "); boolean result; try{ fs.lseek(0, -1); result = true; } catch(Throwable t) { result = false; } updateShouldFail(result); cleanup(); } void Seek_PastEndOfFile_Error() { System.out.print("Running Seek_PastEndOfFile_Error... "); boolean result; try{ fs.lseek(0, 193); result = true; } catch(Throwable t){ result = false; } updateShouldFail(result); cleanup(); } void Seek_ToEndOfFile_Pass() { System.out.print("Running Seek_ToEndOfFile_Pass... "); fs.create("foo"); int index = fs.open("foo"); byte[] b = new byte[10]; Arrays.fill(b,(byte)'x'); fs.write(index, b, 10); boolean result; try{ fs.lseek(index, 10); result = true; } catch(Throwable t){ t.printStackTrace(); result = false; } updateShouldPass(result); cleanup(); } private void updateShouldFail(boolean result) { if (!result) { System.out.println("Passed test"); passed++; } else { System.out.println("Failed test"); failed++; } } private void updateShouldPass(boolean result) { if (!result) { System.out.println("Failed test"); failed++; } else { System.out.println("Passed test"); passed++; } } // public static void main (String[] args) // { // CommandTest test = new CommandTest(); // test.runAllTests(); // } }
24.252613
97
0.470081
89da3a076054b5aed0cb865fc1361bf309f24cbb
2,384
package com.jaimedantas.fiitaxcalculator.business; import com.jaimedantas.fiitaxcalculator.model.FiiData; import com.jaimedantas.fiitaxcalculator.model.FiiTax; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.*; class TaxCalculatorTest { @Test void shouldCalculateTaxForFiiXPLG11() { FiiData fiiData = new FiiData(); fiiData.setName("XPLG11"); fiiData.setPurchasePriceUnit(new BigDecimal("101")); fiiData.setQuantityBought(200l); fiiData.setQuantitySold(200l); fiiData.setSoldPriceUnit(new BigDecimal("130.20")); fiiData.setTotalValueBought(new BigDecimal("2121.00")); fiiData.setTotalValueSold(new BigDecimal("3013.71")); BigDecimal expectedTotalProfitPercentage = new BigDecimal("0.34"); BigDecimal expectedTotalProfitValue = new BigDecimal("714.54"); BigDecimal expectedTDarf = new BigDecimal("178.17"); TaxCalculator taxCalculator = new TaxCalculator(); FiiTax fiiTax = taxCalculator.calculeFiiTaxes(fiiData); assertEquals(expectedTotalProfitPercentage, fiiTax.getTotalProfitPercentage()); assertEquals(expectedTotalProfitValue, fiiTax.getTotalProfitValue()); assertEquals(expectedTDarf, fiiTax.getFixedTax()); } @Test void shouldCalculateTaxForFiiXPML11() { FiiData fiiData = new FiiData(); fiiData.setName("XPML11"); fiiData.setPurchasePriceUnit(new BigDecimal("109")); fiiData.setQuantityBought(47); fiiData.setQuantitySold(47); fiiData.setSoldPriceUnit(new BigDecimal("138.99")); fiiData.setTotalValueBought(new BigDecimal("5295.93")); fiiData.setTotalValueSold(new BigDecimal("6532.53")); BigDecimal expectedTotalProfitPercentage = new BigDecimal("0.19"); BigDecimal expectedTotalProfitValue = new BigDecimal("990.13"); //darf xpml: 246.93 BigDecimal expectedTDarf = new BigDecimal("246.47"); TaxCalculator taxCalculator = new TaxCalculator(); FiiTax fiiTax = taxCalculator.calculeFiiTaxes(fiiData); assertEquals(expectedTotalProfitPercentage, fiiTax.getTotalProfitPercentage()); assertEquals(expectedTotalProfitValue, fiiTax.getTotalProfitValue()); assertEquals(expectedTDarf, fiiTax.getFixedTax()); } }
35.058824
87
0.713507
f2447ced16eb47b164d41afaefc689bc4af6df75
1,009
package ssd8.exam2.bean; import java.io.Serializable; import java.util.ArrayList; /** * 用户实体类 * * @author Hanxy * @version 1.0.0 * @see java.io.Serializable */ public class User implements Serializable{ private String username; private String password; public User(String username, String password) { this.username = username; this.password = password; } 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; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; if (!getUsername().equals(user.getUsername())) return false; return getPassword().equals(user.getPassword()); } }
19.784314
68
0.624381
3e29dbd432669bb6b20c00fb83a54d706c17de71
1,218
package id.ac.tazkia.payment.virtualaccount; import com.fasterxml.jackson.databind.ObjectMapper; import id.ac.tazkia.payment.virtualaccount.dto.VaPayment; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringRunner; import java.time.LocalDateTime; @RunWith(SpringRunner.class) @SpringBootTest public class PaymentVirtualAccountApplicationTests { @Autowired private ObjectMapper objectMapper; @Autowired private PasswordEncoder passwordEncoder; @Test public void checkConfig() { System.out.println("Application runs ok"); } @Test public void testSerializeLocalDateTime() throws Exception { VaPayment payment = new VaPayment(); payment.setPaymentTime(LocalDateTime.now()); System.out.println(objectMapper.writeValueAsString(payment)); } @Test public void testGeneratePassword() { String hashed = passwordEncoder.encode("test123"); System.out.println("Hashed : "+hashed); } }
31.230769
69
0.764368
7ff25bd24d2fa7db8c669e23ddb91fd66077a345
898
package uk.gov.digital.ho.hocs.casework.api.dto; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Getter; import org.springframework.lang.NonNull; import javax.validation.constraints.NotEmpty; @AllArgsConstructor @Getter public class UpdateCorrespondentRequest { @NonNull @NotEmpty @JsonProperty(value = "fullname", required = true) String fullname; @JsonProperty("organisation") String organisation; @JsonProperty("postcode") String postcode; @JsonProperty("address1") String address1; @JsonProperty("address2") String address2; @JsonProperty("address3") String address3; @JsonProperty("country") String country; @JsonProperty("telephone") String telephone; @JsonProperty("email") String email; @JsonProperty("reference") String reference; }
19.106383
54
0.719376
41a925c4e1fae3616660d9ddeaf9757bd4364997
644
package polymorphism; import java.util.List; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; public class CollectionBeanClient { public static void main(String[] args) { // TODO Auto-generated method stub AbstractApplicationContext factory = new GenericXmlApplicationContext("applicationContext.xml"); CollectionBean collectionBean = (CollectionBean) factory.getBean("collectionBean"); List<String> list= collectionBean.getAddressList(); for(String word: list){ System.out.println(word); } factory.close(); } }
25.76
98
0.77795
a8a5bb369826f86841d524fed0c06f367fd8b712
57
package com.cw; public class ConcurrentHashMapDemo { }
9.5
36
0.77193
b5d29aeea5660daabb79fcb241e0227677eb1974
4,848
/* * Copyright (c) 2015 The Jupiter Project * * Licensed under the Apache License, version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jupiter.transport.netty.handler; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.EncoderException; import org.jupiter.common.util.Reflects; import org.jupiter.transport.JProtocolHeader; import org.jupiter.transport.payload.JRequestPayload; import org.jupiter.transport.payload.JResponsePayload; import org.jupiter.transport.payload.PayloadHolder; /** * <pre> * ************************************************************************************************** * Protocol * ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ * 2 │ 1 │ 1 │ 8 │ 4 │ * ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤ * │ │ │ │ │ * │ MAGIC Sign Status Invoke Id Body Size Body Content │ * │ │ │ │ │ * └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ * * 消息头16个字节定长 * = 2 // magic = (short) 0xbabe * + 1 // 消息标志位, 低地址4位用来表示消息类型request/response/heartbeat等, 高地址4位用来表示序列化类型 * + 1 // 状态位, 设置请求响应状态 * + 8 // 消息 id, long 类型, 未来jupiter可能将id限制在48位, 留出高地址的16位作为扩展字段 * + 4 // 消息体 body 长度, int 类型 * </pre> * * jupiter * org.jupiter.transport.netty.handler * * @author jiachun.fjc */ @ChannelHandler.Sharable public class LowCopyProtocolEncoder extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ByteBuf buf = null; try { if (msg instanceof PayloadHolder) { PayloadHolder cast = (PayloadHolder) msg; buf = encode(cast); ctx.write(buf, promise); buf = null; } else { ctx.write(msg, promise); } } catch (Throwable t) { throw new EncoderException(t); } finally { if (buf != null) { buf.release(); } } } protected ByteBuf encode(PayloadHolder msg) throws Exception { if (msg instanceof JRequestPayload) { return doEncodeRequest((JRequestPayload) msg); } else if (msg instanceof JResponsePayload) { return doEncodeResponse((JResponsePayload) msg); } else { throw new IllegalArgumentException(Reflects.simpleClassName(msg)); } } private ByteBuf doEncodeRequest(JRequestPayload request) { byte sign = JProtocolHeader.toSign(request.serializerCode(), JProtocolHeader.REQUEST); long invokeId = request.invokeId(); ByteBuf byteBuf = (ByteBuf) request.outputBuf().backingObject(); int length = byteBuf.readableBytes(); byteBuf.markWriterIndex(); byteBuf.writerIndex(byteBuf.writerIndex() - length); byteBuf.writeShort(JProtocolHeader.MAGIC) .writeByte(sign) .writeByte(0x00) .writeLong(invokeId) .writeInt(length - JProtocolHeader.HEADER_SIZE); byteBuf.resetWriterIndex(); return byteBuf; } private ByteBuf doEncodeResponse(JResponsePayload response) { byte sign = JProtocolHeader.toSign(response.serializerCode(), JProtocolHeader.RESPONSE); byte status = response.status(); long invokeId = response.id(); ByteBuf byteBuf = (ByteBuf) response.outputBuf().backingObject(); int length = byteBuf.readableBytes(); byteBuf.markWriterIndex(); byteBuf.writerIndex(byteBuf.writerIndex() - length); byteBuf.writeShort(JProtocolHeader.MAGIC) .writeByte(sign) .writeByte(status) .writeLong(invokeId) .writeInt(length - JProtocolHeader.HEADER_SIZE); byteBuf.resetWriterIndex(); return byteBuf; } }
35.647059
103
0.571163
e66420f05d2ee7a4c0d1d272181f269d0263fa97
2,121
package com.webank.servicemanagement.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import com.google.common.base.Strings; public class DateUtils { public static java.util.Date convertToTimestamp(String value) throws Exception { if (Strings.isNullOrEmpty(value)) return null; String timestampPattern = "yyyy-MM-dd HH:mm:ss"; String datePattern = "yyyy-MM-dd"; String parsePattern = null; java.util.Date date = null; if (value.length() == timestampPattern.length()) { parsePattern = timestampPattern; } else if (value.length() == datePattern.length()) { parsePattern = datePattern; } if (!Strings.isNullOrEmpty(parsePattern)) { SimpleDateFormat dateFmt = new SimpleDateFormat(parsePattern); dateFmt.setTimeZone(TimeZone.getTimeZone("UTC")); try { date = dateFmt.parse(value); } catch (ParseException e) { throw new Exception(String.format("Failed to parse date string [%s].", value), e); } } else { throw new Exception("Only support 'yyyy-MM-dd HH:mm:ss' and 'yyyy-MM-dd' for datetime."); } return date; } public static String formatDateToString(Date date) { if (date == null) { return ""; } DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(TimeZone.getDefault()); return df.format(date); } public static Date formatStringToDate(String dateString) throws ParseException { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.parse(dateString); } public static Date addDateMinute(Date date,String minute) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MINUTE, Integer.parseInt(minute)); return calendar.getTime(); } }
32.136364
101
0.628477
232699ad6f45fd7c9b6e92781cce1d91998a4652
4,233
package com.main; import java.util.ArrayList; import java.util.List; import resources.Piston; import utils.FinalContainer; import com.lac.petrinet.configuration.providers.PNMLConfigurationReader; import com.lac.petrinet.core.PetriNet; import com.lac.petrinet.exceptions.PetriNetException; import com.productioncell.dummies.v1.AbiertoPistonDummy; import com.productioncell.dummies.v1.AdelantePistonDummy; import com.productioncell.dummies.v1.AdelantePistonPrimeroDummy; import com.productioncell.dummies.v1.AtrasPistonDummy; import com.productioncell.dummies.v1.ErrorChecker; import com.productioncell.dummies.v1.ErrorHandlerPistonDummy; public class ProductionCellChimpMain { public static void main(String[] args) throws PetriNetException { // Resources FinalContainer finalContainer = new FinalContainer(); Piston a = new Piston("PA", 200, 20, 15, 10); Piston b = new Piston("PB", 150, 30, 12, 5); Piston c = new Piston("PC", 170, 40, 8, 4); Piston d = new Piston("PD", 120, 80, 14, 10); // Dummies Adelante AdelantePistonPrimeroDummy adelanteA = new AdelantePistonPrimeroDummy("t2", a ); AdelantePistonDummy adelanteB = new AdelantePistonDummy("t21", b); AdelantePistonDummy adelanteC = new AdelantePistonDummy("t28", c); AdelantePistonDummy adelanteD = new AdelantePistonDummy("t37", d); // Dummies Atras AtrasPistonDummy atrasA = new AtrasPistonDummy("t3", a, b ); AtrasPistonDummy atrasB = new AtrasPistonDummy("t18", b, c ); AtrasPistonDummy atrasC = new AtrasPistonDummy("t26", c, d ); AtrasPistonDummy atrasD = new AtrasPistonDummy("t35", d, finalContainer ); // Dummies Abierto AbiertoPistonDummy abiertoA = new AbiertoPistonDummy("t4", a); AbiertoPistonDummy abiertoB = new AbiertoPistonDummy("t17", b); AbiertoPistonDummy abiertoC = new AbiertoPistonDummy("t25", c); AbiertoPistonDummy abiertoD = new AbiertoPistonDummy("t34", d); // Dummies Error checker ErrorChecker errorCheckerA = new ErrorChecker("t11", a); ErrorChecker errorCheckerB = new ErrorChecker("t15", b); ErrorChecker errorCheckerC = new ErrorChecker("t31", c); ErrorChecker errorCheckerD = new ErrorChecker("t40", d); // Dummies Error Handler ErrorHandlerPistonDummy errorHandlerA = new ErrorHandlerPistonDummy("t5", a); ErrorHandlerPistonDummy errorHandlerB = new ErrorHandlerPistonDummy("t10", b); ErrorHandlerPistonDummy errorHandlerC = new ErrorHandlerPistonDummy("t9", c); ErrorHandlerPistonDummy errorHandlerD = new ErrorHandlerPistonDummy("t7", d); // Relacionar dummies y transiciones Informadas. PNMLConfigurationReader pnmlConfigurator = new PNMLConfigurationReader(); PetriNet pn = pnmlConfigurator.loadConfiguration(ProductionCellChimpMain.class.getClassLoader() .getResource("resources/modelov1.1.pnml").getPath()); pn.assignDummy("t1", adelanteA); pn.assignDummy("t16", adelanteB); pn.assignDummy("t24", adelanteC); pn.assignDummy("t33", adelanteD); pn.assignDummy("t2", abiertoA); pn.assignDummy("t21", abiertoB); pn.assignDummy("t28", abiertoC); pn.assignDummy("t37", abiertoD); pn.assignDummy("t4", atrasA); pn.assignDummy("t17", atrasB); pn.assignDummy("t25", atrasC); pn.assignDummy("t34", atrasD); pn.assignDummy("t8", errorCheckerA ); pn.assignDummy("t13", errorCheckerB ); pn.assignDummy("t30", errorCheckerC ); pn.assignDummy("t39", errorCheckerD ); pn.assignDummy("t41", errorHandlerA); pn.assignDummy("t14", errorHandlerB); pn.assignDummy("t23", errorHandlerC); pn.assignDummy("t32", errorHandlerD); List<String> groupOne = new ArrayList<String>(); List<String> groupTwo = new ArrayList<String>(); List<String> groupThree = new ArrayList<String>(); List<String> groupFour = new ArrayList<String>(); groupOne.add("t8"); groupOne.add("t1"); groupTwo.add("t13"); groupTwo.add("t4"); groupTwo.add("t16"); groupThree.add("t30"); groupThree.add("t17"); groupThree.add("t24"); groupFour.add("t39"); groupFour.add("t25"); groupFour.add("t33"); pn.addTransitionNameGroup(groupOne); pn.addTransitionNameGroup(groupTwo); pn.addTransitionNameGroup(groupThree); pn.addTransitionNameGroup(groupFour); pn.startListening(); } }
35.571429
97
0.741082
3b7ab941c80a99db8b775c7192402bb377327c9c
1,282
/* * Copyright 2017 Google 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.google.cloud.tools.eclipse.appengine.validation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.eclipse.core.resources.IMarker; import org.eclipse.ui.IMarkerResolution; import org.junit.Test; import org.mockito.Mockito; public class ServletMarkerResolutionGeneratorTest { @Test public void testGetResolutions() { ServletMarkerResolutionGenerator resolution = new ServletMarkerResolutionGenerator(); IMarker marker = Mockito.mock(IMarker.class); IMarkerResolution[] resolutions = resolution.getResolutions(marker); assertEquals(1, resolutions.length); assertNotNull(resolutions[0]); } }
32.871795
89
0.767551
5077760cdf5b5f7acfacf8c3565a090e839d1833
4,268
package com.jiaxy.conf.server.facade; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.DelayQueue; /** * Description: <br/> * <p/> * Company: * * @author: <a href=mailto:[email protected]>tom</a> * <br/> * @Date: 2017/09/06 17:16 */ public class ConfDelEventCollection { private static final Logger logger = LoggerFactory.getLogger(ConfDelEventCollection.class); private ConcurrentHashMap<String, ConfDelEvent> confDelEventMap = new ConcurrentHashMap<>(); private DelayQueue<ConfDelEvent> queue = new DelayQueue<>(); public ConfDelEventCollection() { startExpireThread(); } public void addConfDelEvent(long expire, String confOwner, String path, String confKey, Integer version) { String key = buildKey(confOwner, path, confKey, version); ConfDelEvent old = confDelEventMap.putIfAbsent(key, new ConfDelEvent(expire, confOwner, path, confKey, version)); if (old == null) { queue.offer(confDelEventMap.get(key)); } } public ConfDelEvent getConfDelEvent( String confOwner, String path, String confKey, Integer version) { return confDelEventMap.get(buildKey(confOwner, path, confKey, version)); } /** * get all del events belong to the path of the conf owner * * @param confOwner * @param path * @return */ public List<ConfDelEvent> getConfDelEvents( String confOwner, String path ) { Map<String, ConfDelEvent> map = new HashMap<>(confDelEventMap); if (map.isEmpty()) { return null; } List<ConfDelEvent> events = new ArrayList<>(); for (ConfDelEvent event : map.values()) { if (event.getConfOwner().equals(confOwner) && event.getPath().equals(path)) { events.add(event); } } return events; } public ConfDelEvent removeConfDelEvent( String confOwner, String path, String confKey, Integer version) { return confDelEventMap.remove(buildKey(confOwner, path, confKey, version)); } /** * @param confOwner * @param path * @param confKey * @param version * @return */ private String buildKey(String confOwner, String path, String confKey, Integer version) { StringBuilder keyBuilder = new StringBuilder(); keyBuilder.append(confOwner) .append("#") .append(path); if (confKey != null && !"".equals(confKey)) { keyBuilder.append("#") .append(confKey); } if (version != null) { keyBuilder.append("#") .append(version); } return keyBuilder.toString(); } private void startExpireThread() { Thread expireThread = new Thread(() -> { while (true) { try { ConfDelEvent event = queue.take(); if (event != null) { removeConfDelEvent(event.getConfOwner(), event.getPath(), event.getConfKey(), event.getVersion()); logger.info("confOwner:{},path:{},confKey:{},version:{} conf del event expired.", event.getConfOwner(), event.getPath(), event.getConfKey(), event.getVersion()); } } catch (InterruptedException e) { logger.error("conf del event expire thread error.", e); } } }, "conf-del-event-expired-thread"); expireThread.start(); logger.info("conf-del-event-expired-thread started"); } }
30.485714
121
0.532568
0841d3bc4409ec29fcbd8076db72fbb216690065
7,653
// CONTENT UI TEST . JAVA package cat.calidos.morfeu.webapp; import static com.codeborne.selenide.Selenide.open; import static org.junit.Assert.*; import java.util.List; import org.junit.Before; import org.junit.Test; import cat.calidos.morfeu.webapp.ui.UICatalogue; import cat.calidos.morfeu.webapp.ui.UICatalogues; import cat.calidos.morfeu.webapp.ui.UICell; import cat.calidos.morfeu.webapp.ui.UICellModelEntry; import cat.calidos.morfeu.webapp.ui.UIContent; import cat.calidos.morfeu.webapp.ui.UIDocument; import cat.calidos.morfeu.webapp.ui.UIDropArea; import cat.calidos.morfeu.webapp.ui.UIModel; /** Testing content display without manipulation * @author daniel giribet */////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public class ContentUITest extends UITezt { @Before public void setup() { open(appBaseURL); } @Test public void contentTestAppearingAndDisappearing() { UIContent.shouldNotBeVisible(); UICatalogues catalogues = UICatalogues.openCatalogues().shouldAppear(); UIContent.shouldNotBeVisible(); UICatalogue catalogue = catalogues.clickOn(0); UIContent content = catalogue.clickOnDocumentNamed("Document 1").content(); content.shouldBeVisible(); catalogue.clickOnDocumentNamed("Document with non-valid content"); content.shouldDisappear(); } @Test public void contentTest() { UIContent content = UICatalogues.openCatalogues() .shouldAppear() .clickOn(0) .clickOnDocumentNamed("Document 1") .content(); content.shouldBeVisible(); List<UICell> rootCells = content.rootCells(); // TEST assertNotNull(rootCells); assertEquals(1, rootCells.size()); UICell test1 = rootCells.get(0); // TEST/* assertNotNull(test1); assertTrue(test1.isWell()); UICell row2 = test1.children().get(0); // TEST/ROW assertNotNull(row2); assertTrue(row2.isRowWell()); List<UICell> cols3 = row2.children(); // TEST/ROW/* assertNotNull(cols3); assertEquals(2, cols3.size()); UICell col3a = cols3.get(0); // TEST/ROW/COL0 assertNotNull(col3a); assertTrue(col3a.isColumnWell()); UICell data = col3a.child("data(0)"); assertTrue("'data' cell representation img is wrong", data.img().endsWith("assets/images/data-cell.svg")); UICell col3b = cols3.get(1); // TEST/ROW/COL1 assertNotNull(col3b); assertTrue(col3b.isColumnWell()); UICell data2 = col3b.child("row(0)").child("col(0)").child("data2(1)"); assertTrue("'data2' cell representation img is wrong", data2.img().contains("/dyn/preview/svg/data2.svg")); } @Test public void relationshipFromContentToModelTest() { String document1URI = "target/test-classes/test-resources/documents/document1.xml"; UIDocument document = UICatalogues.openCatalogues() .shouldAppear() .clickOn(0) .clickOnDocumentNamed("Document 1"); UIContent content = document.content(); content.shouldBeVisible(); UICell test = content.rootCells().get(0); // /test/row/col/data UICell data = test.child("row(0)").child("col(0)").child("data(0)"); assertTrue(data.isCell()); assertEquals(document1URI+"/test(0)/row(0)/col(0)/data(0)", data.id()); data.hover(); assertTrue(data.isActive()); UIModel model = document.model(); //test/row/col/data UICellModelEntry dataModel = model.rootCellModel("test").child("row").child("col").child("data"); assertTrue(dataModel.isActive()); UICellModelEntry data2Model = model.rootCellModel("test").child("row").child("col").child("data2"); assertFalse(data2Model.isActive()); UICell data2 = test.child("row(0)").child("col(1)").child("row(0)").child("col(1)").child("data2(0)"); assertFalse(data2.isActive()); data2.hover(); assertTrue(data2.isActive()); assertTrue(data2Model.isActive()); assertFalse(dataModel.isActive()); } @Test public void relationshipFromModelToContentTest() { UIDocument document = UICatalogues.openCatalogues() .shouldAppear() .clickOn(0) .clickOnDocumentNamed("Document 1"); UIContent content = document.content(); content.shouldBeVisible(); UICell test = content.rootCells().get(0); UIModel model = document.model(); // let's check for model drop area activations, we highlight row so test can allow them UICellModelEntry rowModel = model.rootCellModel("test").child("row").hover(); assertTrue(rowModel.isActive()); assertTrue(test.dropArea(0).isActive()); // we highlight data2, on this column there are two of them so no drop areas are active UICellModelEntry data2Model = model.rootCellModel("test").child("row").child("col").child("data2"); data2Model.hover(); assertTrue(data2Model.isActive()); List<UIDropArea> dropAreas = test.child("row(0)").child("col(1)").child("row(0)").child("col(1)").dropAreas(); assertEquals(0, dropAreas.stream().filter(UIDropArea::isActive).count()); // on the other one, there is only one data2, so there is room for 1 more, all drop areas active on that column dropAreas = test.child("row(0)").child("col(1)").child("row(0)").child("col(0)").dropAreas(); assertEquals(dropAreas.size(), dropAreas.stream().filter(UIDropArea::isActive).count()); } @Test public void dropAreasTest() { UIDocument document = UICatalogues.openCatalogues() .shouldAppear() .clickOn(0) .clickOnDocumentNamed("Document 1"); UIContent content = document.content(); content.shouldBeVisible(); UICell test = content.rootCells().get(0); // we check that we have two drop areas, first inactive UICell col = test.child("row(0)").child("col(0)"); List<UIDropArea> dropAreas = col.dropAreas(); assertEquals(2, dropAreas.size()); assertEquals(0, dropAreas.stream().filter(UIDropArea::isActive).count()); // we hover over the data cell and we do not activate both drop areas, as it's an only child UICell data = col.child("data(0)"); assertTrue(data.isCell()); data.hover(); assertTrue(data.isActive()); assertEquals(0, dropAreas.stream().filter(UIDropArea::isActive).count()); // we hover over another data, we should activate both drop areas from the original first column test.child("row(0)").child("col(1)").child("row(0)").child("col(0)").child("data(0)").hover(); assertEquals(dropAreas.size(), dropAreas.stream().filter(UIDropArea::isActive).count()); // here we have 2 data2 children, we can reorder them around so all drop areas are active in this col // this is irrespective of child count and expected UICell colWith2data2 = test.child("row(0)").child("col(1)").child("row(0)").child("col(1)"); dropAreas = colWith2data2.dropAreas(); colWith2data2.child("data2(0)").hover(); assertEquals(dropAreas.size(), dropAreas.stream().filter(UIDropArea::isActive).count()); // however, if we hover on another data2 somewhere else, we hit over the count limit of 2 data2 so we have no // active cols test.child("row(0)").child("col(1)").child("row(0)").child("col(0)").child("data2(1)").hover(); assertEquals(0, dropAreas.stream().filter(UIDropArea::isActive).count()); } } /* * Copyright 2019 Daniel Giribet * * 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. */
33.419214
120
0.703646
80011365cf3d2cf58ce98f8a32ca4851576d9b49
1,076
package com.ratku.sample.dao; import java.util.Date; import javax.transaction.Transactional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import com.ratku.sample.dataobject.UcUser; public interface UcUserDao extends JpaRepository<UcUser, Integer>,JpaSpecificationExecutor<UcUser>{ UcUser findByPhone(String Phone); @Transactional @Modifying(clearAutomatically = true) @Query(value = "UPDATE uc_user u SET u.NAME=?1 , u.CODE=?2, u.EMAIL=?3 , u.UPDATE_TIME=?4 ,u.UPDATE_USER=?5 WHERE u.USER_ID = ?6 ",nativeQuery = true) boolean updateNameByTenantId(String name,String code ,String email ,Date updateTime , String updateUser, String userID); @Transactional @Modifying(clearAutomatically = true) @Query(value = "UPDATE uc_user u SET u.PASSWORD=?1 WHERE u.USER_ID = ?2 ",nativeQuery = true) boolean updatePasswordByUserId(String password, String userID); }
35.866667
151
0.792751
1d312be9ca51b75b0f80910f52363b079dc76de1
9,848
// // Decompiled by Procyon v0.5.36 // package groovy.swing.factory; import org.codehaus.groovy.runtime.callsite.CallSiteArray; import groovy.lang.Closure; import org.codehaus.groovy.runtime.callsite.CallSite; import groovy.lang.MissingPropertyException; import org.codehaus.groovy.runtime.GStringImpl; import groovy.lang.GString; import java.util.Map; import groovy.util.FactoryBuilderSupport; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import java.lang.ref.SoftReference; import groovy.lang.MetaClass; import org.codehaus.groovy.reflection.ClassInfo; import groovy.lang.GroovyObject; import groovy.util.AbstractFactory; public class BeanFactory extends AbstractFactory implements GroovyObject { private final Class beanClass; protected final boolean leaf; private static /* synthetic */ ClassInfo $staticClassInfo; private transient /* synthetic */ MetaClass metaClass; public static /* synthetic */ Long __timeStamp; public static /* synthetic */ Long __timeStamp__239_neverHappen1292524204381; private static /* synthetic */ SoftReference $callSiteArray; private static /* synthetic */ Class $class$groovy$lang$MetaClass; private static /* synthetic */ Class $class$java$lang$RuntimeException; private static /* synthetic */ Class $class$java$lang$Object; private static /* synthetic */ Class $class$java$lang$Boolean; private static /* synthetic */ Class $class$groovy$swing$factory$BeanFactory; private static /* synthetic */ Class $class$groovy$util$FactoryBuilderSupport; private static /* synthetic */ Class $class$java$lang$String; private static /* synthetic */ Class $class$java$lang$Class; public BeanFactory(final Class beanClass) { $getCallSiteArray(); Object[] array3; Object[] array2; Object[] array; final Object[] arguments = array = (array2 = (array3 = new Object[2])); arguments[0] = beanClass; arguments[1] = Boolean.FALSE; final int selectConstructorAndTransformArguments = ScriptBytecodeAdapter.selectConstructorAndTransformArguments(arguments, 2, $get$$class$groovy$swing$factory$BeanFactory()); if ((selectConstructorAndTransformArguments & 0x1) != 0x0) { array2 = (array = (array3 = (Object[])arguments[0])); } switch (selectConstructorAndTransformArguments >> 8) { case 0: { this((Class)array[0]); break; } case 1: { this((Class)array2[0], DefaultTypeTransformation.booleanUnbox(array3[1])); break; } default: { throw new IllegalArgumentException("illegal constructor number"); } } } public BeanFactory(final Class beanClass, final boolean leaf) { $getCallSiteArray(); this.metaClass = (MetaClass)ScriptBytecodeAdapter.castToType(this.$getStaticMetaClass(), $get$$class$groovy$lang$MetaClass()); this.beanClass = (Class)ScriptBytecodeAdapter.castToType(beanClass, $get$$class$java$lang$Class()); this.leaf = DefaultTypeTransformation.booleanUnbox(DefaultTypeTransformation.box(leaf)); } public boolean isLeaf() { $getCallSiteArray(); return DefaultTypeTransformation.booleanUnbox(ScriptBytecodeAdapter.castToType(DefaultTypeTransformation.box(this.leaf), $get$$class$java$lang$Boolean())); } public Object newInstance(final FactoryBuilderSupport builder, final Object name, Object value, final Map attributes) throws InstantiationException, IllegalAccessException { final CallSite[] $getCallSiteArray = $getCallSiteArray(); if (value instanceof GString) { value = ScriptBytecodeAdapter.asType(value, $get$$class$java$lang$String()); } if (DefaultTypeTransformation.booleanUnbox($getCallSiteArray[0].call($get$$class$groovy$util$FactoryBuilderSupport(), value, name, this.beanClass))) { return ScriptBytecodeAdapter.castToType(value, $get$$class$java$lang$Object()); } final Object bean = $getCallSiteArray[1].call(this.beanClass); if (value instanceof String) { try { ScriptBytecodeAdapter.setProperty(value, $get$$class$groovy$swing$factory$BeanFactory(), bean, "text"); } catch (MissingPropertyException mpe) { throw (Throwable)$getCallSiteArray[2].callConstructor($get$$class$java$lang$RuntimeException(), new GStringImpl(new Object[] { name }, new String[] { "In ", " value argument of type String cannot be applied to property text:" })); } } return ScriptBytecodeAdapter.castToType(bean, $get$$class$java$lang$Object()); } protected /* synthetic */ MetaClass $getStaticMetaClass() { if (this.getClass() == $get$$class$groovy$swing$factory$BeanFactory()) { return ScriptBytecodeAdapter.initMetaClass(this); } ClassInfo $staticClassInfo = BeanFactory.$staticClassInfo; if ($staticClassInfo == null) { $staticClassInfo = (BeanFactory.$staticClassInfo = ClassInfo.getClassInfo(this.getClass())); } return $staticClassInfo.getMetaClass(); } static { BeanFactory.__timeStamp__239_neverHappen1292524204381 = 0L; BeanFactory.__timeStamp = 1292524204381L; } public final Class getBeanClass() { return this.beanClass; } private static /* synthetic */ CallSiteArray $createCallSiteArray() { final String[] names = new String[3]; $createCallSiteArray_1(names); return new CallSiteArray($get$$class$groovy$swing$factory$BeanFactory(), names); } private static /* synthetic */ CallSite[] $getCallSiteArray() { CallSiteArray $createCallSiteArray; if (BeanFactory.$callSiteArray == null || ($createCallSiteArray = BeanFactory.$callSiteArray.get()) == null) { $createCallSiteArray = $createCallSiteArray(); BeanFactory.$callSiteArray = new SoftReference($createCallSiteArray); } return $createCallSiteArray.array; } private static /* synthetic */ Class $get$$class$groovy$lang$MetaClass() { Class $class$groovy$lang$MetaClass; if (($class$groovy$lang$MetaClass = BeanFactory.$class$groovy$lang$MetaClass) == null) { $class$groovy$lang$MetaClass = (BeanFactory.$class$groovy$lang$MetaClass = class$("groovy.lang.MetaClass")); } return $class$groovy$lang$MetaClass; } private static /* synthetic */ Class $get$$class$java$lang$RuntimeException() { Class $class$java$lang$RuntimeException; if (($class$java$lang$RuntimeException = BeanFactory.$class$java$lang$RuntimeException) == null) { $class$java$lang$RuntimeException = (BeanFactory.$class$java$lang$RuntimeException = class$("java.lang.RuntimeException")); } return $class$java$lang$RuntimeException; } private static /* synthetic */ Class $get$$class$java$lang$Object() { Class $class$java$lang$Object; if (($class$java$lang$Object = BeanFactory.$class$java$lang$Object) == null) { $class$java$lang$Object = (BeanFactory.$class$java$lang$Object = class$("java.lang.Object")); } return $class$java$lang$Object; } private static /* synthetic */ Class $get$$class$java$lang$Boolean() { Class $class$java$lang$Boolean; if (($class$java$lang$Boolean = BeanFactory.$class$java$lang$Boolean) == null) { $class$java$lang$Boolean = (BeanFactory.$class$java$lang$Boolean = class$("java.lang.Boolean")); } return $class$java$lang$Boolean; } private static /* synthetic */ Class $get$$class$groovy$swing$factory$BeanFactory() { Class $class$groovy$swing$factory$BeanFactory; if (($class$groovy$swing$factory$BeanFactory = BeanFactory.$class$groovy$swing$factory$BeanFactory) == null) { $class$groovy$swing$factory$BeanFactory = (BeanFactory.$class$groovy$swing$factory$BeanFactory = class$("groovy.swing.factory.BeanFactory")); } return $class$groovy$swing$factory$BeanFactory; } private static /* synthetic */ Class $get$$class$groovy$util$FactoryBuilderSupport() { Class $class$groovy$util$FactoryBuilderSupport; if (($class$groovy$util$FactoryBuilderSupport = BeanFactory.$class$groovy$util$FactoryBuilderSupport) == null) { $class$groovy$util$FactoryBuilderSupport = (BeanFactory.$class$groovy$util$FactoryBuilderSupport = class$("groovy.util.FactoryBuilderSupport")); } return $class$groovy$util$FactoryBuilderSupport; } private static /* synthetic */ Class $get$$class$java$lang$String() { Class $class$java$lang$String; if (($class$java$lang$String = BeanFactory.$class$java$lang$String) == null) { $class$java$lang$String = (BeanFactory.$class$java$lang$String = class$("java.lang.String")); } return $class$java$lang$String; } private static /* synthetic */ Class $get$$class$java$lang$Class() { Class $class$java$lang$Class; if (($class$java$lang$Class = BeanFactory.$class$java$lang$Class) == null) { $class$java$lang$Class = (BeanFactory.$class$java$lang$Class = class$("java.lang.Class")); } return $class$java$lang$Class; } static /* synthetic */ Class class$(final String className) { try { return Class.forName(className); } catch (ClassNotFoundException ex) { throw new NoClassDefFoundError(ex.getMessage()); } } }
47.346154
246
0.666531
32e8023294e018bb5546031477e449d88666f74e
7,264
/* * Spreadsheet by Madhawa */ package spreadsheet.gui; import java.awt.Component; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.DefaultCellEditor; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.CellEditorListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.TableCellEditor; import spreadsheet.Cell; import spreadsheet.Spreadsheet; /** * * @author Madhawa */ /*Used to edit the values in cells This class does the role of swapping the field value with expression when a cell value is edited(inplace editing). During editing, text and the selection in addressbar is adjusted to match the selection and text in cell being edited. Therefore, the events triggered in the addressbar would update the ui cell highlights as required. Cell highlights - highlight relavent cells in special colours when an expression is being edited. */ class SpreadsheetCellEditor extends DefaultCellEditor implements TableCellEditor{ //the textField representing the cell in ui private JTextField editField ; //keep reference to the spreadsheet private spreadsheet.Spreadsheet spreadsheet; //notifies the registered cellEditListners that focus has been gained private void notifyCellEditFocusGained() { CellEditorListener[] listners = this.getCellEditorListeners(); for(CellEditorListener listener:listners) { if(listener instanceof ISpreadsheetCellEditorListener) { ISpreadsheetCellEditorListener spreadsheetListener = (ISpreadsheetCellEditorListener)listener; spreadsheetListener.cellEditorFocusGained(); } } } //notifies the registered cellEditListners that focus has been lost private void notifyCellEditFocusLost() { CellEditorListener[] listners = this.getCellEditorListeners(); for(CellEditorListener listener:listners) { if(listener instanceof ISpreadsheetCellEditorListener) { ISpreadsheetCellEditorListener spreadsheetListener = (ISpreadsheetCellEditorListener)listener; spreadsheetListener.cellEditorFocusLost(); } } } //notifies the registerd cellEditListners that cell editing has begun private void notifyCellEditingBegun() { CellEditorListener[] listners = this.getCellEditorListeners(); for(CellEditorListener listener:listners) { if(listener instanceof ISpreadsheetCellEditorListener) { ISpreadsheetCellEditorListener spreadsheetListener = (ISpreadsheetCellEditorListener)listener; spreadsheetListener.cellEditingBegun(); } } } //notified the registered cellEditorListners that caret has been updated private void notifyCaretUpdated(CaretEvent e) { CellEditorListener[] listners = this.getCellEditorListeners(); for(CellEditorListener listener:listners) { if(listener instanceof ISpreadsheetCellEditorListener) { ISpreadsheetCellEditorListener spreadsheetListener = (ISpreadsheetCellEditorListener)listener; spreadsheetListener.cellCaretUpdated(e); } } } //notify all registered cellEditorListeners that text has changed in cell being edited private void notifyDocumentListenerTextChanged(DocumentEvent e) { CellEditorListener[] listners = this.getCellEditorListeners(); for(CellEditorListener listener:listners) { if(listener instanceof ISpreadsheetCellEditorListener) { ISpreadsheetCellEditorListener spreadsheetListener = (ISpreadsheetCellEditorListener)listener; spreadsheetListener.cellTextChanged(editField.getText(),e); } } } public spreadsheet.Spreadsheet getSpreadsheet() { return spreadsheet; } public SpreadsheetCellEditor(spreadsheet.Spreadsheet currentSheet) { super(new JTextField()); this.spreadsheet = currentSheet; } @Override public Object getCellEditorValue() { //pass through the new cell text as it is. It will be evaluated when the setCellValue function of CellTableModel is called return editField.getText(); } @Override public Component getTableCellEditorComponent(final JTable table, Object value, boolean isSelected, int row, int column) { //retrieves the ui editor for the cell. editField = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column); if(table==null) { editField.setText(""); return editField; } //find cellId String columnName = Spreadsheet.indexToColumnName(column - 1); String cellName = columnName + String.valueOf(row+1); Cell cell = spreadsheet.getCell(cellName); if(cell != null) { //Set the cell expression instead of cell value. Swapping occurs here. (cell value shown in cell now becomes the cell expression for editing purpose) editField.setText(cell.getCellExpression()); } else{ editField.setText(""); } //to identify when editing begins in cell, a listner is used. editField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { notifyCellEditFocusGained(); } @Override public void focusLost(FocusEvent e) { notifyCellEditFocusLost(); } }); //reflect the cursor position of currentCell in the addressBar. //Therefore, both the addressbar and the cell selects the same token editField.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent e) { notifyCaretUpdated(e); } }); //we need a listner to update the ui textfield editField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { notifyDocumentListenerTextChanged(e); } @Override public void removeUpdate(DocumentEvent e) { notifyDocumentListenerTextChanged(e); } @Override public void changedUpdate(DocumentEvent e) { notifyDocumentListenerTextChanged(e); } }); //pass the message to listners. notifyCellEditingBegun(); return editField; } }
32.573991
161
0.636013
af597cdc373030eb1f9d2bee9ea325f32a704850
2,841
package cn.sz.pxd.floatword.dialog; import cn.sz.pxd.floatword.AppConf; import cn.sz.pxd.floatword.Word; import cn.sz.pxd.floatword.WordFrame; import cn.sz.pxd.floatword.service.WordFileService; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import java.awt.*; import java.util.ArrayList; import java.util.Vector; /** * 单词选择对话框 * @author https://github.com/shadon178 */ public class WordLibDialog extends JDialog { @SuppressWarnings({"rawtypes", "unchecked"}) public WordLibDialog(WordFrame frame, java.util.List<Word> words) { this.setTitle("单词选择"); this.setSize(400, 500); this.setLocationRelativeTo(null); String[][] tableData = new String[words.size()][3]; for (int i = 0, size = words.size(); i < size; i++) { Word word = words.get(i); tableData[i][0] = word.getEnglish(); tableData[i][1] = word.getSoundmark(); tableData[i][2] = word.getChinese(); } String[] head = {"单词", "音标", "翻译"}; DefaultTableModel tableModel = new DefaultTableModel(tableData, head); RowSorter sorter = new TableRowSorter(tableModel); JTable table = new JTable(tableModel); table.setRowSorter(sorter); JScrollPane pane = new JScrollPane(table); JButton newBtn = new JButton("新增"); newBtn.addActionListener((e) -> new NewWordDialog(tableModel).setVisible(true)); JButton delBtn = new JButton("删除"); delBtn.addActionListener((e) -> { int selectedRow = table.getSelectedRow(); int i = table.convertRowIndexToModel(selectedRow); tableModel.removeRow(i); }); JButton saveBtn = new JButton("保存"); saveBtn.addActionListener((e) -> { Vector dataVector = tableModel.getDataVector(); java.util.List<String> lines = new ArrayList<>(); for (Object o : dataVector) { Vector rowData = (Vector) o; String word = (String) rowData.get(0); String soundMark = (String) rowData.get(1); String translate = (String) rowData.get(2); String line = word + "\t" + soundMark + "\t" + translate; lines.add(line); } WordFileService.write(lines, AppConf.wordFilePath); frame.updateAllWord(); WordLibDialog.this.setVisible(false); }); JPanel btnPanel = new JPanel(); btnPanel.add(newBtn); btnPanel.add(delBtn); btnPanel.add(saveBtn); this.setLayout(new BorderLayout()); this.add(pane, BorderLayout.CENTER); this.add(btnPanel, BorderLayout.NORTH); } }
36.423077
89
0.591341
e0d859ab936314d127f84d43baaf4b22d7564c46
910
package de.davelee.trams.operations.response; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * This class tests the StopsResponse class and ensures that its works correctly. * @author Dave Lee */ public class StopsResponseTest { @Test public void testSetters() { StopsResponse stopsResponse = new StopsResponse(); stopsResponse.setCount(1L); stopsResponse.setStopResponses(new StopResponse[] { StopResponse.builder() .company("Mustermann Bus GmbH") .name("Greenfield") .latitude(50.03) .longitude(123.04) .build() }); assertEquals(1L, stopsResponse.getCount()); assertEquals("Mustermann Bus GmbH", stopsResponse.getStopResponses()[0].getCompany()); } }
30.333333
94
0.606593
d05d9f31b7ded0394445a22abd5d7248ae4e0726
1,875
package strings; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Given a sequence of strings, the task is to find out the second most repeated * (or frequent) string in the given sequence. * * Note: No two strings are the second most repeated, there will be always a * single string. */ public class SecondMostRepeatedWord { public static void main(String[] args) { String arr[] = { "aaa", "aaa", "ccc", "aaa", "aaa", "aaa", "aaa" }; System.out.println(secFrequent(arr, arr.length)); } static String secFrequent(String arr[], int N) { HashMap<String, Integer> map = new HashMap<>(); // add all the values to the hashmap for (int i = 0; i < N; i++) { if (map.containsKey(arr[i])) map.put(arr[i], map.get(arr[i]) + 1); else map.put(arr[i], 1); } Values val = new Values(Integer.MIN_VALUE, Integer.MIN_VALUE, "", ""); // looping using iterator and finding the most and second most repeated values Iterator<Map.Entry<String, Integer>> itr = map.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, Integer> entry = itr.next(); int v = entry.getValue(); if (v > val.firstMax) { val.firstMax = v; val.firstMaxValue = entry.getKey(); } else if (v > val.secondMax && v != val.firstMax) { val.secondMax = v; val.secondMaxValue = entry.getKey(); } } // returning the second largest repeated value return val.secondMaxValue; } } /* * A class to keep a track on the first and second largest repeated values */ class Values { int firstMax; int secondMax; String firstMaxValue; String secondMaxValue; public Values(int firstMax, int secondMax, String firstMaxValue, String secondMaxValue) { super(); this.firstMax = firstMax; this.secondMax = secondMax; this.firstMaxValue = firstMaxValue; this.secondMaxValue = secondMaxValue; } }
26.041667
90
0.674667
c945bcf8827a34f6788abb3af126c9af172bf4e3
4,727
package slimeknights.tconstruct.library.materials.traits; import io.netty.buffer.Unpooled; import net.minecraft.network.FriendlyByteBuf; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import slimeknights.tconstruct.fixture.MaterialFixture; import slimeknights.tconstruct.fixture.MaterialStatsFixture; import slimeknights.tconstruct.fixture.ModifierFixture; import slimeknights.tconstruct.library.materials.definition.MaterialId; import slimeknights.tconstruct.library.materials.stats.MaterialStatsId; import slimeknights.tconstruct.library.modifiers.ModifierEntry; import slimeknights.tconstruct.test.BaseMcTest; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; class UpdateMaterialTraitsPacketTest extends BaseMcTest { public static final MaterialId MATERIAL_ID_1 = MaterialFixture.MATERIAL_1.getIdentifier(); public static final MaterialId MATERIAL_ID_2 = MaterialFixture.MATERIAL_2.getIdentifier(); @BeforeAll static void beforeAll() { ModifierFixture.init(); } @Test void testGenericEncodeDecode() { List<ModifierEntry> defaultTraits1 = Arrays.asList(new ModifierEntry(ModifierFixture.TEST_MODIFIER_1, 1), new ModifierEntry(ModifierFixture.TEST_MODIFIER_2, 2)); MaterialTraits materialTraits1 = new MaterialTraits(defaultTraits1, Collections.emptyMap()); List<ModifierEntry> defaultTraits2 = Collections.singletonList(new ModifierEntry(ModifierFixture.TEST_MODIFIER_1, 3)); Map<MaterialStatsId, List<ModifierEntry>> statsTraits2 = new HashMap<>(); statsTraits2.put(MaterialStatsFixture.STATS_TYPE, Arrays.asList(new ModifierEntry(ModifierFixture.TEST_MODIFIER_1, 4), new ModifierEntry(ModifierFixture.TEST_MODIFIER_2, 5))); statsTraits2.put(MaterialStatsFixture.STATS_TYPE_2, Collections.singletonList(new ModifierEntry(ModifierFixture.TEST_MODIFIER_2, 6))); MaterialTraits materialTraits2 = new MaterialTraits(defaultTraits2, statsTraits2); Map<MaterialId, MaterialTraits> map = new HashMap<>(); map.put(MATERIAL_ID_1, materialTraits1); map.put(MATERIAL_ID_2, materialTraits2); // send a packet over the buffer FriendlyByteBuf buffer = new FriendlyByteBuf(Unpooled.buffer()); UpdateMaterialTraitsPacket packetToEncode = new UpdateMaterialTraitsPacket(map); packetToEncode.encode(buffer); UpdateMaterialTraitsPacket decoded = new UpdateMaterialTraitsPacket(buffer); // parse results Map<MaterialId, MaterialTraits> parsed = decoded.getMaterialToTraits(); assertThat(parsed).hasSize(2); // material traits 1 MaterialTraits parsedTraits1 = parsed.get(MATERIAL_ID_1); assertThat(parsedTraits1).isNotNull(); // default assertThat(parsedTraits1.getDefaultTraits()).hasSize(2); ModifierEntry trait1 = parsedTraits1.getDefaultTraits().get(0); assertThat(trait1.getModifier()).isEqualTo(ModifierFixture.TEST_MODIFIER_1); assertThat(trait1.getLevel()).isEqualTo(1); ModifierEntry trait2 = parsedTraits1.getDefaultTraits().get(1); assertThat(trait2.getModifier()).isEqualTo(ModifierFixture.TEST_MODIFIER_2); assertThat(trait2.getLevel()).isEqualTo(2); // per stat assertThat(parsedTraits1.getTraitsPerStats()).isEmpty(); // material traits 2 MaterialTraits parsedTraits2 = parsed.get(MATERIAL_ID_2); assertThat(parsedTraits2).isNotNull(); // default assertThat(parsedTraits2.getDefaultTraits()).hasSize(1); trait1 = parsedTraits2.getDefaultTraits().get(0); assertThat(trait1.getModifier()).isEqualTo(ModifierFixture.TEST_MODIFIER_1); assertThat(trait1.getLevel()).isEqualTo(3); // per stat type assertThat(parsedTraits2.getTraitsPerStats()).hasSize(2); // stat type 1 List<ModifierEntry> traitsForStats1 = parsedTraits2.getTraits(MaterialStatsFixture.STATS_TYPE); assertThat(traitsForStats1).isNotNull(); assertThat(traitsForStats1).hasSize(2); trait1 = traitsForStats1.get(0); assertThat(trait1.getModifier()).isEqualTo(ModifierFixture.TEST_MODIFIER_1); assertThat(trait1.getLevel()).isEqualTo(4); trait2 = traitsForStats1.get(1); assertThat(trait2.getModifier()).isEqualTo(ModifierFixture.TEST_MODIFIER_2); assertThat(trait2.getLevel()).isEqualTo(5); // stat type 2 List<ModifierEntry> traitsForStats2 = parsedTraits2.getTraits(MaterialStatsFixture.STATS_TYPE_2); assertThat(traitsForStats2).isNotNull(); assertThat(traitsForStats2).hasSize(1); trait1 = traitsForStats2.get(0); assertThat(trait1.getModifier()).isEqualTo(ModifierFixture.TEST_MODIFIER_2); assertThat(trait1.getLevel()).isEqualTo(6); } }
46.80198
179
0.785276
8052dec5cd3dbbfc29de45c51a316cd0254573b1
21,194
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.project.impl; import com.intellij.diagnostic.PluginException; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; import com.intellij.ide.startup.StartupManagerEx; import com.intellij.notification.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.PathMacros; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.components.ExtensionAreas; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.components.StorageScheme; import com.intellij.openapi.components.TrackingPathMacroSubstitutor; import com.intellij.openapi.components.impl.ComponentManagerImpl; import com.intellij.openapi.components.impl.ProjectPathMacroManager; import com.intellij.openapi.components.impl.stores.IComponentStore; import com.intellij.openapi.components.impl.stores.IProjectStore; import com.intellij.openapi.components.impl.stores.StoreUtil; import com.intellij.openapi.components.impl.stores.UnknownMacroNotification; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.ex.MessagesEx; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.impl.FrameTitleBuilder; import com.intellij.util.Function; import com.intellij.util.TimedReference; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.picocontainer.*; import org.picocontainer.defaults.CachingComponentAdapter; import org.picocontainer.defaults.ConstructorInjectionComponentAdapter; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; public class ProjectImpl extends ComponentManagerImpl implements ProjectEx { private static final Logger LOG = Logger.getInstance("#com.intellij.project.impl.ProjectImpl"); private static final String PLUGIN_SETTINGS_ERROR = "Plugin Settings Error"; private ProjectManagerImpl myManager; private volatile IProjectStore myComponentStore; private MyProjectManagerListener myProjectManagerListener; private final AtomicBoolean mySavingInProgress = new AtomicBoolean(false); public boolean myOptimiseTestLoadSpeed; @NonNls public static final String TEMPLATE_PROJECT_NAME = "Default (Template) Project"; private String myName; private String myOldName; public static Key<Long> CREATION_TIME = Key.create("ProjectImpl.CREATION_TIME"); protected ProjectImpl(ProjectManagerImpl manager, String filePath, boolean isOptimiseTestLoadSpeed, String projectName) { super(ApplicationManager.getApplication()); putUserData(CREATION_TIME, System.nanoTime()); getPicoContainer().registerComponentInstance(Project.class, this); getStateStore().setProjectFilePath(filePath); myOptimiseTestLoadSpeed = isOptimiseTestLoadSpeed; myManager = manager; myName = isDefault() ? TEMPLATE_PROJECT_NAME : projectName == null ? getStateStore().getProjectName() : projectName; if (!isDefault() && projectName != null && getStateStore().getStorageScheme().equals(StorageScheme.DIRECTORY_BASED)) { myOldName = ""; // new project } } @Override public void setProjectName(@NotNull String projectName) { if (!projectName.equals(myName)) { myOldName = myName; myName = projectName; StartupManager.getInstance(this).runWhenProjectIsInitialized(new DumbAwareRunnable() { @Override public void run() { if (isDisposed()) return; JFrame frame = WindowManager.getInstance().getFrame(ProjectImpl.this); String title = FrameTitleBuilder.getInstance().getProjectTitle(ProjectImpl.this); if (frame != null && title != null) { frame.setTitle(title); } } }); } } @Override protected void bootstrapPicoContainer() { Extensions.instantiateArea(ExtensionAreas.IDEA_PROJECT, this, null); super.bootstrapPicoContainer(); final MutablePicoContainer picoContainer = getPicoContainer(); final ProjectStoreClassProvider projectStoreClassProvider = (ProjectStoreClassProvider)picoContainer.getComponentInstanceOfType(ProjectStoreClassProvider.class); picoContainer.registerComponentImplementation(ProjectPathMacroManager.class); picoContainer.registerComponent(new ComponentAdapter() { ComponentAdapter myDelegate; public ComponentAdapter getDelegate() { if (myDelegate == null) { final Class storeClass = projectStoreClassProvider.getProjectStoreClass(isDefault()); myDelegate = new CachingComponentAdapter( new ConstructorInjectionComponentAdapter(storeClass, storeClass, null, true)); } return myDelegate; } @Override public Object getComponentKey() { return IComponentStore.class; } @Override public Class getComponentImplementation() { return getDelegate().getComponentImplementation(); } @Override public Object getComponentInstance(final PicoContainer container) throws PicoInitializationException, PicoIntrospectionException { return getDelegate().getComponentInstance(container); } @Override public void verify(final PicoContainer container) throws PicoIntrospectionException { getDelegate().verify(container); } @Override public void accept(final PicoVisitor visitor) { visitor.visitComponentAdapter(this); getDelegate().accept(visitor); } }); } @NotNull @Override public IProjectStore getStateStore() { IProjectStore componentStore = myComponentStore; if (componentStore != null) return componentStore; synchronized (this) { componentStore = myComponentStore; if (componentStore == null) { myComponentStore = componentStore = (IProjectStore)getPicoContainer().getComponentInstance(IComponentStore.class); } return componentStore; } } @Override public void initializeComponent(Object component, boolean service) { if (!service) { ProgressIndicator indicator = getProgressIndicator(); if (indicator != null) { indicator.setText2(getComponentName(component)); // indicator.setIndeterminate(false); // indicator.setFraction(myComponentsRegistry.getPercentageOfComponentsLoaded()); } } getStateStore().initComponent(component, service); } @Override public boolean isOpen() { return ProjectManagerEx.getInstanceEx().isProjectOpened(this); } @Override public boolean isInitialized() { return isOpen() && !isDisposed() && StartupManagerEx.getInstanceEx(this).startupActivityPassed(); } public void loadProjectComponents() { final IdeaPluginDescriptor[] plugins = PluginManager.getPlugins(); for (IdeaPluginDescriptor plugin : plugins) { if (PluginManager.shouldSkipPlugin(plugin)) continue; loadComponentsConfiguration(plugin.getProjectComponents(), plugin, isDefault()); } } @Override @NotNull public String getProjectFilePath() { return getStateStore().getProjectFilePath(); } @Override public VirtualFile getProjectFile() { return getStateStore().getProjectFile(); } @Override public VirtualFile getBaseDir() { return getStateStore().getProjectBaseDir(); } @Override public String getBasePath() { return getStateStore().getProjectBasePath(); } @NotNull @Override public String getName() { return myName; } @NonNls @Override public String getPresentableUrl() { if (myName == null) return null; // not yet initialized return getStateStore().getPresentableUrl(); } @NotNull @NonNls @Override public String getLocationHash() { String str = getPresentableUrl(); if (str == null) str = getName(); final String prefix = getStateStore().getStorageScheme() == StorageScheme.DIRECTORY_BASED ? "" : getName(); return prefix + Integer.toHexString(str.hashCode()); } @SuppressWarnings("deprecation") @Nullable @NonNls @Override public String getLocation() { if (myName == null) return null; // was called before initialized return isDisposed() ? null : getStateStore().getLocation(); } @Override @Nullable public VirtualFile getWorkspaceFile() { return getStateStore().getWorkspaceFile(); } @Override public boolean isOptimiseTestLoadSpeed() { return myOptimiseTestLoadSpeed; } @Override public void setOptimiseTestLoadSpeed(final boolean optimiseTestLoadSpeed) { myOptimiseTestLoadSpeed = optimiseTestLoadSpeed; } @Override public void init() { long start = System.currentTimeMillis(); // ProfilingUtil.startCPUProfiling(); super.init(); // ProfilingUtil.captureCPUSnapshot(); long time = System.currentTimeMillis() - start; LOG.info(getComponentConfigurations().length + " project components initialized in " + time + " ms"); getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).projectComponentsInitialized(this); myProjectManagerListener = new MyProjectManagerListener(); myManager.addProjectManagerListener(this, myProjectManagerListener); } public boolean isToSaveProjectName() { if (!isDefault()) { final IProjectStore stateStore = getStateStore(); if (stateStore.getStorageScheme().equals(StorageScheme.DIRECTORY_BASED)) { final VirtualFile baseDir = stateStore.getProjectBaseDir(); if (baseDir != null && baseDir.isValid()) { return myOldName != null && !myOldName.equals(getName()); } } } return false; } @Override public void save() { if (ApplicationManagerEx.getApplicationEx().isDoNotSave()) return; //no need to save if (!mySavingInProgress.compareAndSet(false, true)) { return; } try { if (isToSaveProjectName()) { final IProjectStore stateStore = getStateStore(); final VirtualFile baseDir = stateStore.getProjectBaseDir(); if (baseDir != null && baseDir.isValid()) { final VirtualFile ideaDir = baseDir.findChild(DIRECTORY_STORE_FOLDER); if (ideaDir != null && ideaDir.isValid() && ideaDir.isDirectory()) { final File nameFile = new File(ideaDir.getPath(), ".name"); try { FileUtil.writeToFile(nameFile, getName().getBytes("UTF-8"), false); myOldName = null; } catch (IOException e) { LOG.info("Unable to store project name to: " + nameFile.getPath()); } } } } StoreUtil.doSave(getStateStore()); } catch (IComponentStore.SaveCancelledException e) { LOG.info(e); } catch (PluginException e) { PluginManager.disablePlugin(e.getPluginId().getIdString()); Notification notification = new Notification( PLUGIN_SETTINGS_ERROR, "Unable to save plugin settings!", "<p>The plugin <i>" + e.getPluginId() + "</i> failed to save settings and has been disabled. Please restart" + ApplicationNamesInfo.getInstance().getFullProductName() + "</p>" + (ApplicationManagerEx.getApplicationEx().isInternal() ? "<p>" + StringUtil.getThrowableText(e) + "</p>" : ""), NotificationType.ERROR); Notifications.Bus.notify(notification, this); LOG.info("Unable to save plugin settings",e); } catch (IOException e) { MessagesEx.error(this, ProjectBundle.message("project.save.error", e.getMessage())).showLater(); LOG.info("Error saving project", e); } finally { mySavingInProgress.set(false); ApplicationManager.getApplication().getMessageBus().syncPublisher(ProjectSaved.TOPIC).saved(this); } } @Override public synchronized void dispose() { ApplicationEx application = ApplicationManagerEx.getApplicationEx(); assert application.isWriteAccessAllowed(); // dispose must be under write action // can call dispose only via com.intellij.ide.impl.ProjectUtil.closeAndDispose() LOG.assertTrue(application.isUnitTestMode() || !ProjectManagerEx.getInstanceEx().isProjectOpened(this)); LOG.assertTrue(!isDisposed()); if (myProjectManagerListener != null) { myManager.removeProjectManagerListener(this, myProjectManagerListener); } disposeComponents(); Extensions.disposeArea(this); myManager = null; myProjectManagerListener = null; myComponentStore = null; super.dispose(); if (!application.isDisposed()) { application.getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).afterProjectClosed(this); } TimedReference.disposeTimed(); } private void projectOpened() { final ProjectComponent[] components = getComponents(ProjectComponent.class); for (ProjectComponent component : components) { try { component.projectOpened(); } catch (Throwable e) { LOG.error(component.toString(), e); } } } private void projectClosed() { List<ProjectComponent> components = new ArrayList<ProjectComponent>(Arrays.asList(getComponents(ProjectComponent.class))); Collections.reverse(components); for (ProjectComponent component : components) { try { component.projectClosed(); } catch (Throwable e) { LOG.error(e); } } } @Override public <T> T[] getExtensions(final ExtensionPointName<T> extensionPointName) { return Extensions.getArea(this).getExtensionPoint(extensionPointName).getExtensions(); } public String getDefaultName() { if (isDefault()) return TEMPLATE_PROJECT_NAME; return getStateStore().getProjectName(); } private class MyProjectManagerListener extends ProjectManagerAdapter { @Override public void projectOpened(Project project) { LOG.assertTrue(project == ProjectImpl.this); ProjectImpl.this.projectOpened(); } @Override public void projectClosed(Project project) { LOG.assertTrue(project == ProjectImpl.this); ProjectImpl.this.projectClosed(); } } @Override protected MutablePicoContainer createPicoContainer() { return Extensions.getArea(this).getPicoContainer(); } @Override public boolean isDefault() { return false; } @Override public void checkUnknownMacros(final boolean showDialog) { final IProjectStore stateStore = getStateStore(); final TrackingPathMacroSubstitutor[] substitutors = stateStore.getSubstitutors(); final Set<String> unknownMacros = new HashSet<String>(); for (final TrackingPathMacroSubstitutor substitutor : substitutors) { unknownMacros.addAll(substitutor.getUnknownMacros(null)); } if (!unknownMacros.isEmpty()) { if (!showDialog || ProjectMacrosUtil.checkMacros(this, new HashSet<String>(unknownMacros))) { final PathMacros pathMacros = PathMacros.getInstance(); final Set<String> macros2invalidate = new HashSet<String>(unknownMacros); for (Iterator it = macros2invalidate.iterator(); it.hasNext();) { final String macro = (String)it.next(); final String value = pathMacros.getValue(macro); if ((value == null || value.trim().isEmpty()) && !pathMacros.isIgnoredMacroName(macro)) { it.remove(); } } if (!macros2invalidate.isEmpty()) { final Set<String> components = new HashSet<String>(); for (TrackingPathMacroSubstitutor substitutor : substitutors) { components.addAll(substitutor.getComponents(macros2invalidate)); } if (stateStore.isReloadPossible(components)) { for (final TrackingPathMacroSubstitutor substitutor : substitutors) { substitutor.invalidateUnknownMacros(macros2invalidate); } final UnknownMacroNotification[] notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnknownMacroNotification.class, this); for (final UnknownMacroNotification notification : notifications) { if (macros2invalidate.containsAll(notification.getMacros())) notification.expire(); } ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { stateStore.reinitComponents(components, true); } }); } else { if (Messages.showYesNoDialog(this, "Component could not be reloaded. Reload project?", "Configuration Changed", Messages.getQuestionIcon()) == 0) { ProjectManagerEx.getInstanceEx().reloadProject(this); } } } } } } @NonNls @Override public String toString() { return "Project" + (isDisposed() ? " (Disposed" + (temporarilyDisposed ? " temporarily" : "") + ")" : isDefault() ? "" : " '" + getPresentableUrl() + "'") + (isDefault() ? " (Default)" : "") + " " + myName; } @Override protected boolean logSlowComponents() { return super.logSlowComponents() || ApplicationInfoImpl.getShadowInstance().isEAP(); } public static void dropUnableToSaveProjectNotification(@NotNull final Project project, final VirtualFile[] readOnlyFiles) { final UnableToSaveProjectNotification[] notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification.class, project); if (notifications.length == 0) { Notifications.Bus.notify(new UnableToSaveProjectNotification(project, readOnlyFiles), project); } } public static class UnableToSaveProjectNotification extends Notification { private Project myProject; private final String[] myFileNames; private UnableToSaveProjectNotification(@NotNull final Project project, final VirtualFile[] readOnlyFiles) { super("Project Settings", "Could not save project!", buildMessage(), NotificationType.ERROR, new NotificationListener() { @Override public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { final UnableToSaveProjectNotification unableToSaveProjectNotification = (UnableToSaveProjectNotification)notification; final Project _project = unableToSaveProjectNotification.getProject(); notification.expire(); if (_project != null && !_project.isDisposed()) { _project.save(); } } }); myProject = project; myFileNames = ContainerUtil.map(readOnlyFiles, new Function<VirtualFile, String>() { @Override public String fun(VirtualFile file) { return file.getPresentableUrl(); } }, new String[readOnlyFiles.length]); } public String[] getFileNames() { return myFileNames; } private static String buildMessage() { final StringBuilder sb = new StringBuilder( "<p>Unable to save project files. Please ensure project files are writable and you have permissions to modify them."); return sb.append(" <a href=\"\">Try to save project again</a>.</p>").toString(); } public Project getProject() { return myProject; } @Override public void expire() { myProject = null; super.expire(); } } }
35.382304
165
0.708219
bb93ca1bfc842ccbff0878678c344ac29fc1233e
1,708
package io.manbang.ebatis.sample; //import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.Environment; import java.net.InetAddress; import java.net.UnknownHostException; /** * @author 章多亮 * @since 2020/6/1 18:25 */ //@EnableSwaggerBootstrapUI @SpringBootApplication public class SampleApplication { static Logger logger= LoggerFactory.getLogger(SampleApplication.class); public static void main(String[] args) throws UnknownHostException { ConfigurableApplicationContext application=SpringApplication.run(SampleApplication.class, args); Environment env = application.getEnvironment(); String host= InetAddress.getLocalHost().getHostAddress(); String port=env.getProperty("server.port"); logger.info("\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\thttp://localhost:{}\n\t" + "External: \thttp://{}:{}\n\t"+ "Doc: \thttp://{}:{}/doc.html\n\t"+ "----------------------------------------------------------", env.getProperty("spring.application.name"), env.getProperty("server.port"), host,port, host,port); //SpringApplication.run(SampleApplication.class, args); } }
40.666667
104
0.620609
deaac246a3eabd1c19a4298edbe37daab7e90fe7
671
package org.jetlinks.community.logging.entity; import io.swagger.v3.oas.annotations.media.Schema; import lombok.*; import org.hswebframework.web.api.crud.entity.GenericEntity; import javax.persistence.*; @Getter @Setter @Table(name = "device_log") @NoArgsConstructor @AllArgsConstructor @Builder @Data public class DeviceLogEntity extends GenericEntity<String> { @Column @Schema(description = "设备ID") private String deviceId; @Column @Schema(description = "状态码") private String stateCode; @Column @Schema(description = "log序列号") private Integer logIndex; @Column @Schema(description = "备注信息") private String mark; }
19.735294
60
0.727273
fb2abf1eb5ed356655b780faf89e609bec1aadf0
4,479
package seedu.address.model; import static java.util.Objects.requireNonNull; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Objects; import seedu.address.commons.core.GuiSettings; /** * Represents User's preferences. */ public class UserPrefs implements ReadOnlyUserPrefs { private GuiSettings guiSettings = new GuiSettings(); private Path customerBookFilePath = Paths.get("data" , "customerbook.json"); private Path phoneBookFilePath = Paths.get("data" , "phonebook.json"); private Path scheduleBookFilePath = Paths.get("data" , "schedulebook.json"); private Path orderBookFilePath = Paths.get("data" , "orderbook.json"); private Path archivedOrderBookFilePath = Paths.get("data", "archivedbook.json"); /** * Creates a {@code UserPrefs} with default values. */ public UserPrefs() {} /** * Creates a {@code UserPrefs} with the prefs in {@code userPrefs}. */ public UserPrefs(ReadOnlyUserPrefs userPrefs) { this(); resetData(userPrefs); } /** * Resets the existing data of this {@code UserPrefs} with {@code newUserPrefs}. */ public void resetData(ReadOnlyUserPrefs newUserPrefs) { requireNonNull(newUserPrefs); setGuiSettings(newUserPrefs.getGuiSettings()); setCustomerBookFilePath(newUserPrefs.getCustomerBookFilePath()); setPhoneBookFilePath(newUserPrefs.getPhoneBookFilePath()); setScheduleBookFilePath(newUserPrefs.getScheduleBookFilePath()); setOrderBookFilePath(newUserPrefs.getOrderBookFilePath()); setArchivedOrderBookFilePath(newUserPrefs.getArchivedOrderBookFilePath()); } public GuiSettings getGuiSettings() { return guiSettings; } public void setGuiSettings(GuiSettings guiSettings) { requireNonNull(guiSettings); this.guiSettings = guiSettings; } public Path getCustomerBookFilePath() { return customerBookFilePath; } public void setCustomerBookFilePath(Path customerBookFilePath) { requireNonNull(customerBookFilePath); this.customerBookFilePath = customerBookFilePath; } public Path getPhoneBookFilePath() { return phoneBookFilePath; } public void setPhoneBookFilePath(Path phoneBookFilePath) { requireNonNull(phoneBookFilePath); this.phoneBookFilePath = phoneBookFilePath; } public Path getScheduleBookFilePath() { return scheduleBookFilePath; } public void setScheduleBookFilePath(Path scheduleBookFilePath) { requireNonNull(scheduleBookFilePath); this.scheduleBookFilePath = scheduleBookFilePath; } public Path getOrderBookFilePath() { return orderBookFilePath; } public void setOrderBookFilePath(Path orderBookFilePath) { requireNonNull(orderBookFilePath); this.orderBookFilePath = orderBookFilePath; } public Path getArchivedOrderBookFilePath() { return archivedOrderBookFilePath; } public void setArchivedOrderBookFilePath(Path archivedOrderBookFilePath) { requireNonNull(orderBookFilePath); this.archivedOrderBookFilePath = archivedOrderBookFilePath; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof UserPrefs)) { //this handles null as well. return false; } UserPrefs o = (UserPrefs) other; return guiSettings.equals(o.guiSettings) && customerBookFilePath.equals(o.customerBookFilePath) && phoneBookFilePath.equals(o.phoneBookFilePath) && scheduleBookFilePath.equals(o.scheduleBookFilePath) && orderBookFilePath.equals(o.orderBookFilePath) && archivedOrderBookFilePath.equals(o.archivedOrderBookFilePath); } @Override public int hashCode() { return Objects.hash(guiSettings); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Gui Settings : " + guiSettings); sb.append("\nCustomer data file location : " + customerBookFilePath); sb.append("\nPhone data file location : " + phoneBookFilePath); sb.append("\nSchedule data file location : " + scheduleBookFilePath); sb.append("\nOrder data file location : " + orderBookFilePath); return sb.toString(); } }
32.223022
84
0.684528
12f8f114604e52ab329dfa92c58782e5411de2fc
398
package br.com.oobj.controlefinanceiro; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; @ActiveProfiles("test") @TestConfiguration @TestPropertySource(locations = "classpath:application-test.properties") public class ControleFinanceiroTestContext { }
30.615385
73
0.824121
8914c4ad7227f794ed240c25475c9347663a654e
14,443
package org.intranet.graphics.raytrace.steps; import org.intranet.graphics.raytrace.Shape; import org.intranet.graphics.raytrace.World; import org.intranet.graphics.raytrace.primitive.Color; import org.intranet.graphics.raytrace.primitive.Matrix; import org.intranet.graphics.raytrace.primitive.Point; import org.intranet.graphics.raytrace.primitive.Tuple; import org.intranet.graphics.raytrace.primitive.Vector; import org.intranet.graphics.raytrace.shape.Cone; import org.intranet.graphics.raytrace.shape.Cube; import org.intranet.graphics.raytrace.shape.Cylinder; import org.intranet.graphics.raytrace.shape.FixedSequence; import org.intranet.graphics.raytrace.shape.Group; import org.intranet.graphics.raytrace.shape.Plane; import org.intranet.graphics.raytrace.shape.Sequence; import org.intranet.graphics.raytrace.shape.Sphere; import org.intranet.graphics.raytrace.surface.Material; import org.intranet.graphics.raytrace.surface.map.Canvas; import org.junit.Assert; import io.cucumber.java.ParameterType; public class CustomParameters implements StepPatterns { @ParameterType(wordPattern) public String identifier(String s) { return s; } @ParameterType("(" + doublePattern + "|-?infinity)") public double dbl(String s) { if ("infinity".equals(s)) return Double.POSITIVE_INFINITY; if ("-infinity".equals(s)) return Double.NEGATIVE_INFINITY; return Double.valueOf(s); } @ParameterType(name="boolean", value="(" + TRUE_PATTERN + "|[Ff][Aa][lL][sS][eE]|0|[nN][oO])") public Boolean bln(String str) { return str.matches("(" + TRUE_PATTERN + ")"); } @ParameterType("(min|max)") public String minMax(String s) { return s; } @ParameterType("tuple\\(" + fourDoublesPattern + "\\)") public Tuple tuple(String xStr, String yStr, String zStr, String wStr) { double x = Double.valueOf(xStr); double y = Double.valueOf(yStr); double z = Double.valueOf(zStr); double w = Double.valueOf(wStr); if (Tuple.dblEqual(1.0, w)) return new Point(x, y, z); else if (Tuple.dblEqual(0.0, w)) return new Vector(x, y, z); else return new Tuple(x, y, z, w); } @ParameterType(preferForRegexMatch = true, value = "point\\(" + threeDoublesPattern + "\\)") public Point point(String xStr, String yStr, String zStr) { double x = Double.valueOf(xStr); double y = Double.valueOf(yStr); double z = Double.valueOf(zStr); return new Point(x, y, z); } @ParameterType("point\\(" + doublePattern + ", " + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + "\\)") public Point pointNNS(String xStr, String yStr, String zNeg, String zSqrtStr, String zDenomStr) { double x = Double.valueOf(xStr); double y = Double.valueOf(yStr); double z = calcSqrtValue(zNeg, zSqrtStr, zDenomStr); return new Point(x, y, z); } @ParameterType("point\\(" + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + "\\)") public Point pointNSS(String xStr, String yNeg, String ySqrtStr, String yDenomStr, String zNeg, String zSqrtStr, String zDenomStr) { double x = Double.valueOf(xStr); double y = calcSqrtValue(yNeg, ySqrtStr, yDenomStr); double z = calcSqrtValue(zNeg, zSqrtStr, zDenomStr); return new Point(x, y, z); } @ParameterType("point\\((-?)√" + doublePattern + "/" + doublePattern + ", " + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + "\\)") public Point pointSNS(String xNeg, String xSqrtStr, String xDenomStr, String yStr, String zNeg, String zSqrtStr, String zDenomStr) { double x = calcSqrtValue(xNeg, xSqrtStr, xDenomStr); double y = Double.valueOf(yStr); double z = calcSqrtValue(zNeg, zSqrtStr, zDenomStr); return new Point(x, y, z); } @ParameterType("point\\((-?)√" + doublePattern + "/" + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + "\\)") public Point pointSSS( String xNeg, String xSqrtStr, String xDenomStr, String yNeg, String ySqrtStr, String yDenomStr, String zNeg, String zSqrtStr, String zDenomStr) { double x = calcSqrtValue(xNeg, xSqrtStr, xDenomStr); double y = calcSqrtValue(yNeg, ySqrtStr, yDenomStr); double z = calcSqrtValue(zNeg, zSqrtStr, zDenomStr); return new Point(x, y, z); } @ParameterType("point\\((-?)√" + doublePattern + "/" + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + ", " + doublePattern + "\\)") public Point pointSSN( String xNeg, String xSqrtStr, String xDenomStr, String yNeg, String ySqrtStr, String yDenomStr, String zStr) { double x = calcSqrtValue(xNeg, xSqrtStr, xDenomStr); double y = calcSqrtValue(yNeg, ySqrtStr, yDenomStr); double z = Double.valueOf(zStr); return new Point(x, y, z); } private double calcSqrtValue(String neg, String sqrtStr, String denomStr) { int sign = "-".equals(neg) ? -1 : 1; double num = Math.sqrt(Double.valueOf(sqrtStr)); double denom = Double.valueOf(denomStr); return sign * num / denom; } @ParameterType("point\\((-?)infinity, (-?)infinity, (-?)infinity\\)") public Point pointInfinity(String xNeg, String yNeg, String zNeg) { double x = infinityForSign(xNeg); double y = infinityForSign(yNeg); double z = infinityForSign(zNeg); return new Point(x, y, z); } @ParameterType("point\\(" + doublePattern + ", (-?)infinity, " + doublePattern + "\\)") public Point pointYinfinity(String xStr, String yNeg, String zStr) { double x = Double.valueOf(xStr); double y = infinityForSign(yNeg); double z = Double.valueOf(zStr); return new Point(x, y, z); } @ParameterType("point\\((-?)infinity, " + doublePattern + ", (-?)infinity\\)") public Point pointXZinfinity(String xNeg, String yStr, String zNeg) { double x = infinityForSign(xNeg); double y = Double.valueOf(yStr); double z = infinityForSign(zNeg); return new Point(x, y, z); } private double infinityForSign(String xNeg) { return "-".contentEquals(xNeg) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } @ParameterType("vector\\(" + threeDoublesPattern + "\\)") public Vector vector(String xStr, String yStr, String zStr) { double x = Double.valueOf(xStr); double y = Double.valueOf(yStr); double z = Double.valueOf(zStr); return new Vector(x, y, z); } @ParameterType("vector\\((-?)√2/2, (-?)√2/2, " + doublePattern + "\\)") public Vector vectorSSN(String xNeg, String yNeg, String zStr) { double x = calcSqrtValue(xNeg, "2", "2"); double y = calcSqrtValue(yNeg, "2", "2"); double z = Double.valueOf(zStr); return new Vector(x, y, z); } @ParameterType("vector\\(" + doublePattern + ", (-?)√2, " + doublePattern + "\\)") public Vector vectorNsN(String xStr, String yNeg, String zStr) { double x = Double.valueOf(xStr); int ySign = "-".equals(yNeg) ? -1 : 1; double yNum = Math.sqrt(2); double z = Double.valueOf(zStr); return new Vector(x, ySign * yNum, z); } @ParameterType("vector\\((-?)√" + doublePattern + "/" + doublePattern + ", " + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + "\\)") public Vector vectorSNS(String xNeg, String xNumStr, String xDenomStr, String yStr, String zNeg, String zNumStr, String zDenomStr) { int xSign = "-".equals(xNeg) ? -1 : 1; double xNumSqrt = Math.sqrt(Double.valueOf(xNumStr)); double xDenom = Double.valueOf(xDenomStr); double y = Double.valueOf(yStr); int zSign = "-".equals(zNeg) ? -1 : 1; double zNum = Math.sqrt(Double.valueOf(zNumStr)); double zDenom = Double.valueOf(zDenomStr); return new Vector(xSign * xNumSqrt / xDenom, y, zSign * zNum / zDenom); } @ParameterType("vector\\((-?)√" + doublePattern + "/" + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + ", (-?)√" + doublePattern + "/" + doublePattern + "\\)") public Vector vectorSSS(String xNeg, String xNumStr, String xDenomStr, String yNeg, String yNumStr, String yDenomStr, String zNeg, String zNumStr, String zDenomStr) { double x = calcSqrtValue(xNeg, xNumStr, xDenomStr); int ySign = "-".equals(yNeg) ? -1 : 1; double yNumSqrt = Math.sqrt(Double.valueOf(yNumStr)); double yDenom = Double.valueOf(yDenomStr); double y = ySign * yNumSqrt / yDenom; int zSign = "-".equals(zNeg) ? -1 : 1; double zNumSqrt = Math.sqrt(Double.valueOf(zNumStr)); double zDenom = Double.valueOf(zDenomStr); double z = zSign * zNumSqrt / zDenom; return new Vector(x, y, z); } @ParameterType("vector\\(" + doublePattern + ", (-?)√2/2, (-?)√2/2\\)") public Vector vectorNSS(String xStr, String yNeg, String zNeg) { double x = Double.valueOf(xStr); int ySign = "-".equals(yNeg) ? -1 : 1; double yNum = 2; double yDenom = 2; double y = Math.sqrt(yNum) / yDenom * ySign; double zNum = 2; double zDenom = 2; int zSign = "-".equals(zNeg) ? -1 : 1; double z = Math.sqrt(zNum) / zDenom * zSign; return new Vector(x, y, z); } @ParameterType("color\\(" + threeDoublesPattern + "\\)") public Color color(String redStr, String greenStr, String blueStr) { double red = Double.valueOf(redStr); double green = Double.valueOf(greenStr); double blue = Double.valueOf(blueStr); return new Color(red, green, blue); } @ParameterType("(translation|scaling)\\(" + threeDoublesPattern + "\\)") public Matrix matrix(String type, String xStr, String yStr, String zStr) { double x = Double.valueOf(xStr); double y = Double.valueOf(yStr); double z = Double.valueOf(zStr); return "translation".equals(type) ? Matrix.newTranslation(x, y, z) : Matrix.newScaling(x, y, z); } @ParameterType("shearing\\(" + sixDoublesPattern + "\\)") public Matrix shearing(String xyStr, String xzStr, String yxStr, String yzStr, String zxStr, String zyStr) { double xy = Double.valueOf(xyStr); double xz = Double.valueOf(xzStr); double yx = Double.valueOf(yxStr); double yz = Double.valueOf(yzStr); double zx = Double.valueOf(zxStr); double zy = Double.valueOf(zyStr); return Matrix.shearing(xy, xz, yx, yz, zx, zy); } @ParameterType("(rotation_x|rotation_y|rotation_z)\\(π[\\s ]*\\/[\\s ]*" + doublePattern + "\\)") public Matrix matrixRotationPiDiv(String type, String denomAmt) { double denom = Double.valueOf(denomAmt); double rotation = Math.PI / denom; switch (type) { case "rotation_z": return Matrix.newRotationZ(rotation); case "rotation_x": return Matrix.newRotationX(rotation); case "rotation_y": return Matrix.newRotationY(rotation); default: Assert.fail("Invalid type " + type); } return null; } @ParameterType("canvas\\(" + twoDoublesPattern + "\\)") public Canvas canvas(String widthStr, String heightStr) { int width = Integer.valueOf(widthStr); int height = Integer.valueOf(heightStr); return new Canvas(width, height); } @ParameterType("(sphere|glass_sphere|plane|cube|test_shape|group|cone|cylinder)\\(\\)") public Shape shape(String value) { switch (value) { case "sphere": return new Sphere(); case "glass_sphere": return createGlassSphere(); case "plane": return new Plane(); case "cube": return new Cube(); case "test_shape": return new TestShape(); case "cone": return new Cone(); case "cylinder": return new Cylinder(); case "group": return new Group(); default: Assert.fail("Unknown shape type " + value); } return null; } @ParameterType("default_world\\(\\)") public World default_world(String value) { return DefaultWorld.defaultWorld(); } @ParameterType("world\\(\\)") public World world(String value) { return new World(); } @ParameterType("test_pattern\\(\\)") public TestPattern test_pattern(String value) { return new TestPattern(); } @ParameterType("material\\(\\)") public Material emptyMaterial(String value) { return new Material(); } private Sphere createGlassSphere() { Sphere sphere = new Sphere(); Material material = sphere.getMaterial(); material.setTransparency(1.0); material.setRefractive(1.5); return sphere; } @ParameterType("(\\*|\\/)") public String multiplyDivide(String multDiv) { return multDiv; } @ParameterType("(\\+|\\-|\\*)") public String plusMinusTimes(String multDiv) { return multDiv; } @ParameterType("(\\+|\\-|)") public int sign(String multDiv) { return "-".equals(multDiv) ? -1 : 1; } @ParameterType("(=|!=)") public String equalNotEqual(String eqNe) { return eqNe; } @ParameterType("sequence\\(" + threeDoublesPattern + "\\)") public Sequence sequence3(String xStr, String yStr, String zStr) { double x = Double.valueOf(xStr); double y = Double.valueOf(yStr); double z = Double.valueOf(zStr); return new FixedSequence(x, y, z); } @ParameterType("sequence\\(" + twoDoublesPattern + "\\)") public Sequence sequence2(String xStr, String yStr) { double x = Double.valueOf(xStr); double y = Double.valueOf(yStr); return new FixedSequence(x, y); } @ParameterType("sequence\\(" + fiveDoublesPattern + "\\)") public Sequence sequence5(String str1, String str2, String str3, String str4, String str5) { double d1 = Double.valueOf(str1); double d2 = Double.valueOf(str2); double d3 = Double.valueOf(str3); double d4 = Double.valueOf(str4); double d5 = Double.valueOf(str5); return new FixedSequence(d1, d2, d3, d4, d5); } // @ParameterType("vector\\(" + threeDoublesPattern + ")") // public Vector vector(String type, String xStr, String yStr, String zStr) // { // double x = Double.valueOf(xStr); // double y = Double.valueOf(yStr); // double z = Double.valueOf(zStr); // // return new Vector(x, y, z); // } // @ParameterType("(scaling|translation)\\(" + threeDoublesPattern + "\\)\\)") // public Matrix matrixOperation(String operation, String xStr, String yStr, String zStr) // { // double x = Double.valueOf(xStr); // double y = Double.valueOf(yStr); // double z = Double.valueOf(zStr); // return "scaling".equals(operation) ? Matrix.newScaling(x, y, z) : // Matrix.newTranslation(x, y, z); // } }
30.278826
180
0.655542
a6229378050aa369d4504b0125919f36781a5e23
9,333
/* * Copyright 2013 David Jurgens * * This file is part of the Cluster-Comparison package and is covered under the * terms and conditions therein. * * The Cluster-Comparison package is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation and distributed hereunder to * you. * * THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES, * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER * RIGHTS. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package edu.ucla.clustercomparison; /** * A class for computing an approximation of <a * href="http://en.wikipedia.org/wiki/Differential_entropy">Differential * Entropy</a>, where samples from a continuous variable are discretized into * bins and the entropy is calcuated using <a * href="http://en.wikipedia.org/wiki/Information_entropy">discrete methods</a>. * This discrete approximation is necessary to avoid the potential negative * entropy values that may occur with differential entropy. The discretization * process transforms the <a * href="http://en.wikipedia.org/wiki/Probability_density_function">probability * density function</a> that would have been genreated from the samples into a * <a href="http://en.wikipedia.org/wiki/Multinomial_distribution">multinomial * distribution</a> over the probabiity a sample would occur in evenly spaced * value ranges. This class provides functionality for computing discrete * approximations of both differential entropy and conditional differential entropy. * * <p> This class's functionality is currently designed for use with fuzzy * variables, which imposes two major functional restrictions (which could be * removed with better engineering). First, the samples are expected to occur * in the range [0,1], which indicate membership in a fuzzy cluster. A robust * implementation would allow any sample value. Second, the class assumes * equally sized bins when discretizing the probability density function. More * advanced discretization methods could induce variable sized bins or identify * the optimal bin sizes from the data itself. However, no such process is * attempted in this implementation. * * <p> <i>Note</i>: due to the heavy use of this method, no input checking is * done to ensure the input samples are bounded in [0,1]. However, {@code * assert} statements are included, which allows the algorithm user to ensure * their input is well formed when the Java assertions are enabled. */ public class DiscretizedDifferentialEntropy { /** * The default number of bins used to divide the samples into in order to * compute the multinomial appromating the probability density function of a * random variable. */ private static final int DEFAULT_NUMBER_OF_BINS = 10; /** * Computes the multinomial approximation of the probability density * function of the variable samples in {@code var1samples}, and returns the * entropy of that multinomial as an approximation of the function's * differential entropy, using the default number of bins to discretize the * values. * * @param var1samples random samples from a continuous variable, bounded in * the range [0,1] */ public static double compute(double[] var1samples) { return compute(var1samples, DEFAULT_NUMBER_OF_BINS); } /** * Computes the multinomial approximation of the probability density * function of the variable samples in {@code var1samples}, and returns the * entropy of that multinomial as an approximation of the function's * differential entropy, using the specified number of bins to discretize the * values. * * @param var1samples random samples from a continuous variable, bounded in * the range [0,1] * @param numBins the number of bins in [0,1] into which the values in * {@code var1samples} should be discretized. For example, setting * this value to {@code 10} would produce bins with ranges of 0.1. */ public static double compute(double[] var1samples, int numBins) { assert checkBounds(var1samples) : "var1samples contains values " + "that are outside the bounds of [0,1]"; double numSamples = var1samples.length; Counter<Integer> binCounts = new Counter<Integer>(); // Discretizes the samples into bins for (int i = 0; i < var1samples.length; ++i) { double v1 = var1samples[i]; binCounts.count(bin(v1, numBins)); } double entropy = 0; for (int i = 0; i < numBins; ++i) { // Count how many items appeared in this bin int count = binCounts.get(i); if (count > 0) { double prob = count / numSamples; entropy += prob * Log.log2(prob); } } return -entropy; } /** * Computes the multinomial approximation of the probability density * functions of the two variables' samples and then returns the conditional * entropy of the two multinomials as an approximation of the two functions' * conditional differential entropy, using the default number of bins to * discretize the values. * * @param var1samples random samples from a continuous variable, bounded in * the range [0,1]. The number of samples should be the same as in * {@code var2samples}. * @param var2samples random samples from a continuous variable, bounded in * the range [0,1]. The number of samples should be the same as in * {@code var1samples}. */ public static double compute(double[] var1samples, double[] var2samples) { return compute(var1samples, var2samples, DEFAULT_NUMBER_OF_BINS); } /** * Computes the multinomial approximation of the probability density * functions of the two variables' samples and then returns the conditional * entropy of the two multinomials as an approximation of the two functions' * conditional differential entropy, using the default number of bins to * discretize the values. * * @param var1samples random samples from a continuous variable, bounded in * the range [0,1]. The number of samples should be the same as in * {@code var2samples}. * @param var2samples random samples from a continuous variable, bounded in * the range [0,1]. The number of samples should be the same as in * {@code var1samples}. * @param numBins the number of bins in [0,1] into which the values in * {@code var1samples} should be discretized. For example, setting * this value to {@code 10} would produce bins with ranges of 0.1. */ public static double compute(double[] var1samples, double[] var2samples, int numBins) { assert checkBounds(var1samples) : "var1samples contains values " + "that are outside the bounds of [0,1]"; assert checkBounds(var2samples) : "var2samples contains values " + "that are outside the bounds of [0,1]"; double numSamples = var1samples.length; Counter<Pair> jointBins = new Counter<Pair>(); // Discretizes the samples into bins for (int i = 0; i < var1samples.length; ++i) { double v1 = var1samples[i]; double v2 = var2samples[i]; jointBins.count(new Pair(bin(v1, numBins), bin(v2, numBins))); } double jointEntropy = 0; for (int i = 0; i < numBins; ++i) { for (int j = 0; j < numBins; ++j) { // Count how many items appeared in this joint bin int count = jointBins.get(new Pair(i, j)); if (count > 0) { double prob = count / numSamples; jointEntropy += prob * Log.log2(prob); } } } return -jointEntropy - compute(var2samples); } /** * Returns {@code true} if all the values in the sample are in the expected * range of [0,1]. This methods is used entirely for assertion-based input * validation. */ private static boolean checkBounds(double[] arr) { for (double d : arr) { if (d < 0 || d > 1) return false; } return true; } /** * Bins the value into one of {@code numBins} that exist in the range [0, 1] */ static int bin(double val, int numBins) { // Start at 1 to capture the first bin of [0, 1/numBins] for (int i = 1; i <= numBins; ++i) { if (val <= ((double)i) / numBins) return i - 1; } return numBins - 1; } }
44.442857
84
0.654881
cb2e1aaa13fd884672fc106041485f016a012e76
1,885
package info.manuelmayer.licensed.test; import java.time.LocalDate; import java.time.ZoneOffset; import javax.servlet.http.HttpServletRequest; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import info.manuelmayer.licensed.boot.LicensingConfiguration; import info.manuelmayer.licensed.service.LicensingRepository; import info.manuelmayer.licensed.service.SecurityContext; import info.manuelmayer.licensed.test.BaseLicensingIT.LicensedTestConfiguration; @RunWith(SpringRunner.class) @SpringBootTest(classes= { LicensingConfiguration.class, LicensedTestConfiguration.class }) @ActiveProfiles("test") public abstract class BaseLicensingIT { public static final String APPLICATION_KEY = "application"; @MockBean protected LicensedCode code; @MockBean protected LicensingRepository licensingRepo; @MockBean protected HttpServletRequest request; @MockBean protected SecurityContext securityContext; @TestConfiguration @Profile("test") public static class LicensedTestConfiguration { @Bean public TestClock clock() { return new TestClock(LocalDate.of(2016, 6, 4).atStartOfDay().toInstant(ZoneOffset.UTC)); } @Bean @Scope(proxyMode=ScopedProxyMode.TARGET_CLASS) public LicensedObject licensedObject(LicensedCode code) { return new LicensedObjectImpl(code); } } }
31.416667
92
0.796817
a34490193f47ae09c581fc5e4a1fdb9b81b9ca66
4,631
package com.yangsx95.da; import org.junit.Test; import java.util.Arrays; public class ClassicSortTest { public static void selectionSort(int[] arr) { if (arr == null || arr.length < 2) { return; } // 找出 0 ~ n-1 中的最小值的索引 // 找出 1 ~ n-1 中的最小值的索引 // 找出 2 ~ n-1 中的最小值的索引 // 找出 i ~ n-1 中的最小值的索引 for (int i = 0; i < arr.length; i++) { int minValueIndex = i; for (int j = i + 1; j < arr.length; j++) { minValueIndex = arr[j] < arr[minValueIndex] ? j : minValueIndex; } // 交换值,将每次最小都放入前面 swap(arr, i, minValueIndex); } } private static void swap(int[] arr, int i, int j) { int iV = arr[i]; arr[i] = arr[j]; arr[j] = iV; } @Test public void testSelectionSort() { int[] arr = new int[]{1, 3, 5, 3, 2, 9, 2, 5}; selectionSort(arr); System.out.println(Arrays.toString(arr)); } public static void bubbleSort(int[] arr) { if (arr == null || arr.length < 2) { return; } // 0 ~ n-1 // 0 ~ n-2 // 0 ~ n-3 // 0 ~ n-4 // 也就是 0 ~ end for (int end = arr.length - 1; end >= 0; end--) { // 在 0 ~ end 上对数进行两两比较,将最大的数冒泡到最后 // 需要循环 end-1 次,倒数第二次循环已经将最大值选出了 for (int i = 0; i <= end - 1; i++) { // 从1开始是为了不溢出 if (arr[i] > arr[i + 1]) { swap(arr, i, i + 1); } } } } public static void insertSort(int[] arr) { if (arr == null || arr.length < 2) { return; } // 0 ~ 0 // 0 ~ 1 范围有序 // 0 ~ 2 范围有序 // ... // 0 ~ n 范围有序 for (int end = 0; end < arr.length; end++) { // 排序新数 int newNumIndex = end; while (newNumIndex - 1 >= 0 && arr[newNumIndex - 1] > arr[newNumIndex]) { swap(arr, newNumIndex - 1, newNumIndex); newNumIndex--; } } } @Test public void testBubbleSort() { int[] arr = new int[]{1, 3, 5, 3, 2, 9, 2, 5}; bubbleSort(arr); System.out.println(Arrays.toString(arr)); } @Test public void testInsertSort() { int[] arr = new int[]{1, 3, 5, 3, 2, 9, 2, 5}; insertSort(arr); System.out.println(Arrays.toString(arr)); } /** * 递归实现归并排序 */ public void mergeSort1(int[] arr, int L, int R) { if (arr == null || arr.length < 2 || L < 0 || L >= arr.length || R < 0 || R >= arr.length || L >= R) { return; } process(arr, L, R); } public void process(int[] arr, int L, int R) { if (L == R) { return; } int M = (L + R) / 2; process(arr, L, M); process(arr, M + 1, R); merge(arr, L, M, R); } public void merge(int[] arr, int L, int M, int R) { int[] help = new int[R - L + 1]; // 创建一个用于盛放合并后数组的数组 int i = 0; // help的指针,每次填充后+1 int p1 = L; // 遍历左部分的指针 int p2 = M + 1;// 遍历有部分的指针 // p1 p2 都在正确的范围内 while (p1 <= M && p2 <= R) { help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++]; } // 如果p1在正确的范围内,说明p2循环完毕了 while (p1 <= M) { help[i++] = arr[p1++]; } // 如果p2在正确的范围内,说明p1循环完毕了 while (p2 <= R) { help[i++] = arr[p2++]; } // 将help排序后的内容填充到arr中 for (i = 0; i < help.length; i++) { arr[L + i] = help[i]; } } @Test public void testMergeSort1() { int[] arr = new int[]{9, 7, 3, 1, 0, 1, 4, 5, 9, 8, 0, 2}; mergeSort1(arr, 0, 5); System.out.println(Arrays.toString(arr)); } public void mergeSort2(int[] arr) { int k = 1; int i = 0; while (k <= arr.length) { if (i >= arr.length) { i = 0; k <<= 1; } // 左索引为i,右索引为 i + 2 * k - 1,且不能超过数组长度-1,中间为i + k - 1,且不能超过数组长度 int L = i; int R = Math.min(i + 2 * k - 1, arr.length - 1); int M = Math.min(i + k - 1, arr.length - 1); // 将小组合并为大组 merge(arr, L, M, R); // 重置i索引 i += 2 * k; } } @Test public void testMergeSort2() { int[] arr = new int[]{9, 7, 3, 1, 0, 1, 4, 5, 9, 8, 0, 2}; mergeSort2(arr); System.out.println(Arrays.toString(arr)); } }
26.016854
85
0.418916
dd9ac0df57cfab17c4b3547030c2711b99964c96
9,005
/* * 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.dolphinscheduler.plugin.alert.telegram; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.dolphinscheduler.alert.api.AlertData; import org.apache.dolphinscheduler.alert.api.AlertResult; import org.apache.dolphinscheduler.spi.utils.JSONUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public final class TelegramSender { private static final Logger logger = LoggerFactory.getLogger(TelegramSender.class); private static final String BOT_TOKEN_REGEX = "{botToken}"; private final String chatId; private final String parseMode; private final Boolean enableProxy; private String botToken; private String url; private String proxy; private Integer port; private String user; private String password; TelegramSender(Map<String, String> config) { url = config.get(TelegramParamsConstants.NAME_TELEGRAM_WEB_HOOK); botToken = config.get(TelegramParamsConstants.NAME_TELEGRAM_BOT_TOKEN); chatId = config.get(TelegramParamsConstants.NAME_TELEGRAM_CHAT_ID); parseMode = config.get(TelegramParamsConstants.NAME_TELEGRAM_PARSE_MODE); if (url == null || url.isEmpty()) { url = TelegramAlertConstants.TELEGRAM_PUSH_URL.replace(BOT_TOKEN_REGEX, botToken); } else { url = url.replace(BOT_TOKEN_REGEX, botToken); } enableProxy = Boolean.valueOf(config.get(TelegramParamsConstants.NAME_TELEGRAM_PROXY_ENABLE)); if (Boolean.TRUE.equals(enableProxy)) { port = Integer.parseInt(config.get(TelegramParamsConstants.NAME_TELEGRAM_PORT)); proxy = config.get(TelegramParamsConstants.NAME_TELEGRAM_PROXY); user = config.get(TelegramParamsConstants.NAME_TELEGRAM_USER); password = config.get(TelegramParamsConstants.NAME_TELEGRAM_PASSWORD); } } /** * sendMessage * * @param alertData alert data * @return alert result * @see <a href="https://core.telegram.org/bots/api#sendmessage">telegram bot api</a> */ public AlertResult sendMessage(AlertData alertData) { AlertResult result; try { String resp = sendInvoke(alertData.getTitle(), alertData.getContent()); result = parseRespToResult(resp); } catch (Exception e) { logger.warn("send telegram alert msg exception : {}", e.getMessage()); result = new AlertResult(); result.setStatus("false"); result.setMessage(String.format("send telegram alert fail. %s", e.getMessage())); } return result; } private AlertResult parseRespToResult(String resp) { AlertResult result = new AlertResult(); result.setStatus("false"); if (null == resp || resp.isEmpty()) { result.setMessage("send telegram msg error. telegram server resp is empty"); return result; } TelegramSendMsgResponse response = JSONUtils.parseObject(resp, TelegramSendMsgResponse.class); if (null == response) { result.setMessage("send telegram msg fail."); return result; } if (!response.isOk()) { result.setMessage(String.format("send telegram alert fail. telegram server error_code: %d, description: %s", response.errorCode, response.description)); } else { result.setStatus("true"); result.setMessage("send telegram msg success."); } return result; } private String sendInvoke(String title, String content) throws IOException { HttpPost httpPost = buildHttpPost(url, buildMsgJsonStr(content)); CloseableHttpClient httpClient; if (Boolean.TRUE.equals(enableProxy)) { httpClient = getProxyClient(proxy, port, user, password); RequestConfig rcf = getProxyConfig(proxy, port); httpPost.setConfig(rcf); } else { httpClient = getDefaultClient(); } try { CloseableHttpResponse response = httpClient.execute(httpPost); String resp; try { HttpEntity entity = response.getEntity(); resp = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } finally { response.close(); } logger.info("Telegram send title :{},content : {}, resp: {}", title, content, resp); return resp; } finally { httpClient.close(); } } private String buildMsgJsonStr(String content) { Map<String, Object> items = new HashMap<>(); items.put("chat_id", chatId); if (!isTextParseMode()) { items.put("parse_mode", parseMode); } items.put("text", content); return JSONUtils.toJsonString(items); } private boolean isTextParseMode() { return null == parseMode || TelegramAlertConstants.PARSE_MODE_TXT.equals(parseMode); } static class TelegramSendMsgResponse { @JsonProperty("ok") private Boolean ok; @JsonProperty("error_code") private Integer errorCode; @JsonProperty("description") private String description; @JsonProperty("result") private Object result; public boolean isOk() { return null != ok && ok; } public Boolean getOk() { return ok; } @JsonProperty("ok") public void setOk(Boolean ok) { this.ok = ok; } @JsonProperty("error_code") public void setErrorCode(Integer errorCode) { this.errorCode = errorCode; } public Integer getErrorCode() { return errorCode; } public String getDescription() { return description; } @JsonProperty("description") public void setDescription(String description) { this.description = description; } public Object getResult() { return result; } @JsonProperty("result") public void setResult(Object result) { this.result = result; } } private static HttpPost buildHttpPost(String url, String msg) { HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(msg, StandardCharsets.UTF_8); post.setEntity(entity); post.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); return post; } private static CloseableHttpClient getDefaultClient() { return HttpClients.createDefault(); } private static CloseableHttpClient getProxyClient(String proxy, int port, String user, String password) { HttpHost httpProxy = new HttpHost(proxy, port); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(httpProxy), new UsernamePasswordCredentials(user, password)); return HttpClients.custom().setDefaultCredentialsProvider(provider).build(); } private static RequestConfig getProxyConfig(String proxy, int port) { HttpHost httpProxy = new HttpHost(proxy, port); return RequestConfig.custom().setProxy(httpProxy).build(); } }
35.734127
120
0.663409
f84075dc5606f87e6086ed5ea4e83c6290f2be40
5,037
package com.zc.express.view.widget; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.TranslateAnimation; import android.widget.ScrollView; /** * 有弹性的ScrollView实现下拉弹回和上拉弹回 * Created by JK2DOG on 2017/1/19. */ public class SpringScrollView extends ScrollView { // 移动因子,手指移动100px,那么View就只移动50px private static final float MOVE_FACTOR = 0.5f; // 松开手指后, 界面回到正常位置需要的动画时间 private static final int ANIM_TIME = 300; // 手指按下时的Y值, 用于在移动时计算移动距离,如果按下时不能上拉和下拉,会在手指移动时更新为当前手指的Y值 private float startY; // ScrollView的唯一内容控件 private View contentView; // 用于记录正常的布局位置 private Rect originalRect = new Rect(); // 是否可以继续下拉 private boolean canPullDown = false; // 是否可以继续上拉 private boolean canPullUp = false; // 记录是否移动了布局 private boolean isMoved = false; public SpringScrollView(Context context) { super(context); } public SpringScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public SpringScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @SuppressLint("MissingSuperCall") @Override protected void onFinishInflate() { if (getChildCount() > 0) { contentView = getChildAt(0); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (contentView == null) { return; } // ScrollView中的唯一子控件的位置信息, 这个位置信息在整个控件的生命周期中保持不变 originalRect.set(contentView.getLeft(), contentView.getTop(), contentView.getRight(), contentView.getBottom()); } /** * 在触摸事件中, 处理上拉和下拉的逻辑 */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (contentView == null) { return super.dispatchTouchEvent(ev); } // 手指是否移动到了当前ScrollView控件之外 boolean isTouchOutOfScrollView = ev.getY() >= this.getHeight() || ev.getY() <= 0; if (isTouchOutOfScrollView) { // 如果移动到了当前ScrollView控件之外 if (isMoved) // 如果当前contentView已经被移动, 首先把布局移到原位置, 然后消费点这个事件 { boundBack(); } return true; } int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: // 判断是否可以上拉和下拉 canPullDown = isCanPullDown(); canPullUp = isCanPullUp(); // 记录按下时的Y值 startY = ev.getY(); break; case MotionEvent.ACTION_UP: boundBack(); break; case MotionEvent.ACTION_MOVE: // 在移动的过程中, 既没有滚动到可以上拉的程度, 也没有滚动到可以下拉的程度 if (!canPullDown && !canPullUp) { startY = ev.getY(); canPullDown = isCanPullDown(); canPullUp = isCanPullUp(); break; } // 计算手指移动的距离 float nowY = ev.getY(); int deltaY = (int) (nowY - startY); // 是否应该移动布局 boolean shouldMove = (canPullDown && deltaY > 0) // 可以下拉, 并且手指向下移动 || (canPullUp && deltaY < 0) // 可以上拉, 并且手指向上移动 || (canPullUp && canPullDown); // 既可以上拉也可以下拉(这种情况出现在ScrollView包裹的控件比ScrollView还小) if (shouldMove) { // 计算偏移量 int offset = (int) (deltaY * MOVE_FACTOR); // 随着手指的移动而移动布局 contentView.layout(originalRect.left, originalRect.top + offset, originalRect.right, originalRect.bottom + offset); isMoved = true; // 记录移动了布局 } break; } return super.dispatchTouchEvent(ev); } /** * 将内容布局移动到原位置 可以在UP事件中调用, 也可以在其他需要的地方调用, 如手指移动到当前ScrollView外时 */ private void boundBack() { if (!isMoved) { return; // 如果没有移动布局, 则跳过执行 } // 开启动画 TranslateAnimation anim = new TranslateAnimation(0, 0, contentView.getTop(), originalRect.top); anim.setDuration(ANIM_TIME); contentView.startAnimation(anim); // 设置回到正常的布局位置 contentView.layout(originalRect.left, originalRect.top, originalRect.right, originalRect.bottom); // 将标志位设回false canPullDown = false; canPullUp = false; isMoved = false; } /** * 判断是否滚动到顶部 */ private boolean isCanPullDown() { return getScrollY() == 0 || contentView.getHeight() < getHeight() + getScrollY(); } /** * 判断是否滚动到底部 */ private boolean isCanPullUp() { return contentView.getHeight() <= getHeight() + getScrollY(); } }
27.52459
105
0.567997
ad4ff1cd792938f98ab66f8617f95f33de674b2f
2,114
/********************************************************************************* * (Draw lines using the arrow keys) Write a program that draws line segments * * using the arrow keys. The line starts from the center of the pane and draws * * toward east, north, west, or south when the right-arrow key, up-arrow key, * * leftarrow key, or down-arrow key is pressed, as shown in Figure 15.26b. * *********************************************************************************/ import javafx.application.Application; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.shape.Polyline; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.Stage; public class Exercise_15_09 extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { // Create a pane Pane pane = new Pane(); // Create a polyline Polyline polyline = new Polyline(new Double(100.0), new Double(100.0)); polyline.setFill(Color.WHITE); polyline.setStroke(Color.BLACK); pane.getChildren().add(polyline); ObservableList<Double> list = polyline.getPoints(); // Create and register handler pane.setOnKeyPressed(e -> { double x = 0, y = 0; double length = 10; switch (e.getCode()) { case DOWN: x = list.get(list.size() - 2); y = list.get(list.size() - 1) + length; break; case UP: x = list.get(list.size() - 2); y = list.get(list.size() - 1) - length; break; case RIGHT: x = list.get(list.size() - 2) + length; y = list.get(list.size() - 1); break; case LEFT: x = list.get(list.size() - 2) - length; y = list.get(list.size() - 1); break; } list.add(x); list.add(y); }); // Create a scene and place it in the stage Scene scene = new Scene(pane, 200, 200); primaryStage.setTitle("Exercise_15_09"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage pane.requestFocus(); // Pane is focused to receive key input } }
38.436364
82
0.621097