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
227ae732fcc5be4a6336b00bac30a136d0f8333f
1,077
package com.company.Kursy_YauheniEkuntsevich.Lesson5_Methods.Zadaniya; public class method_12 { public static void main(String[] args) { int meth_1 = meth_1(); int meth_2 = meth_2(); int meth_3 = meth_3(); int meth_4 = meth_4(); int meth_5 = meth_5(); int meth_6 = meth_6(2); System.out.println(meth_1); System.out.println(meth_2); System.out.println(meth_3); System.out.println(meth_4); System.out.println(meth_5); System.out.println(meth_6); } static int meth_1() { int meth_1 = meth_2() + meth_3(); return meth_1; } static int meth_2() { int meth_4 = meth_4(); return meth_4 + 10; } static int meth_3() { int meth_4 = meth_4(); return meth_4 + 5; } static int meth_4() { int meth_4 = meth_6(2); return meth_4 * 2; } static int meth_5() { int meth_5 = meth_6(2); return meth_5 * 3; } static int meth_6(int a6) { return a6; } }
21.979592
70
0.545961
aab34ebf5e2a32bc84ffbb348beb77d8cfab6930
6,111
package org.jbei.ice.lib.models; import java.util.Set; import javax.persistence.*; import javax.xml.bind.annotation.XmlTransient; import org.jbei.ice.lib.dao.IDataModel; import org.jbei.ice.lib.dto.entry.SequenceInfo; import org.jbei.ice.lib.entry.model.Entry; import org.jbei.ice.lib.entry.model.EntryBooleanPropertiesBridge; import org.jbei.ice.lib.utils.SequenceFeatureCollection; import org.jbei.ice.lib.utils.SequenceUtils; import org.jbei.ice.lib.utils.UtilityException; import org.hibernate.annotations.Type; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.FieldBridge; /** * Stores the unique sequence for an {@link org.jbei.ice.lib.entry.model.Entry} object. * <p/> * <ul> * <li><b>sequence: </b>Normalized (lower cased, trimmed) sequence for {@link org.jbei.ice.lib.entry.model.Entry}.</li> * <li><b>sequenceUser: </b>Original sequence uploaded by the user. For example, the unparsed * genbank file, if that was the original upload. If the original upload does not exist, then this * field is the same as sequence.</li> * <li><b>fwdHash, revHash: </b>sha1 hash of the normalized sequence for fast searches.</li> * <li><b>sequenceFeatures: </b>{@link SequenceFeature} objects.</li> * </ul> * * @author Timothy Ham, Zinovii Dmytriv */ @Entity @Table(name = "sequences") @SequenceGenerator(name = "sequence", sequenceName = "sequences_id_seq", allocationSize = 1) public class Sequence implements IDataModel { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "sequence") private long id; @Column(name = "sequence") @Lob @Type(type = "org.hibernate.type.TextType") private String sequence; @Column(name = "identifier") private String identifier; @Column(name = "sequence_user") @Lob @Type(type = "org.hibernate.type.TextType") private String sequenceUser; @Column(name = "fwd_hash", length = 40) private String fwdHash; @Column(name = "rev_hash", length = 40) private String revHash; @Column(name = "uri") private String uri; @Column(name = "component_uri") private String componentUri; @Column(name = "file_name") private String fileName; @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "entries_id", nullable = true, unique = true) @Field(bridge = @FieldBridge(impl = EntryBooleanPropertiesBridge.class, params = { @org.hibernate.search.annotations.Parameter(name = "boolean", value = "hasSequence") })) private Entry entry; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "sequence") @OrderBy("id") private Set<SequenceFeature> sequenceFeatures = new SequenceFeatureCollection(); public Sequence() { } public Sequence(String sequence, String sequenceUser, String fwdHash, String revHash, Entry entry) { super(); this.sequence = sequence; this.sequenceUser = sequenceUser; this.fwdHash = fwdHash; this.revHash = revHash; this.entry = entry; } @XmlTransient public long getId() { return id; } public void setId(long id) { this.id = id; } public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence; setFwdHash(SequenceUtils.calculateSequenceHash(sequence)); try { setRevHash(SequenceUtils.calculateReverseComplementSequenceHash(sequence)); } catch (UtilityException e) { setRevHash(""); } } @XmlTransient public String getSequenceUser() { return sequenceUser; } public void setSequenceUser(String sequenceUser) { this.sequenceUser = sequenceUser; } @XmlTransient public String getFwdHash() { return fwdHash; } public void setFwdHash(String fwdHash) { this.fwdHash = fwdHash; } @XmlTransient public String getRevHash() { return revHash; } public void setRevHash(String revHash) { this.revHash = revHash; } @XmlTransient public Entry getEntry() { return entry; } public void setEntry(Entry entry) { this.entry = entry; } public Set<SequenceFeature> getSequenceFeatures() { /* Hibernate hack. To use costum collections with Hibernate, I have to implement all sorts of hibernate methods to do this correctly. Instead, I just replace this set when I do a get method here with the SequenceFeatureCollection. */ if (sequenceFeatures instanceof SequenceFeatureCollection) { } else { SequenceFeatureCollection newSequenceFeatures = new SequenceFeatureCollection(); newSequenceFeatures.addAll(sequenceFeatures); sequenceFeatures = newSequenceFeatures; } return sequenceFeatures; } public void setSequenceFeatures(Set<SequenceFeature> features) { sequenceFeatures = features; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } /** * @return uri for component that this sequence is a part of */ public String getComponentUri() { return componentUri; } public void setComponentUri(String componentUri) { this.componentUri = componentUri; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } @Override public SequenceInfo toDataTransferObject() { SequenceInfo info = new SequenceInfo(); if (this.entry != null) { info.setEntryId(entry.getId()); } info.setFilename(fileName); return info; } }
27.777273
119
0.661921
b0cf91576ce181e70d9889af6944f023f31740e4
9,433
package quests; import l2f.gameserver.model.instances.NpcInstance; import l2f.gameserver.model.quest.Quest; import l2f.gameserver.model.quest.QuestState; import l2f.gameserver.scripts.ScriptFile; public class _404_PathToWizard extends Quest implements ScriptFile { //npc public final int PARINA = 30391; public final int EARTH_SNAKE = 30409; public final int WASTELAND_LIZARDMAN = 30410; public final int FLAME_SALAMANDER = 30411; public final int WIND_SYLPH = 30412; public final int WATER_UNDINE = 30413; //mobs public final int RED_BEAR = 20021; public final int RATMAN_WARRIOR = 20359; public final int WATER_SEER = 27030; //items public final int MAP_OF_LUSTER_ID = 1280; public final int KEY_OF_FLAME_ID = 1281; public final int FLAME_EARING_ID = 1282; public final int BROKEN_BRONZE_MIRROR_ID = 1283; public final int WIND_FEATHER_ID = 1284; public final int WIND_BANGEL_ID = 1285; public final int RAMAS_DIARY_ID = 1286; public final int SPARKLE_PEBBLE_ID = 1287; public final int WATER_NECKLACE_ID = 1288; public final int RUST_GOLD_COIN_ID = 1289; public final int RED_SOIL_ID = 1290; public final int EARTH_RING_ID = 1291; public final int BEAD_OF_SEASON_ID = 1292; @Override public void onLoad() { } @Override public void onReload() { } @Override public void onShutdown() { } public _404_PathToWizard() { super(false); addStartNpc(PARINA); addTalkId(EARTH_SNAKE); addTalkId(WASTELAND_LIZARDMAN); addTalkId(FLAME_SALAMANDER); addTalkId(WIND_SYLPH); addTalkId(WATER_UNDINE); addKillId(RED_BEAR); addKillId(RATMAN_WARRIOR); addKillId(WATER_SEER); addQuestItem(new int[]{ KEY_OF_FLAME_ID, MAP_OF_LUSTER_ID, WIND_FEATHER_ID, BROKEN_BRONZE_MIRROR_ID, SPARKLE_PEBBLE_ID, RAMAS_DIARY_ID, RED_SOIL_ID, RUST_GOLD_COIN_ID, FLAME_EARING_ID, WIND_BANGEL_ID, WATER_NECKLACE_ID, EARTH_RING_ID }); } @Override public String onEvent(String event, QuestState st, NpcInstance npc) { String htmltext = event; if (event.equalsIgnoreCase("1")) { if (st.getPlayer().getClassId().getId() == 0x0a) { if (st.getPlayer().getLevel() >= 18) { if (st.getQuestItemsCount(BEAD_OF_SEASON_ID) > 0) htmltext = "parina_q0404_03.htm"; else { htmltext = "parina_q0404_08.htm"; st.setCond(1); st.setState(STARTED); st.playSound(SOUND_ACCEPT); } } else htmltext = "parina_q0404_02.htm"; } else if (st.getPlayer().getClassId().getId() == 0x0b) htmltext = "parina_q0404_02a.htm"; else htmltext = "parina_q0404_01.htm"; } else if (event.equalsIgnoreCase("30410_1")) if (st.getQuestItemsCount(WIND_FEATHER_ID) < 1) { htmltext = "lizardman_of_wasteland_q0404_03.htm"; st.giveItems(WIND_FEATHER_ID, 1); st.setCond(6); } return htmltext; } @Override public String onTalk(NpcInstance npc, QuestState st) { String htmltext = "noquest"; int npcId = npc.getNpcId(); int cond = st.getCond(); if (npcId == PARINA) { if (cond == 0) htmltext = "parina_q0404_04.htm"; else if (cond > 0 && st.getQuestItemsCount(FLAME_EARING_ID) < 1 | st.getQuestItemsCount(WIND_BANGEL_ID) < 1 | st.getQuestItemsCount(WATER_NECKLACE_ID) < 1 | st.getQuestItemsCount(EARTH_RING_ID) < 1) htmltext = "parina_q0404_05.htm"; else if (cond > 0 && st.getQuestItemsCount(FLAME_EARING_ID) > 0 && st.getQuestItemsCount(WIND_BANGEL_ID) > 0 && st.getQuestItemsCount(WATER_NECKLACE_ID) > 0 && st.getQuestItemsCount(EARTH_RING_ID) > 0) { htmltext = "parina_q0404_06.htm"; st.takeItems(FLAME_EARING_ID, st.getQuestItemsCount(FLAME_EARING_ID)); st.takeItems(WIND_BANGEL_ID, st.getQuestItemsCount(WIND_BANGEL_ID)); st.takeItems(WATER_NECKLACE_ID, st.getQuestItemsCount(WATER_NECKLACE_ID)); st.takeItems(EARTH_RING_ID, st.getQuestItemsCount(EARTH_RING_ID)); if (st.getPlayer().getClassId().getLevel() == 1) { if (st.getQuestItemsCount(BEAD_OF_SEASON_ID) < 1) st.giveItems(BEAD_OF_SEASON_ID, 1); if (!st.getPlayer().getVarB("prof1")) { st.getPlayer().setVar("prof1", "1", -1); st.addExpAndSp(295862, 18274); //FIXME [G1ta0] ะดะฐั‚ัŒ ะฐะดะตะฝั‹, ั‚ะพะปัŒะบะพ ะตัะปะธ ะฟะตั€ะฒั‹ะน ั‡ะฐั€ ะฝะฐ ะฐะบะบะต st.giveItems(ADENA_ID, 81900); } } st.playSound(SOUND_FINISH); st.exitCurrentQuest(true); } } else if (npcId == FLAME_SALAMANDER) { if (cond > 0 && st.getQuestItemsCount(MAP_OF_LUSTER_ID) < 1 && st.getQuestItemsCount(FLAME_EARING_ID) < 1) { st.giveItems(MAP_OF_LUSTER_ID, 1); htmltext = "flame_salamander_q0404_01.htm"; st.setCond(2); } else if (cond > 0 && st.getQuestItemsCount(MAP_OF_LUSTER_ID) > 0 && st.getQuestItemsCount(KEY_OF_FLAME_ID) < 1) htmltext = "flame_salamander_q0404_02.htm"; else if (cond == 3 && st.getQuestItemsCount(MAP_OF_LUSTER_ID) > 0 && st.getQuestItemsCount(KEY_OF_FLAME_ID) > 0) { st.takeItems(KEY_OF_FLAME_ID, -1); st.takeItems(MAP_OF_LUSTER_ID, -1); if (st.getQuestItemsCount(FLAME_EARING_ID) < 1) st.giveItems(FLAME_EARING_ID, 1); htmltext = "flame_salamander_q0404_03.htm"; st.setCond(4); } else if (cond > 0 && st.getQuestItemsCount(FLAME_EARING_ID) > 0) htmltext = "flame_salamander_q0404_04.htm"; } else if (npcId == WIND_SYLPH) { if (cond == 4 && st.getQuestItemsCount(FLAME_EARING_ID) > 0 && st.getQuestItemsCount(BROKEN_BRONZE_MIRROR_ID) < 1 && st.getQuestItemsCount(WIND_BANGEL_ID) < 1) { st.giveItems(BROKEN_BRONZE_MIRROR_ID, 1); htmltext = "wind_sylph_q0404_01.htm"; st.setCond(5); } else if (cond > 0 && st.getQuestItemsCount(BROKEN_BRONZE_MIRROR_ID) > 0 && st.getQuestItemsCount(WIND_FEATHER_ID) < 1) htmltext = "wind_sylph_q0404_02.htm"; else if (cond > 0 && st.getQuestItemsCount(BROKEN_BRONZE_MIRROR_ID) > 0 && st.getQuestItemsCount(WIND_FEATHER_ID) > 0) { st.takeItems(WIND_FEATHER_ID, st.getQuestItemsCount(WIND_FEATHER_ID)); st.takeItems(BROKEN_BRONZE_MIRROR_ID, st.getQuestItemsCount(BROKEN_BRONZE_MIRROR_ID)); if (st.getQuestItemsCount(WIND_BANGEL_ID) < 1) st.giveItems(WIND_BANGEL_ID, 1); htmltext = "wind_sylph_q0404_03.htm"; st.setCond(7); } else if (cond > 0 && st.getQuestItemsCount(WIND_BANGEL_ID) > 0) htmltext = "wind_sylph_q0404_04.htm"; } else if (npcId == WASTELAND_LIZARDMAN) { if (cond > 0 && st.getQuestItemsCount(BROKEN_BRONZE_MIRROR_ID) > 0 && st.getQuestItemsCount(WIND_FEATHER_ID) < 1) htmltext = "lizardman_of_wasteland_q0404_01.htm"; else if (cond > 0 && st.getQuestItemsCount(BROKEN_BRONZE_MIRROR_ID) > 0 && st.getQuestItemsCount(WIND_FEATHER_ID) > 0) htmltext = "lizardman_of_wasteland_q0404_04.htm"; } else if (npcId == WATER_UNDINE) { if (cond == 7 && st.getQuestItemsCount(WIND_BANGEL_ID) > 0 && st.getQuestItemsCount(RAMAS_DIARY_ID) < 1 && st.getQuestItemsCount(WATER_NECKLACE_ID) < 1) { st.giveItems(RAMAS_DIARY_ID, 1); htmltext = "water_undine_q0404_01.htm"; st.setCond(8); } else if (cond > 0 && st.getQuestItemsCount(RAMAS_DIARY_ID) > 0 && st.getQuestItemsCount(SPARKLE_PEBBLE_ID) < 2) htmltext = "water_undine_q0404_02.htm"; else if (cond == 9 && st.getQuestItemsCount(RAMAS_DIARY_ID) > 0 && st.getQuestItemsCount(SPARKLE_PEBBLE_ID) > 1) { st.takeItems(SPARKLE_PEBBLE_ID, -1); st.takeItems(RAMAS_DIARY_ID, -1); if (st.getQuestItemsCount(WATER_NECKLACE_ID) < 1) st.giveItems(WATER_NECKLACE_ID, 1); htmltext = "water_undine_q0404_03.htm"; st.setCond(10); } else if (cond > 0 && st.getQuestItemsCount(WATER_NECKLACE_ID) > 0) htmltext = "water_undine_q0404_04.htm"; } else if (npcId == EARTH_SNAKE) if (cond > 0 && st.getQuestItemsCount(WATER_NECKLACE_ID) > 0 && st.getQuestItemsCount(RUST_GOLD_COIN_ID) < 1 && st.getQuestItemsCount(EARTH_RING_ID) < 1) { st.giveItems(RUST_GOLD_COIN_ID, 1); htmltext = "earth_snake_q0404_01.htm"; st.setCond(11); } else if (cond > 0 && st.getQuestItemsCount(RUST_GOLD_COIN_ID) > 0 && st.getQuestItemsCount(RED_SOIL_ID) < 1) htmltext = "earth_snake_q0404_02.htm"; else if (cond == 12 && st.getQuestItemsCount(RUST_GOLD_COIN_ID) > 0 && st.getQuestItemsCount(RED_SOIL_ID) > 0) { st.takeItems(RED_SOIL_ID, st.getQuestItemsCount(RED_SOIL_ID)); st.takeItems(RUST_GOLD_COIN_ID, st.getQuestItemsCount(RUST_GOLD_COIN_ID)); if (st.getQuestItemsCount(EARTH_RING_ID) < 1) st.giveItems(EARTH_RING_ID, 1); htmltext = "earth_snake_q0404_04.htm"; st.setCond(13); } else if (cond > 0 && st.getQuestItemsCount(EARTH_RING_ID) > 0) htmltext = "earth_snake_q0404_04.htm"; return htmltext; } @Override public String onKill(NpcInstance npc, QuestState st) { int npcId = npc.getNpcId(); int cond = st.getCond(); if (npcId == RATMAN_WARRIOR) { if (cond == 2) { st.giveItems(KEY_OF_FLAME_ID, 1); st.playSound(SOUND_MIDDLE); st.setCond(3); } } else if (npcId == WATER_SEER) { if (cond == 8 && st.getQuestItemsCount(SPARKLE_PEBBLE_ID) < 2) { st.giveItems(SPARKLE_PEBBLE_ID, 1); if (st.getQuestItemsCount(SPARKLE_PEBBLE_ID) == 2) { st.playSound(SOUND_MIDDLE); st.setCond(9); } else st.playSound(SOUND_ITEMGET); } } else if (npcId == RED_BEAR) if (cond == 11) { st.giveItems(RED_SOIL_ID, 1); st.playSound(SOUND_MIDDLE); st.setCond(12); } return null; } }
32.527586
204
0.700095
ba3fd13ba3e8ffbf0d261da672e85164e94241aa
17,678
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|karaf operator|. name|jaas operator|. name|modules operator|. name|ldap package|; end_package begin_import import|import name|java operator|. name|io operator|. name|File import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|file operator|. name|Path import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|file operator|. name|Paths import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|Subject import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|auth operator|. name|login operator|. name|LoginException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|server operator|. name|annotations operator|. name|CreateLdapServer import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|server operator|. name|annotations operator|. name|CreateTransport import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|server operator|. name|core operator|. name|annotations operator|. name|ApplyLdifFiles import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|server operator|. name|core operator|. name|annotations operator|. name|CreateDS import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|server operator|. name|core operator|. name|annotations operator|. name|CreatePartition import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|server operator|. name|core operator|. name|integ operator|. name|AbstractLdapTestUnit import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|directory operator|. name|server operator|. name|core operator|. name|integ operator|. name|FrameworkRunner import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|felix operator|. name|utils operator|. name|properties operator|. name|Properties import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|jaas operator|. name|boot operator|. name|principal operator|. name|RolePrincipal import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|jaas operator|. name|boot operator|. name|principal operator|. name|UserPrincipal import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|jaas operator|. name|modules operator|. name|NamePubkeyCallbackHandler import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|karaf operator|. name|jaas operator|. name|modules operator|. name|PrincipalHelper operator|. name|names import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|karaf operator|. name|jaas operator|. name|modules operator|. name|ldap operator|. name|LdapPropsUpdater operator|. name|ldapProps import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|log4j operator|. name|Level import|; end_import begin_import import|import name|org operator|. name|hamcrest operator|. name|Matchers import|; end_import begin_import import|import static name|org operator|. name|hamcrest operator|. name|Matchers operator|. name|containsInAnyOrder import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|After import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertEquals import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertFalse import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertThat import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|fail import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Before import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|runner operator|. name|RunWith import|; end_import begin_class annotation|@ name|RunWith argument_list|( name|FrameworkRunner operator|. name|class argument_list|) annotation|@ name|CreateLdapServer argument_list|( name|transports operator|= block|{ annotation|@ name|CreateTransport argument_list|( name|protocol operator|= literal|"LDAP" argument_list|) block|} argument_list|) annotation|@ name|CreateDS argument_list|( name|name operator|= literal|"LdapPubkeyLoginModuleTest-class" argument_list|, name|partitions operator|= block|{ annotation|@ name|CreatePartition argument_list|( name|name operator|= literal|"example" argument_list|, name|suffix operator|= literal|"dc=example,dc=com" argument_list|) block|} argument_list|) annotation|@ name|ApplyLdifFiles argument_list|( literal|"org/apache/karaf/jaas/modules/ldap/example.com_pubkey.ldif" argument_list|) specifier|public class|class name|LDAPPubkeyLoginModuleTest extends|extends name|AbstractLdapTestUnit block|{ specifier|private specifier|static specifier|final name|String name|LDAP_PROPERTIES_FILE init|= literal|"org/apache/karaf/jaas/modules/ldap/ldap_pubkey.properties" decl_stmt|; annotation|@ name|Before specifier|public name|void name|updatePort parameter_list|() throws|throws name|Exception block|{ name|ldapProps argument_list|( name|LDAP_PROPERTIES_FILE argument_list|, name|LdapLoginModuleTest operator|:: name|replacePort argument_list|) expr_stmt|; block|} specifier|public specifier|static name|String name|replacePort parameter_list|( name|String name|line parameter_list|) block|{ return|return name|line operator|. name|replaceAll argument_list|( literal|"portno" argument_list|, literal|"" operator|+ name|getLdapServer argument_list|() operator|. name|getPort argument_list|() argument_list|) return|; block|} annotation|@ name|After specifier|public name|void name|tearDown parameter_list|() block|{ name|LDAPCache operator|. name|clear argument_list|() expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testAdminLogin parameter_list|() throws|throws name|Exception block|{ name|Properties name|options init|= name|ldapLoginModuleOptions argument_list|() decl_stmt|; name|LDAPPubkeyLoginModule name|module init|= operator|new name|LDAPPubkeyLoginModule argument_list|() decl_stmt|; name|Subject name|subject init|= operator|new name|Subject argument_list|() decl_stmt|; name|Path name|pubkeyFile init|= name|srcTestResourcePath argument_list|( literal|"org/apache/karaf/jaas/modules/ldap/ldaptest.admin.id_rsa" argument_list|) decl_stmt|; name|module operator|. name|initialize argument_list|( name|subject argument_list|, operator|new name|NamePubkeyCallbackHandler argument_list|( literal|"admin" argument_list|, name|pubkeyFile argument_list|) argument_list|, literal|null argument_list|, name|options argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"Precondition" argument_list|, literal|0 argument_list|, name|subject operator|. name|getPrincipals argument_list|() operator|. name|size argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|module operator|. name|login argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|module operator|. name|commit argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|2 argument_list|, name|subject operator|. name|getPrincipals argument_list|() operator|. name|size argument_list|() argument_list|) expr_stmt|; name|assertThat argument_list|( name|names argument_list|( name|subject operator|. name|getPrincipals argument_list|( name|UserPrincipal operator|. name|class argument_list|) argument_list|) argument_list|, name|containsInAnyOrder argument_list|( literal|"admin" argument_list|) argument_list|) expr_stmt|; name|assertThat argument_list|( name|names argument_list|( name|subject operator|. name|getPrincipals argument_list|( name|RolePrincipal operator|. name|class argument_list|) argument_list|) argument_list|, name|containsInAnyOrder argument_list|( literal|"admin" argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|module operator|. name|logout argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"Principals should be gone as the user has logged out" argument_list|, literal|0 argument_list|, name|subject operator|. name|getPrincipals argument_list|() operator|. name|size argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testNonAdminLogin parameter_list|() throws|throws name|Exception block|{ name|Properties name|options init|= name|ldapLoginModuleOptions argument_list|() decl_stmt|; name|LDAPPubkeyLoginModule name|module init|= operator|new name|LDAPPubkeyLoginModule argument_list|() decl_stmt|; name|Subject name|subject init|= operator|new name|Subject argument_list|() decl_stmt|; name|Path name|pubkeyFile init|= name|srcTestResourcePath argument_list|( literal|"org/apache/karaf/jaas/modules/ldap/ldaptest.cheese.id_rsa" argument_list|) decl_stmt|; name|module operator|. name|initialize argument_list|( name|subject argument_list|, operator|new name|NamePubkeyCallbackHandler argument_list|( literal|"cheese" argument_list|, name|pubkeyFile argument_list|) argument_list|, literal|null argument_list|, name|options argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"Precondition" argument_list|, literal|0 argument_list|, name|subject operator|. name|getPrincipals argument_list|() operator|. name|size argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|module operator|. name|login argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|module operator|. name|commit argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|subject operator|. name|getPrincipals argument_list|() operator|. name|size argument_list|() argument_list|) expr_stmt|; name|assertThat argument_list|( name|names argument_list|( name|subject operator|. name|getPrincipals argument_list|( name|UserPrincipal operator|. name|class argument_list|) argument_list|) argument_list|, name|containsInAnyOrder argument_list|( literal|"cheese" argument_list|) argument_list|) expr_stmt|; name|assertThat argument_list|( name|names argument_list|( name|subject operator|. name|getPrincipals argument_list|( name|RolePrincipal operator|. name|class argument_list|) argument_list|) argument_list|, name|Matchers operator|. name|empty argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|module operator|. name|logout argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"Principals should be gone as the user has logged out" argument_list|, literal|0 argument_list|, name|subject operator|. name|getPrincipals argument_list|() operator|. name|size argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testBadPrivateKey parameter_list|() throws|throws name|Exception block|{ name|Properties name|options init|= name|ldapLoginModuleOptions argument_list|() decl_stmt|; name|LDAPPubkeyLoginModule name|module init|= operator|new name|LDAPPubkeyLoginModule argument_list|() decl_stmt|; name|Subject name|subject init|= operator|new name|Subject argument_list|() decl_stmt|; name|Path name|pubkeyFile init|= name|srcTestResourcePath argument_list|( literal|"org/apache/karaf/jaas/modules/ldap/ldaptest.cheese.id_rsa" argument_list|) decl_stmt|; name|module operator|. name|initialize argument_list|( name|subject argument_list|, operator|new name|NamePubkeyCallbackHandler argument_list|( literal|"admin" argument_list|, name|pubkeyFile argument_list|) argument_list|, literal|null argument_list|, name|options argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"Precondition" argument_list|, literal|0 argument_list|, name|subject operator|. name|getPrincipals argument_list|() operator|. name|size argument_list|() argument_list|) expr_stmt|; name|org operator|. name|apache operator|. name|log4j operator|. name|Logger name|logger init|= name|org operator|. name|apache operator|. name|log4j operator|. name|Logger operator|. name|getLogger argument_list|( name|LDAPLoginModule operator|. name|class argument_list|) decl_stmt|; name|Level name|oldLevel init|= name|logger operator|. name|getLevel argument_list|() decl_stmt|; name|logger operator|. name|setLevel argument_list|( name|Level operator|. name|OFF argument_list|) expr_stmt|; try|try block|{ name|module operator|. name|login argument_list|() expr_stmt|; name|fail argument_list|( literal|"Should have thrown LoginException" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|LoginException name|e parameter_list|) block|{ name|assertTrue argument_list|( name|e operator|. name|getMessage argument_list|() operator|. name|startsWith argument_list|( literal|"Authentication failed" argument_list|) argument_list|) expr_stmt|; block|} finally|finally block|{ name|logger operator|. name|setLevel argument_list|( name|oldLevel argument_list|) expr_stmt|; block|} block|} annotation|@ name|Test specifier|public name|void name|testUserNotFound parameter_list|() throws|throws name|Exception block|{ name|Properties name|options init|= name|ldapLoginModuleOptions argument_list|() decl_stmt|; name|LDAPPubkeyLoginModule name|module init|= operator|new name|LDAPPubkeyLoginModule argument_list|() decl_stmt|; name|Subject name|subject init|= operator|new name|Subject argument_list|() decl_stmt|; name|Path name|pubkeyFile init|= name|srcTestResourcePath argument_list|( literal|"org/apache/karaf/jaas/modules/ldap/ldaptest.admin.id_rsa" argument_list|) decl_stmt|; name|module operator|. name|initialize argument_list|( name|subject argument_list|, operator|new name|NamePubkeyCallbackHandler argument_list|( literal|"imnothere" argument_list|, name|pubkeyFile argument_list|) argument_list|, literal|null argument_list|, name|options argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"Precondition" argument_list|, literal|0 argument_list|, name|subject operator|. name|getPrincipals argument_list|() operator|. name|size argument_list|() argument_list|) expr_stmt|; name|assertFalse argument_list|( name|module operator|. name|login argument_list|() argument_list|) expr_stmt|; block|} specifier|private name|Path name|srcTestResourcePath parameter_list|( name|String name|relativePath parameter_list|) throws|throws name|IOException block|{ name|String name|basedir init|= name|System operator|. name|getProperty argument_list|( literal|"basedir" argument_list|) decl_stmt|; if|if condition|( name|basedir operator|== literal|null condition|) block|{ name|basedir operator|= operator|new name|File argument_list|( literal|"." argument_list|) operator|. name|getCanonicalPath argument_list|() expr_stmt|; block|} name|Path name|pubkeyFile init|= name|Paths operator|. name|get argument_list|( name|basedir argument_list|, literal|"/src/test/resources/" argument_list|, name|relativePath argument_list|) decl_stmt|; return|return name|pubkeyFile return|; block|} specifier|protected name|Properties name|ldapLoginModuleOptions parameter_list|() throws|throws name|IOException block|{ name|String name|basedir init|= name|System operator|. name|getProperty argument_list|( literal|"basedir" argument_list|) decl_stmt|; if|if condition|( name|basedir operator|== literal|null condition|) block|{ name|basedir operator|= operator|new name|File argument_list|( literal|"." argument_list|) operator|. name|getCanonicalPath argument_list|() expr_stmt|; block|} name|File name|file init|= operator|new name|File argument_list|( name|basedir operator|+ literal|"/target/test-classes/" operator|+ name|LDAP_PROPERTIES_FILE argument_list|) decl_stmt|; return|return operator|new name|Properties argument_list|( name|file argument_list|) return|; block|} block|} end_class end_unit
14.007924
602
0.80818
f2e4041afabfc537e34a9bd9f7b0ddfcd2a0a1fa
1,655
package iiit.speech.dialog; import iiit.speech.domain.HealthDomain; import iiit.speech.itra.VaidyaActivity; import iiit.speech.nlu.NLU; /** * Created by danda on 7/13/16. */ public class DiseaseEnquiry extends DialogState { private VaidyaActivity app; private NLU nlu; public DiseaseEnquiry(VaidyaActivity a,NLU nlu1){ entered = false; app = a; nlu = nlu1; this.setName("disease_enquiry"); } @Override public void onEntry() { entered = true; current_grammar = app.DISEASE_QUERY_RESPONSE; app.speakOut("Enquire disease name or Diagnose disease name?", null); } @Override public void onRecognize(String hyp) { String detail_of_disease = nlu.findDiseaseInHyp(hyp); System.out.println("Hypothesis ======================>" + hyp); System.out.println(" detail_of_disease ======================>" + detail_of_disease); if(nlu.resolveGreetStateResponse(hyp).contains("ask symptoms")){ for (Integer sym : ((HealthDomain) domain).getSymptomsForDisease(detail_of_disease)) { //((HealthDomain) domain).addSymptoms(sym); } conclude = true; next_state = "ask_symptoms"; } else if (nlu.resolveGreetStateResponse(hyp).contains("disease enquiry")) { ((HealthDomain) domain).setDisease(detail_of_disease); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5"); conclude = true; next_state = "disease_details"; } } @Override public void onExit() { } }
29.553571
99
0.583686
c4504f6b36cfc81608913c5b0787925e3db3fe02
5,924
//@@author A0147984L package seedu.address.model.task; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.tag.Tag; import seedu.address.model.task.ReadOnlyRecurringTask.RecurringMode; import seedu.address.model.task.ReadOnlyTask.FinishProperty; import seedu.address.model.task.ReadOnlyTask.RecurringProperty; public class RecurringEventTest { private RecurringEvent tester; private static RecurringEvent sample; @Rule public ExpectedException thrown = ExpectedException.none(); @BeforeClass public static void oneTimeSetup() throws IllegalValueException { sample = new RecurringEvent(new Name("tester"), new TaskDate("20/12/2017"), new TaskTime("0:00"), new TaskDate("21/12/2017"), new TaskTime(""), new Description(""), new Tag(""), new Venue(""), new Priority(""), false, FinishProperty.FINISHED, RecurringMode.MONTH); } @Test public void constructor1_validInput_recurringEventConstructed() throws IllegalValueException { tester = new RecurringEvent(new Name("tester"), new TaskDate("20/12/2017"), new TaskTime("0:00"), new TaskDate("21/12/2017"), new TaskTime(""), new Description(""), new Tag(""), new Venue(""), new Priority(""), false, RecurringMode.MONTH); assertTrue(tester.isEvent()); assertTrue(tester.isRecurring()); assertFalse(tester.isFinished()); assertEquals(tester.getRecurringProperty(), RecurringProperty.RECURRING); assertEquals(tester.getMode(), RecurringMode.MONTH); assertEquals(tester.getRecurringPeriod(), "every month"); } @Test public void constructor2_validInput_recurringEventConstructed() throws IllegalValueException { tester = new RecurringEvent(new Name("tester"), new TaskDate("20/12/2017"), new TaskTime("0:00"), new TaskDate("21/12/2017"), new TaskTime(""), new Description(""), new Tag(""), new Venue(""), new Priority(""), false, FinishProperty.FINISHED, RecurringMode.MONTH); assertTrue(tester.isEvent()); assertTrue(tester.isRecurring()); assertTrue(tester.isFinished()); assertEquals(tester.getRecurringProperty(), RecurringProperty.RECURRING); assertEquals(tester.getMode(), RecurringMode.MONTH); assertEquals(tester.getRecurringPeriod(), "every month"); } @Test public void constructor3_validInput_recurringEventConstructed() throws IllegalValueException { tester = new RecurringEvent(new Name("tester"), new TaskDate("20/12/2017"), new TaskTime("6:10"), new TaskTime("6:20"), new Description(""), new Tag(""), new Venue(""), new Priority(""), false, RecurringMode.DAY); assertTrue(tester.isEvent()); assertTrue(tester.isRecurring()); assertFalse(tester.isFinished()); assertEquals(tester.getRecurringProperty(), RecurringProperty.RECURRING); assertEquals(tester.getMode(), RecurringMode.DAY); assertEquals(tester.getRecurringPeriod(), "every day"); } @Test public void constructor4_validInput_recurringEventConstructed() throws IllegalValueException { tester = new RecurringEvent(new Name("tester"), new TaskDate("20/12/2017"), new TaskTime("6:10"), new TaskTime("6:20"), new Description(""), new Tag(""), new Venue(""), new Priority(""), false, FinishProperty.UNFINISHED, RecurringMode.DAY); assertTrue(tester.isEvent()); assertTrue(tester.isRecurring()); assertFalse(tester.isFinished()); assertEquals(tester.getStartDate(), tester.getDate()); assertEquals(tester.getRecurringProperty(), RecurringProperty.RECURRING); assertEquals(tester.getMode(), RecurringMode.DAY); assertEquals(tester.getRecurringPeriod(), "every day"); assertFalse(tester.getDate().getValue().equals("")); } @Test public void constructor5_validInputAsReadOnlyEvent_recurringEventConstructed() throws IllegalValueException { tester = new RecurringEvent(sample); assertTrue(tester.isEvent()); assertTrue(tester.isRecurring()); assertTrue(tester.isFinished()); assertEquals(tester.getRecurringProperty(), RecurringProperty.RECURRING); assertEquals(tester.getMode(), RecurringMode.MONTH); assertEquals(tester.getRecurringPeriod(), "every month"); } @Test public void resetData_validInputAsReadOnlyEvent_recurringEventConstructed() throws IllegalValueException { tester = new RecurringEvent(new Name("tester"), new TaskDate("20/12/2017"), new TaskTime("6:10"), new TaskTime("6:20"), new Description(""), new Tag(""), new Venue(""), new Priority(""), false, RecurringMode.DAY); tester.resetData(sample); assertTrue(tester.isEvent()); assertTrue(tester.isRecurring()); assertTrue(tester.isFinished()); assertEquals(tester.getRecurringProperty(), RecurringProperty.RECURRING); assertEquals(tester.getMode(), RecurringMode.MONTH); assertEquals(tester.getRecurringPeriod(), "every month"); assertFalse(tester.getDate().getValue().equals("")); } @Test public void finishOnce_sampleRecurringEvent_dateIsIncreasedByOnePeriod() throws IllegalValueException { tester = new RecurringEvent(sample); tester.finishOnce(); assertEquals(tester.getDate().getValue(), "21/1/2018"); assertEquals(tester.getStartDate().getValue(), "20/1/2018"); } }
44.541353
110
0.680115
417de7886774ef270814b21cfddc5a9845b7832a
4,404
/* * 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.camel.component.jira.consumer; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import com.atlassian.jira.rest.client.api.domain.Issue; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.component.jira.JiraEndpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WatchUpdatesConsumer extends AbstractJiraConsumer { private static final transient Logger LOG = LoggerFactory.getLogger(WatchUpdatesConsumer.class); HashMap<Long, Issue> watchedIssues; List<String> watchedFieldsList; String watchedIssuesKeys; public WatchUpdatesConsumer(JiraEndpoint endpoint, Processor processor) { super(endpoint, processor); this.watchedFieldsList = new ArrayList<>(); this.watchedFieldsList = Arrays.asList(endpoint.getWatchedFields().split(",")); initIssues(); } private void initIssues() { watchedIssues = new HashMap<>(); List<Issue> issues = getIssues(((JiraEndpoint) getEndpoint()).getJql(), 0, 50, ((JiraEndpoint) getEndpoint()).getMaxResults()); issues.forEach(i -> watchedIssues.put(i.getId(), i)); watchedIssuesKeys = issues.stream() .map(Issue::getKey) .collect(Collectors.joining(",")); } @Override protected int poll() throws Exception { List<Issue> issues = getIssues(((JiraEndpoint) getEndpoint()).getJql(), 0, 50, ((JiraEndpoint) getEndpoint()).getMaxResults()); if (watchedIssues.values().size() != issues.size()) { init(); } for (Issue issue : issues) { checkIfIssueChanged(issue); } return 0; } private void checkIfIssueChanged(Issue issue) throws Exception { Issue original = watchedIssues.get(issue.getId()); AtomicBoolean issueChanged = new AtomicBoolean(false); if (original != null) { for (String field : this.watchedFieldsList) { if (hasFieldChanged(issue, original, field)) { issueChanged.set(true); } } if (issueChanged.get()) { watchedIssues.put(issue.getId(), issue); } } } private boolean hasFieldChanged(Issue changed, Issue original, String fieldName) throws Exception { Method get = Issue.class.getDeclaredMethod("get" + fieldName); Object originalField = get.invoke(original); Object changedField = get.invoke(changed); if (!Objects.equals(originalField, changedField)) { if (!((JiraEndpoint) getEndpoint()).isSendOnlyUpdatedField()) { processExchange(changed, changed.getKey(), fieldName); } else { processExchange(changedField, changed.getKey(), fieldName); } return true; } return false; } private void processExchange(Object body, String issueKey, String changed) throws Exception { Exchange e = getEndpoint().createExchange(); e.getIn().setBody(body); e.getIn().setHeader("issueKey", issueKey); e.getIn().setHeader("changed", changed); e.getIn().setHeader("watchedIssues", watchedIssuesKeys); LOG.debug(" {}: {} changed to {}", issueKey, changed, body); getProcessor().process(e); } }
38.631579
103
0.659855
048780b2c7eaa0f6630b1ecdd5b9b8d2ce78df32
1,128
package edyene; public class Pessoa { String nome, sexo; int idade, altura, peso; public Pessoa(String nome, int idade, String sexo, int altura, int peso) { this.nome = nome; this.idade = idade; this.sexo = sexo; this.altura = altura; this.peso = peso; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSexo() { return sexo; } public void setSexo(String sexo) { this.sexo = sexo; } public int getIdade() { return idade; } public void setIdade(int idade) { this.idade = idade; } public int getAltura() { return altura; } public void setAltura(int altura) { this.altura = altura; } public int getPeso() { return peso; } public void setPeso(int peso) { this.peso = peso; } public int calculaImc() { if (this.sexo == "m") { return (72 * (this.altura/100) - 58); } else { return (62 * (this.altura/100) - 44); } } @Override public String toString() { return "Pessoa [nome=" + nome + ", sexo=" + sexo + ", idade=" + idade + ", altura=" + altura + ", peso=" + peso + "]"; } }
16.347826
113
0.611702
683218f46fbf1a08f3a83991df303ab7a20d28d2
2,532
/* * Copyright (C) 2009-2012 Felix Bechstein * * This file is part of WebSMS. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * 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 de.ub0r.android.websms.connector.common; import java.util.HashMap; import java.util.Map; import android.os.Bundle; /** * Character table is replacing unwanted characters with well behaving ones. * * @author Thomas Pilarski <[email protected]>, Felix Bechstein * <[email protected]> */ public final class CharacterTable { /** Mapping. */ private final Map<String, String> mMap; /** * Default constructor. * * @param map * {@link Map} holding bad and good characters */ public CharacterTable(final Map<String, String> map) { // this.mMap = new HashMap<String, String>(map.size()); // this.mMap.putAll(map); this.mMap = map; } /** * Import from {@link Bundle} constructor. * * @param b * {@link Bundle} holding bad and good characters */ public CharacterTable(final Bundle b) { this.mMap = new HashMap<String, String>(b.size()); for (String k : b.keySet()) { this.mMap.put(k, b.getString(k)); } } /** * Encode {@link String}. * * @param str * {@link String} * @return encoded {@link String} */ public String encodeString(final String str) { final int l = str.length(); final StringBuffer strb = new StringBuffer(l); for (int i = 0; i < l; i++) { String s = str.substring(i, i + 1); String chr = this.mMap.get(s); if (chr == null) { strb.append(s); } else { strb.append(chr); } } return strb.toString(); } /** * @return inner {@link Map} */ public Map<String, String> getMap() { return this.mMap; } /** * @return inner {@link Map} as {@link Bundle} */ public Bundle getBundle() { final Bundle b = new Bundle(this.mMap.size()); for (String k : this.mMap.keySet()) { b.putString(k, this.mMap.get(k)); } return b; } }
24.823529
80
0.647314
bfeba0e2f1fae4cf2276f086a23c08a3c9617911
5,523
class b { } class SzJeAOImIGFLp { public void[] bt () { return null[ !true.QkPOTId3K_0PB()]; if ( -P0X()[ !--null.j]) return; KV0gFB6 hiizA5P; !!x6ZI2Ojs5()[ -!new os2mKfqfSXA()[ !-!new void[ uQeTLNoOc()[ !5878.wZnwhF0TLjZLJ]][ new boolean[ 968123.dseI3pGxdQMDs].E9ifFP]]]; int[] lx_tfJAlEsyg1 = ZlmRvVRQf1sz().cLjNZMld(); if ( ivYAx_()[ -!!5046259[ -SAqB.XQ]]) ;else while ( !-true[ 3.n]) ; if ( --t4_IFyILx6YJgk().SQf()) while ( --true.Kdogl()) return; IFaWVIgBxn xo = null.RTn834(); { RW_it qOVtBsw1zjfS; ; if ( true.vcCenpLt1CS()) if ( !39.A_2oukp94FI_z()) ; { if ( -!new lqrFMD7().sCX) { U[] oz; } } while ( new void[ c4Cy6B9h.g6kGdrLU].E()) ; --m16z9907yC.os; frDwyga[] DyxYTsQP9QyR; boolean nZL; JqDBwn[] Nlf_Tk; mK[][][] Xb; JCZoJ[] YmPN5v; { int[][] OVuZzR; } if ( !!-635.x2JyCnNZIhyIUJ) while ( !!!-( -299675.K_1yKXtWrnal).JVuL74qVE04M) { if ( 04804972.FM3SEZ) ; } ; jgid_Ct4OIlrx bGu; W UwD8IRCKiL; } int[][][] BT; int[][] agIr0Fq_wH7iGe; void vsh5L3KZ5 = -true.EAIYJNwbd1dQY(); return !-!!new fQCW5cCfPLd1ds[ -null[ HHSVgB().SA]].lhfRT(); boolean[] Ov; } public int[][][][] f1vErZ () throws lbFWr { -new void[ !---!( !new boolean[ 13692[ --new kRAXatQziqK().vDI]][ false.N7EYIhs()]).fiCdK()][ false[ new int[ -Jw.ZLZfOGYspeZ_Fj()].UI8P5oBCjH()]]; int nMfWbef6qxI; this.x6nij_; boolean Yqs1; ; int cmGc; void[] IFCReHC1jb9Tm = vnqc_yuo.pSIYoHcq() = !-!-3111116[ !-( -!!--!null[ new RX8().ai0XpNX()]).xSTbPXJxs()]; void IkXG9wzj = --null.IqvKU9NbVQEnHF(); int[][][][] cC2 = rj[ -!-0249.pK1qr()] = ( CEN_BToI8tx.H7m).lvFZE4Rq5H; EKMsU12Slh9X[] kmRH8af7O = T[ false.CC8()] = new Ow81KxRrTZm().PmO_j(); boolean _kW10F_kN; return U5().NUd; } public int sN8SbL () throws q { -new vYIM()[ new iLsAHeGOrP_0W5().gckn]; { while ( !null.nJw()) ; return; while ( new s91ISN7En().ikCgeTwUy) ; boolean dT1Ky9hsx; boolean Sy1QDN; return; if ( new int[ BGpZN().bououvRs6jZ()][ !!kvI.FaqyD5JelMcX_t]) { ; } pkMGO[] PESgvKAms; if ( -false.Mrtzgskf7F33) ; } boolean[] xTfk; int WTYn2Bo4xu; fEeCNw8c MXwtS; int YcPXN3M9AP; { int P1AjLKF7; boolean kG9; fo0UMIzHfgAa[][] naou; } gU b = this.B6AULNuYfvmv() = !false[ !RR0R4aUPcpVFQ().TQqfh3ACTUu8()]; if ( -( -new _IFsbzu4nt().kd5sf3()).CfAbe7i()) while ( this.ZOjkKhB3Q7wRI()) 803195362[ 7.mQi()]; } public LlpDEG[] G3g () throws X_e { -false.KS3(); while ( DSesmV().vmt()) ; if ( -!this.Gb4NOn8bFDZeuJ()) { void njtk7z1dNh; } void r_ = this.Ds = !!!-dU3.s8GGnbW; void IMj88; int D2BfuacQp1; return; void[] be8C0JGB0ZyS = new rBDxBD().YCl9(); return false.kFtar(); !--new int[ 78252733.YGq_EeQH()][ --!( !-false.chHPBy1LY()).dmf()]; ; { if ( !-( !!true[ -( false.svQtOLes96()).YO()])[ new BZL[ -!j.sS9z].pG()]) ( new pZCrsxHbuUo().cJi1U9).NHlZ7jc(); if ( true[ this[ 73.I9MVnAOGTW]]) while ( -S50().r5t()) return; sCYzTDBF[][][] y; boolean[][] G5gtD; ; if ( ( !-!!-!( 805293[ biEtaMk08jcz_.rj8vxH]).UK00roKX8())[ !new BA9CSVP6()[ new NxTST()[ -!new int[ -null.qpwiAT7F6385g][ -!new mtMn_7Xf8bi3a().LBFCM2dQH]]]]) return; if ( 377247473.sZY0v4()) while ( false.Wi52()) ; { boolean whS5NuvaUW; } { void[][][] _G5AOWWW0_; } while ( this[ new DsN()[ !3.X8ACvhfgOsV()]]) while ( true[ -new YX5FAVlW().L0dj3Q()]) while ( !new fKu().W) -!!new whKTB4W().AfSY1tof; ---hPEmw4[ Q5Jymd_5WSqhRt()._hkg()]; boolean[] ZngvpPHtxBaRo; LoKXO yDMaavLQEYF; LW[][][][][] d9s3T; } int[][] TrRF; boolean[] Xe; int[] q = -this[ null[ dh.uzgQvny]] = new RGzyMgZ().VnWA8kG0zf(); } } class WR4Ni { public static void sU (String[] jWRa_XFg) throws OUKS6Q_wb7r { ; ( DiH4XPrpNwn[ true.MoBsrHQl_g]).aOwWV3; int[] G; boolean BfO0RYyvx; if ( XTbyX1jmVSv[ !true[ null.T8bw6()]]) ; ; if ( EtIRvAlOHuymk().Qm7xppuNGQ) { boolean sKlrvMeToddX2; } if ( !( new TNSYAEOY()._8MCEkAxfvzVL).b2Cghc5CnS_TR()) return;else return; while ( -fpBQ[ !this.VOLy()]) !( -true[ A().i6kTSErH()])[ ( ( false.tH()).Vz0OlRXe73b()).DiJG7xrZtgHZy]; while ( 28.NzCQarFMCazB_G()) if ( -eHSh.OcULxE2R()) if ( -!---new UfOhztusSVnYw().CKS3) while ( -null.vvOPK_) { int mlvtUKa4jw2CY; } if ( !new O[ !true[ !new I4Bl().H_N57zmaNPreY2]].ELAwhTBKOEoR()) { int D_AGrNhX5Fi; }else ; int[] DMgkMoBDO; } }
36.82
179
0.47782
e1617ca45e3e2188984c974560ba3eeec4fda83e
7,896
/* * Copyright (C) 2017-2018 Dremio Corporation * * 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.dremio.exec.store.hive.exec; import java.io.IOException; import java.security.PrivilegedAction; import java.util.Collections; import java.util.List; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.security.UserGroupInformation; import com.dremio.common.AutoCloseables; import com.dremio.common.exceptions.UserException; import com.dremio.exec.ExecConstants; import com.dremio.exec.store.EmptyRecordReader; import com.dremio.exec.store.RecordReader; import com.dremio.exec.store.ScanFilter; import com.dremio.exec.store.dfs.FileSystemWrapper; import com.dremio.exec.store.dfs.implicit.CompositeReaderConfig; import com.dremio.exec.store.hive.HiveUtilities; import com.dremio.exec.store.parquet.ParquetFilterCondition; import com.dremio.exec.store.parquet.ParquetReaderFactory; import com.dremio.exec.store.parquet.ParquetScanFilter; import com.dremio.exec.store.parquet.SingletonParquetFooterCache; import com.dremio.exec.store.parquet.UnifiedParquetReader; import com.dremio.exec.util.ImpersonationUtil; import com.dremio.hive.proto.HiveReaderProto.HiveSplitXattr; import com.dremio.hive.proto.HiveReaderProto.HiveTableXattr; import com.dremio.hive.proto.HiveReaderProto.Prop; import com.dremio.options.OptionManager; import com.dremio.sabot.exec.context.OperatorContext; import com.dremio.sabot.exec.fragment.FragmentExecutionContext; import com.dremio.sabot.op.scan.ScanOperator; import com.dremio.sabot.op.spi.ProducerOperator; import com.dremio.service.namespace.dataset.proto.DatasetSplit; import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; /** * Helper class for {@link ScanWithDremioReader} to create a {@link ProducerOperator} that uses readers provided by * Dremio. */ class ScanWithDremioReader { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ScanWithDremioReader.class); static ProducerOperator createProducer( final HiveConf hiveConf, final FragmentExecutionContext fragmentExecContext, final OperatorContext context, final HiveSubScan config, final HiveTableXattr tableAttr, final CompositeReaderConfig compositeReader) { final JobConf jobConf = new JobConf(hiveConf); final OptionManager options = context.getOptions(); final boolean vectorize = options.getOption(ExecConstants.PARQUET_READER_VECTORIZE); final boolean enableDetailedTracing = options.getOption(ExecConstants.ENABLED_PARQUET_TRACING); final ParquetReaderFactory readerFactory = UnifiedParquetReader.getReaderFactory(context.getConfig()); if(config.getSplits().isEmpty()) { return new ScanOperator(fragmentExecContext.getSchemaUpdater(), config, context, Iterators.singletonIterator(new EmptyRecordReader())); } Iterable<RecordReader> readers = null; try { final UserGroupInformation currentUGI = UserGroupInformation.getCurrentUser(); final List<HiveParquetSplit> sortedSplits = Lists.newArrayList(); final SingletonParquetFooterCache footerCache = new SingletonParquetFooterCache(); for (DatasetSplit split : config.getSplits()) { sortedSplits.add(new HiveParquetSplit(split)); } Collections.sort(sortedSplits); final ScanFilter scanFilter = config.getFilter(); final List<ParquetFilterCondition> conditions; if (scanFilter == null) { conditions = null; } else { conditions = ((ParquetScanFilter) scanFilter).getConditions(); } readers = FluentIterable.from(sortedSplits).transform(new Function<HiveParquetSplit, RecordReader>(){ @Override public RecordReader apply(final HiveParquetSplit split) { return currentUGI.doAs(new PrivilegedAction<RecordReader>() { @Override public RecordReader run() { for (Prop prop : HiveReaderProtoUtil.getPartitionProperties(tableAttr, split.getPartitionId())) { jobConf.set(prop.getKey(), prop.getValue()); } // per partition fs is different final FileSystemWrapper fs = ImpersonationUtil.createFileSystem(ImpersonationUtil.getProcessUserName(), jobConf, split.getFileSplit().getPath()); final RecordReader innerReader; try (FSDataInputStream is = fs.open(split.fileSplit.getPath())) { innerReader = new FileSplitParquetRecordReader( context, readerFactory, config.getSchema(), compositeReader.getInnerColumns(), conditions, split.getFileSplit(), footerCache.getFooter(is, split.fileSplit.getPath().toString(), -1, fs), jobConf, vectorize, config.getSchema(), enableDetailedTracing ); } catch (IOException e) { throw UserException.dataReadError(e).addContext("split", split.fileSplit.toString()).build(logger); } return compositeReader.wrapIfNecessary(context.getAllocator(), innerReader, split.getDatasetSplit()); } }); }}); return new ScanOperator(fragmentExecContext.getSchemaUpdater(), config, context, readers.iterator()); } catch (final Exception e) { if(readers != null) { AutoCloseables.close(e, readers); } throw Throwables.propagate(e); } } private static class HiveParquetSplit implements Comparable { private final DatasetSplit datasetSplit; private final FileSplit fileSplit; private final int partitionId; HiveParquetSplit(DatasetSplit datasetSplit) { this.datasetSplit = datasetSplit; try { final HiveSplitXattr splitAttr = HiveSplitXattr.parseFrom(datasetSplit.getExtendedProperty().toByteArray()); final FileSplit fullFileSplit = (FileSplit) HiveUtilities.deserializeInputSplit(splitAttr.getInputSplit()); // make a copy of file split, we only need file path, start and length, throw away hosts this.fileSplit = new FileSplit(fullFileSplit.getPath(), fullFileSplit.getStart(), fullFileSplit.getLength(), (String[])null); this.partitionId = splitAttr.getPartitionId(); } catch (IOException | ReflectiveOperationException e) { throw new RuntimeException("Failed to parse dataset split for " + datasetSplit.getSplitKey(), e); } } public int getPartitionId() { return partitionId; } DatasetSplit getDatasetSplit() { return datasetSplit; } FileSplit getFileSplit() { return fileSplit; } @Override public int compareTo(Object o) { final HiveParquetSplit other = (HiveParquetSplit) o; final int ret = fileSplit.getPath().compareTo(other.fileSplit.getPath()); if (ret == 0) { return Long.compare(fileSplit.getStart(), other.getFileSplit().getStart()); } return ret; } } }
40.911917
159
0.715552
371da692e3942d840aa68d315c7fca65545f9611
577
package xyz.zelamkin.MFAN.pojo; public class Storage { private Integer id; private Integer product_id; private Integer product_count; public Integer getProduct_id() { return product_id; } public void setProduct_id(Integer product_id) { this.product_id = product_id; } public Integer getProduct_count() { return product_count; } public void setProduct_count(Integer product_count) { this.product_count = product_count; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
16.970588
54
0.691508
ed3ca2427b73ed8add42974b05b281bc13890739
807
package de.slackspace.smartnightstand.behavior; import java.awt.Color; import de.slackspace.smartnightstand.device.api.LedStrip; public abstract class AbstractLedBehavior { protected LedStrip ledStrip; protected short red; protected short green; protected short blue; public AbstractLedBehavior(LedStrip ledStrip, int frameRatePerSecond) { this(ledStrip, "#000000", frameRatePerSecond); } public AbstractLedBehavior(LedStrip ledStrip, String colorHexTriplet, int frameRatePerSecond) { this.ledStrip = ledStrip; Color color = Color.decode(colorHexTriplet); red = (short) color.getRed(); green = (short) color.getGreen(); blue = (short) color.getBlue(); ledStrip.setFrameDuration(1000 / frameRatePerSecond); } }
26.9
99
0.710037
55a779136efe804955e2c4dca4370266971c0d14
2,010
package com.toutiao.day; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * ็ป„ๅˆๆ‹ฌๅท * ไธญ็ญ‰ * ๅญ—่Š‚่ทณๅŠจ็ฎ—ๆณ•้ข˜ */ public class ๅ†ฒๅˆบ็ฎ—ๆณ•้ข่ฏ•ๆฏๆ—ฅไธ€้ข˜5_3ๅญ—่Š‚่ทณๅŠจๆ‹ฌๅท็”Ÿๆˆ { public static void main(String[] args) { System.out.println(generateParenthesisOne(3)); // System.out.println(generateParenthesisTwo(4)); } /** * DFSไธ€ * * @param n * @return */ public static List<String> generateParenthesisOne(int n) { //ๅฎšไน‰่ฟ”ๅ›žๆœ‰ๆ•ˆๆ‹ฌๅท็š„้›†ๅˆ List<String> list = new LinkedList(); //ๆž„้€ ๆ‹ฌๅทๆ•ฐ็ป„๏ผŒๅ› ไธบๆ‹ฌๅท้ƒฝๆ˜ฏๆˆๅฏน็š„ๅ‡บ็Žฐ char[] chars = new char[n * 2]; //ๅฎšไน‰charsๆ•ฐ็ป„ไธ‹ๆ ‡ int index = 0; //้€’ๅฝ’dfs dfs(list, chars, n, n, index); return list; } private static void dfs(List<String> list, char[] chars, int left, int right, int index) { if (left > right) return; if (left == 0 && right == 0) list.add(new String(chars)); if (left > 0) { chars[index] = '('; // ๆ€่€ƒ๏ผไธบไป€ไนˆไธ่ƒฝไฝฟ็”จไธ‹้ข็š„--left๏ผŒ++index dfs(list, chars, left - 1, right, index + 1); // dfs(list, chars, --left, right, ++index ); } if (right > 0) { chars[index] = ')'; dfs(list, chars, left, right - 1, index + 1); // dfs(list, chars, left, --right, ++index ); } ; } /** * DFS2 * @param n * @return */ public static List<String> generateParenthesisTwo(int n) { List<String> list = new ArrayList<>(); int left=n; int right=0; String str =""; dfs2(list, left, right, str); return list; } public static void dfs2(List<String> list, int left, int right, String str){ if(left==0 && right==0){ list.add(str); }else{ if(left>0){ dfs2(list,left-1,right+1,str+"("); } if(right>0){ dfs2(list,left,right-1,str+")"); } } } }
23.928571
94
0.497015
8fd99552b8390d8e4ab35aa3ad51d2d7b5a3d541
1,013
package cgeo.geocaching.settings; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.gcvote.GCVote; import org.apache.commons.lang3.tuple.ImmutablePair; import org.eclipse.jdt.annotation.NonNull; import rx.Observable; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; public class CheckGCVoteCredentialsPreference extends AbstractCheckCredentialsPreference { public CheckGCVoteCredentialsPreference(final Context context, final AttributeSet attrs) { super(context, attrs); } public CheckGCVoteCredentialsPreference(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); } @Override @NonNull protected Credentials getCredentials() { return Settings.getGCVoteLogin(); } @Override protected ImmutablePair<StatusCode, Observable<Drawable>> login() { return new ImmutablePair<>(GCVote.login(), null); } }
28.138889
114
0.762093
524ceeec1e3372ba8a53955eced833af76a282dc
10,637
package com.orange.poi.util; import com.orange.poi.PoiUnitTool; import com.sun.imageio.plugins.jpeg.JPEG; import com.sun.imageio.plugins.jpeg.JPEGImageReader; import com.sun.imageio.plugins.jpeg.JPEGMetadata; import com.sun.imageio.plugins.png.PNGMetadata; import org.w3c.dom.Node; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOInvalidTreeException; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.Iterator; /** * ๅ›พ็‰‡ๅค„็†ๅทฅๅ…ท * * @author ๅฐๅคฉ * @date 2019/6/3 23:29 */ public class ImageTool { /** * jpeg ๆ–‡ไปถ้ญ”ๆ•ฐ๏ผŒ็ฌฌ 0 ไฝ */ public static final byte JPEG_MAGIC_CODE_0 = (byte) 0xFF; public static final byte JPEG_MAGIC_CODE_1 = (byte) 0xD8; /** * ๆฐดๅนณๅ’Œๅž‚็›ดๆ–นๅ‘็š„ๅƒ็ด ๅฏ†ๅบฆๅ•ไฝ๏ผšๆ— ๅ•ไฝ */ public static final byte JPEG_UNIT_OF_DENSITIES_NONE = 0x00; /** * ๆฐดๅนณๅ’Œๅž‚็›ดๆ–นๅ‘็š„ๅƒ็ด ๅฏ†ๅบฆๅ•ไฝ๏ผš็‚นๆ•ฐ/่‹ฑๅฏธ */ public static final byte JPEG_UNIT_OF_DENSITIES_INCH = 0x01; /** * ๆฐดๅนณๅ’Œๅž‚็›ดๆ–นๅ‘็š„ๅƒ็ด ๅฏ†ๅบฆๅ•ไฝ๏ผš็‚นๆ•ฐ/ๅŽ˜็ฑณ */ public static final byte JPEG_NIT_OF_DENSITIES_CM = 0x02; public static final byte DPI_120 = 0x78; public static final byte DPI_96 = 0x60; public static final byte DPI_72 = 0x48; /** * png ๅ›พ็‰‡ pHYs ๅ—๏ผŒๅƒ็ด ๅฏ†ๅบฆๅ•ไฝ / ๆฏ็ฑณ */ public static final int PNG_pHYs_pixelsPerUnit = (int) PoiUnitTool.centimeterToPixel(100); /** * ่ฏปๅ–ๅ›พ็‰‡ๆ–‡ไปถ * * @param imgFile ๅ›พ็‰‡ๆ–‡ไปถ * * @return {@link BufferedImage} * * @throws IOException */ public static BufferedImage readImage(File imgFile) throws IOException { InputStream inputStream; if ((inputStream = FileUtil.readFile(imgFile)) == null) { return null; } return ImageIO.read(inputStream); } /** * ้‡็ฝฎๅ›พ็‰‡็š„ๅƒ็ด ๅฏ†ๅบฆไฟกๆฏ๏ผˆ้ป˜่ฎค้‡็ฝฎไธบ 96๏ผŒๅชๆ”ฏๆŒ jpg ๅ’Œ png ๅ›พ็‰‡๏ผ‰๏ผŒไปฅไฟฎๅค wps ๅœจ win10 ไธ‹ๆ‰“ๅฐๅ›พ็‰‡็ผบๅคฑ็š„ bug * * @param imageFile ๆบๆ–‡ไปถ * * @return ๆ–ฐ็š„ๆ–‡ไปถ๏ผŒnull๏ผšๅค„็†ๅคฑ่ดฅ * * @throws IOException */ public static File resetDensity(File imageFile) throws IOException { ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageFile); if (imageInputStream == null) { return null; } ImageReader reader = getImageReader(imageInputStream); if (reader == null) { return null; } reader.setInput(imageInputStream, true, false); String exName; IIOMetadata metadata = reader.getImageMetadata(0); if (metadata instanceof JPEGMetadata) { JPEGMetadata jpegMetadata = (JPEGMetadata) metadata; Integer resUnits = getResUnits(jpegMetadata); if (resUnits != null && resUnits != 0) { // ๅทฒๆŒ‡ๅฎšไบ†ๅƒ็ด ๅฏ†ๅบฆๆ—ถ๏ผŒไธๅ†็ปง็ปญๅค„็† return null; } resetDensity(jpegMetadata); exName = "jpg"; } else if (metadata instanceof PNGMetadata) { PNGMetadata pngMetadata = (PNGMetadata) metadata; if (pngMetadata.pHYs_unitSpecifier != 0) { // ๅทฒๆŒ‡ๅฎšไบ†ๅƒ็ด ๅฏ†ๅบฆๆ—ถ๏ผŒไธๅ†็ปง็ปญๅค„็† return null; } resetDensity(pngMetadata); exName = "png"; } else { throw new IllegalArgumentException("ไธๆ”ฏๆŒ็š„ๅ›พ็‰‡ๆ ผๅผ"); } BufferedImage bufferedImage; try { bufferedImage = reader.read(0, reader.getDefaultReadParam()); } finally { reader.dispose(); imageInputStream.close(); } ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { File dstImgFile = TempFileUtil.createTempFile(exName); imageOutputStream = ImageIO.createImageOutputStream(dstImgFile); imageWriter = ImageIO.getImageWriter(reader); imageWriter.setOutput(imageOutputStream); ImageWriteParam writeParam = imageWriter.getDefaultWriteParam(); if (writeParam instanceof JPEGImageWriteParam) { ((JPEGImageWriteParam) writeParam).setOptimizeHuffmanTables(true); } imageWriter.write(metadata, new IIOImage(bufferedImage, Collections.emptyList(), metadata), writeParam); return dstImgFile; } finally { if (imageWriter != null) { imageWriter.dispose(); } if (imageWriter != null) { imageOutputStream.flush(); } } } private static void resetDensity(JPEGMetadata metadata) throws IIOInvalidTreeException { final IIOMetadataNode newRootNode = new IIOMetadataNode(JPEG.nativeImageMetadataFormatName); // ๆ–นๆณ•ไธ€ final IIOMetadataNode mergeJFIFsubNode = new IIOMetadataNode("mergeJFIFsubNode"); IIOMetadataNode jfifNode = new IIOMetadataNode("jfif"); jfifNode.setAttribute("majorVersion", null); jfifNode.setAttribute("minorVersion", null); jfifNode.setAttribute("thumbWidth", null); jfifNode.setAttribute("thumbHeight", null); // ้‡็ฝฎๅƒ็ด ๅฏ†ๅบฆๅ•ไฝ jfifNode.setAttribute("resUnits", "1"); jfifNode.setAttribute("Xdensity", "96"); jfifNode.setAttribute("Ydensity", "96"); mergeJFIFsubNode.appendChild(jfifNode); newRootNode.appendChild(mergeJFIFsubNode); newRootNode.appendChild(new IIOMetadataNode("mergeSequenceSubNode")); metadata.mergeTree(JPEG.nativeImageMetadataFormatName, newRootNode); // ๆ–นๆณ•ไบŒ // final IIOMetadataNode dimensionNode = new IIOMetadataNode("Dimension"); // final IIOMetadataNode horizontalPixelSizeNode = new IIOMetadataNode("HorizontalPixelSize"); // horizontalPixelSizeNode.setAttribute("value", String.valueOf(25.4f / 96)); // final IIOMetadataNode verticalPixelSizeNode = new IIOMetadataNode("VerticalPixelSize"); // verticalPixelSizeNode.setAttribute("value", String.valueOf(25.4f / 96)); // dimensionNode.appendChild(horizontalPixelSizeNode); // dimensionNode.appendChild(verticalPixelSizeNode); // newRootNode.appendChild(dimensionNode); // metadata.mergeTree(IIOMetadataFormatImpl.standardMetadataFormatName, newRootNode); } private static void resetDensity(PNGMetadata metadata) throws IIOInvalidTreeException { metadata.pHYs_pixelsPerUnitXAxis = PNG_pHYs_pixelsPerUnit; metadata.pHYs_pixelsPerUnitYAxis = PNG_pHYs_pixelsPerUnit; metadata.pHYs_unitSpecifier = 1; metadata.pHYs_present = true; } /** * ่Žทๅ– jpg ๅ›พ็‰‡็š„ๅƒ็ด ๅฏ†ๅบฆ็ฑปๅž‹ * * @param metadata * * @return */ private static Integer getResUnits(JPEGMetadata metadata) { String value = getJfifAttr(metadata, "resUnits"); if (value == null) { return null; } return Integer.parseInt(value); } /** * ่Žทๅ– jpg ๅ›พ็‰‡็š„ๅƒ็ด ๅฏ†ๅบฆ็ฑปๅž‹ * * @param metadata * * @return */ private static String getJfifAttr(JPEGMetadata metadata, String attrName) { Node metadataNode = metadata.getAsTree(JPEG.nativeImageMetadataFormatName); if (metadataNode != null) { Node child = metadataNode.getFirstChild(); while (child != null) { if (child.getNodeName().equals("JPEGvariety")) { Node subChild = child.getFirstChild(); while (subChild != null) { if ("app0JFIF".equals(subChild.getNodeName())) { Node valueNode = subChild.getAttributes().getNamedItem(attrName); if (valueNode != null) { return valueNode.getNodeValue(); } break; } subChild = subChild.getNextSibling(); } break; } child = child.getNextSibling(); } } return null; } private static ImageReader getImageReader(ImageInputStream stream) { Iterator iter = ImageIO.getImageReaders(stream); if (!iter.hasNext()) { return null; } return (ImageReader) iter.next(); } /** * ่Žทๅ–ๅƒ็ด ๅฏ†ๅบฆ * * @param imageFile ๆบๆ–‡ไปถ * * @return ๅƒ็ด ๅฏ†ๅบฆ * * @throws IOException */ public static Integer getDensity(File imageFile) throws IOException { ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageFile); if (imageInputStream == null) { return null; } ImageReader reader = getImageReader(imageInputStream); if (reader == null) { return null; } if (!(reader instanceof JPEGImageReader)) { return null; } reader.setInput(imageInputStream, true, false); IIOMetadata metadata = reader.getImageMetadata(0); if (metadata instanceof JPEGMetadata) { JPEGMetadata jpegMetadata = (JPEGMetadata) metadata; Integer resUnits = getResUnits(jpegMetadata); if (resUnits == null) { return null; } if (resUnits == 1) { // ๆš‚ๆ—ถๅชๆ”ฏๆŒ resUnits == 1 ็ญ‰ๆƒ…ๅ†ต String value = getJfifAttr(jpegMetadata, "Xdensity"); if (value == null) { return null; } return Integer.parseInt(value); } return null; } else if (metadata instanceof PNGMetadata) { PNGMetadata pngMetadata = (PNGMetadata) metadata; if (pngMetadata.pHYs_unitSpecifier == 1) { // ๆš‚ๆ—ถๅชๆ”ฏๆŒ pHYs_unitSpecifier == 1 ็ญ‰ๆƒ…ๅ†ต return pngMetadata.pHYs_pixelsPerUnitXAxis; } return null; } else { throw new IllegalArgumentException("ไธๆ”ฏๆŒ็š„ๅ›พ็‰‡ๆ ผๅผ"); } } }
34.312903
117
0.590674
48747d578afcfc02b13238e85fcffdfc3407e65d
2,678
package novamachina.exnihilosequentia.api.crafting.crucible; import java.util.Arrays; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipeType; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.RegistryObject; import novamachina.exnihilosequentia.api.crafting.RecipeSerializer; import novamachina.exnihilosequentia.api.crafting.SerializableRecipe; import novamachina.exnihilosequentia.common.tileentity.crucible.CrucilbeTypeEnum; import novamachina.exnihilosequentia.common.utility.ExNihiloConstants; public class CrucibleRecipe extends SerializableRecipe { public static final IRecipeType<CrucibleRecipe> RECIPE_TYPE = IRecipeType .register(ExNihiloConstants.ModIds.EX_NIHILO_SEQUENTIA + ":crucible"); private static RegistryObject<RecipeSerializer<CrucibleRecipe>> serializer; private int amount; private CrucilbeTypeEnum crucibleType; private Ingredient input; private FluidStack resultFluid; public CrucibleRecipe(ResourceLocation id, Ingredient input, int amount, FluidStack fluid, CrucilbeTypeEnum crucibleType) { super(null, RECIPE_TYPE, id); this.input = input; this.amount = amount; this.resultFluid = fluid; this.crucibleType = crucibleType; } public static RegistryObject<RecipeSerializer<CrucibleRecipe>> getStaticSerializer() { return serializer; } public static void setSerializer(RegistryObject<RecipeSerializer<CrucibleRecipe>> serializer) { CrucibleRecipe.serializer = serializer; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public CrucilbeTypeEnum getCrucibleType() { return crucibleType; } public void setCrucibleType(String crucibleType) { this.crucibleType = CrucilbeTypeEnum.getTypeByName(crucibleType); } public Ingredient getInput() { return input; } public void setInput(Ingredient input) { this.input = input; } public List<ItemStack> getInputs() { return Arrays.asList(input.getItems()); } @Override public ItemStack getResultItem() { return ItemStack.EMPTY; } public FluidStack getResultFluid() { return resultFluid; } public void setResultFluid(FluidStack resultFluid) { this.resultFluid = resultFluid; } @Override protected RecipeSerializer<CrucibleRecipe> getENSerializer() { return serializer.get(); } }
30.781609
127
0.732263
4de7553b36c996600d3de2e06e946ba9b6f4fd57
6,226
package japicmp.test; import japicmp.cmp.JarArchiveComparator; import japicmp.cmp.JarArchiveComparatorOptions; import japicmp.model.JApiChangeStatus; import japicmp.model.JApiClass; import japicmp.model.JApiField; import japicmp.model.JApiMethod; import org.junit.BeforeClass; import org.junit.Test; import java.io.Serializable; import java.util.List; import static japicmp.test.util.Helper.getArchive; import static japicmp.test.util.Helper.getJApiClass; import static japicmp.test.util.Helper.getJApiField; import static japicmp.test.util.Helper.getJApiImplementedInterface; import static japicmp.test.util.Helper.getJApiMethod; import static japicmp.test.util.Helper.replaceLastDotWith$; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class InterfacesTest { private static List<JApiClass> jApiClasses; @BeforeClass public static void beforeClass() { JarArchiveComparator jarArchiveComparator = new JarArchiveComparator(new JarArchiveComparatorOptions()); jApiClasses = jarArchiveComparator.compare(getArchive("japicmp-test-v1.jar"), getArchive("japicmp-test-v2.jar")); } @Test public void testInterfaceToNoInterface() { JApiClass interfaceToNoInterfaceClass = getJApiClass(jApiClasses, Interfaces.InterfaceToNoInterfaceClass.class.getName()); assertThat(interfaceToNoInterfaceClass.getChangeStatus(), is(JApiChangeStatus.MODIFIED)); assertThat(interfaceToNoInterfaceClass.getInterfaces().size(), is(1)); assertThat(getJApiImplementedInterface(interfaceToNoInterfaceClass.getInterfaces(), replaceLastDotWith$(Interfaces.TestInterface.class.getCanonicalName())).getChangeStatus(), is(JApiChangeStatus.REMOVED)); } @Test public void testInterfaceChangesClass() { JApiClass interfaceChangesClass = getJApiClass(jApiClasses, Interfaces.InterfaceChangesClass.class.getName()); assertThat(interfaceChangesClass.getChangeStatus(), is(JApiChangeStatus.MODIFIED)); assertThat(interfaceChangesClass.getInterfaces().size(), is(2)); assertThat(getJApiImplementedInterface(interfaceChangesClass.getInterfaces(), replaceLastDotWith$(Interfaces.TestInterface.class.getCanonicalName())).getChangeStatus(), is(JApiChangeStatus.REMOVED)); assertThat(getJApiImplementedInterface(interfaceChangesClass.getInterfaces(), replaceLastDotWith$(Interfaces.SecondTestInterface.class.getCanonicalName())).getChangeStatus(), is(JApiChangeStatus.NEW)); } @Test public void testInterfaceRemainsInterface() { JApiClass interfaceRemainsInterfaceClass = getJApiClass(jApiClasses, Interfaces.InterfaceRemainsInterfaceClass.class.getName()); assertThat(interfaceRemainsInterfaceClass.getChangeStatus(), is(JApiChangeStatus.UNCHANGED)); assertThat(interfaceRemainsInterfaceClass.getInterfaces().size(), is(1)); assertThat(getJApiImplementedInterface(interfaceRemainsInterfaceClass.getInterfaces(), replaceLastDotWith$(Interfaces.TestInterface.class.getCanonicalName())).getChangeStatus(), is(JApiChangeStatus.UNCHANGED)); } @Test public void testNoInterfaceToWithInterface() { JApiClass noInterfaceToWithInterfaceClass = getJApiClass(jApiClasses, Interfaces.NoInterfaceToInterfaceClass.class.getName()); assertThat(noInterfaceToWithInterfaceClass.getChangeStatus(), is(JApiChangeStatus.MODIFIED)); assertThat(noInterfaceToWithInterfaceClass.getInterfaces().size(), is(1)); assertThat(getJApiImplementedInterface(noInterfaceToWithInterfaceClass.getInterfaces(), replaceLastDotWith$(Interfaces.TestInterface.class.getCanonicalName())).getChangeStatus(), is(JApiChangeStatus.NEW)); } @Test public void testNoInterfaceToSerializableInterface() { JApiClass jApiClass = getJApiClass(jApiClasses, Interfaces.NoInterfaceToSerializableInterface.class.getName()); assertThat(jApiClass.getChangeStatus(), is(JApiChangeStatus.MODIFIED)); assertThat(jApiClass.getInterfaces().size(), is(1)); assertThat(getJApiImplementedInterface(jApiClass.getInterfaces(), Serializable.class.getCanonicalName()).getChangeStatus(), is(JApiChangeStatus.NEW)); } @Test public void testNewClassWithNewInterface() { JApiClass newClassWithNewInterface = getJApiClass(jApiClasses, "japicmp.test.Interfaces$NewClassWithNewInterface"); assertThat(getJApiImplementedInterface(newClassWithNewInterface.getInterfaces(), Interfaces.TestInterface.class.getName()).getChangeStatus(), is(JApiChangeStatus.NEW)); assertThat(getJApiImplementedInterface(newClassWithNewInterface.getInterfaces(), Interfaces.TestInterface.class.getName()).isBinaryCompatible(), is(true)); } @Test public void testMethodPulledUpToSuperInterface() { JApiClass jApiClass = getJApiClass(jApiClasses, Interfaces.MethodPulledToSuperInterfaceBase.class.getName()); assertThat(jApiClass.isBinaryCompatible(), is(true)); JApiMethod methodPulledUp = getJApiMethod(jApiClass.getMethods(), "methodPulledUp"); assertThat(methodPulledUp.isBinaryCompatible(), is(true)); jApiClass = getJApiClass(jApiClasses, Interfaces.MethodPulledToSuperInterfaceChild.class.getName()); assertThat(jApiClass.isBinaryCompatible(), is(true)); methodPulledUp = getJApiMethod(jApiClass.getMethods(), "methodPulledUp"); assertThat(methodPulledUp.isBinaryCompatible(), is(true)); } @Test public void testFieldsOfInterface() { JApiClass interfaceWithFields = getJApiClass(jApiClasses, "japicmp.test.Interfaces$InterfaceWithFields"); List<JApiField> fields = interfaceWithFields.getFields(); assertThat(fields.size(), is(3)); JApiField jApiField = getJApiField(fields, "ADDED"); assertThat(jApiField.getChangeStatus(), is(JApiChangeStatus.NEW)); jApiField = getJApiField(fields, "REMOVED"); assertThat(jApiField.getChangeStatus(), is(JApiChangeStatus.REMOVED)); jApiField = getJApiField(fields, "UNCHANGED"); assertThat(jApiField.getChangeStatus(), is(JApiChangeStatus.UNCHANGED)); assertThat(interfaceWithFields.isBinaryCompatible(), is(false)); } @Test public void testInterfaceMethodAdded() { JApiClass jApiClass = getJApiClass(jApiClasses, "japicmp.test.Interfaces$InterfaceAddMethod"); assertThat(jApiClass.getChangeStatus(), is(JApiChangeStatus.MODIFIED)); assertThat(jApiClass.isBinaryCompatible(), is(true)); assertThat(jApiClass.isSourceCompatible(), is(false)); } }
54.13913
212
0.821234
e5478ab3f10b5f0920198b96e08f6dff2f144987
3,000
package com.dhc.android.testdemoforwzw; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.Scroller; public class DragView extends View { private int mLastX; private int mLastY; private Scroller mScroller; public DragView(Context context) { this(context, null, 0); } public DragView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public DragView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mScroller = new Scroller(context); } @Override public void computeScroll() { super.computeScroll(); if (mScroller.computeScrollOffset()){ //ๅˆคๆ–ญๆ˜ฏๅฆๅฎŒๆˆไบ†ๆ•ดไธชๆป‘ๅŠจใ€‚true๏ผšๅŠจ็”ปๅฐšๆœชๅฎŒๆˆ ((View)getParent()).scrollTo(mScroller.getCurrX(),mScroller.getCurrY()); invalidate(); //ๅฎžๆ—ถ่Žทๅ–View็š„ไฝ็ฝฎๅ˜ๅŒ–๏ผŒๅฎžๆ—ถๆ›ดๆ–ฐๆป‘ๅŠจ } } @Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); //ๅฎžๆ—ถๆต‹้‡็‚นๅ‡ปไฝ็ฝฎๅˆฐ่‡ชๅทฑๅทฆ่พน็š„่ท็ฆป int y = (int) event.getY(); //ๅฎžๆ—ถๆต‹้‡็‚นๅ‡ปไฝ็ฝฎๅˆฐ่‡ชๅทฑ้กถ่พน็š„่ท็ฆป switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mLastX = x; //ๅญ˜ไธ‹ๅผ€ๅง‹ๆ—ถๅ€™็š„ไฝ็ฝฎ mLastY = y; //ๅญ˜ไธ‹ๅผ€ๅง‹ๆ—ถๅ€™็š„ไฝ็ฝฎ break; case MotionEvent.ACTION_MOVE: int offsetX = x - mLastX; //x่ฝดๅ็งป้‡ int offsetY = y - mLastY; //y่ฝดๅ็งป้‡ // layout(getLeft()+offsetX,getTop()+offsetY,getRight()+offsetX,getBottom()+offsetY); //ๆ–นๆณ•1๏ผš้‡ๅ†™layout()ๆ–นๆณ• // offsetLeftAndRight(offsetX); //ๆ–นๆณ•2๏ผš็›ดๆŽฅ็งปๅŠจๅทฆๅณๅ’ŒไธŠไธ‹็š„ๅ็งป้‡ // offsetTopAndBottom(offsetY); // LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) getLayoutParams(); //ๆ–นๆณ•3๏ผš้€š่ฟ‡ๆ”นๅ˜ๅทฆๅค–่พน่ทๅ’ŒไธŠๅค–่พน่ท็š„ๅ‚ๆ•ฐ๏ผŒๆ”นๅ˜ไฝ็ฝฎ // params.leftMargin = getLeft() + offsetX; // params.topMargin = getTop() + offsetY; // setLayoutParams(params); // ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) getLayoutParams(); //ๆ–นๆณ•4๏ผš้€š่ฟ‡ๆ”นๅ˜ๅทฆๅค–่พน่ทๅ’ŒไธŠๅค–่พน่ท็š„ๅ‚ๆ•ฐ๏ผŒๆ”นๅ˜ไฝ็ฝฎ // params.leftMargin = getLeft()+offsetX; // params.topMargin = getTop()+offsetY; // setLayoutParams(params); ((View)getParent()).scrollBy(-offsetX,-offsetY); //ๆ–นๆณ•5๏ผš้€š่ฟ‡scrollByๆ–นๆณ•ๆ”นๅ˜ไฝ็ฝฎ break; case MotionEvent.ACTION_UP: View viewGroup = (View) getParent(); mScroller.startScroll( viewGroup.getScrollX(), //ๅˆๅง‹ไฝ็ฝฎX viewGroup.getScrollY(), //ๅˆๅง‹ไฝ็ฝฎY -viewGroup.getScrollX(), //ๅๅ‘ไฝ็งปX -viewGroup.getScrollY() //ๅๅ‘ไฝ็งปY ); invalidate(); break; } return true; } }
38.961039
136
0.573
7d0df2c28e049365fffa6a3612a20443531f0caf
310
package com.lgy.demo.statemachine.state; import com.lgy.demo.statemachine.OrderContext; /** * ่ฎขๅ•ๅฎŒๆˆ็Šถๆ€ */ public class OrderCompleteState extends AbstractOrderState{ OrderContext orderContext; public OrderCompleteState(OrderContext orderContext) { this.orderContext = orderContext; } }
19.375
59
0.754839
521bb115675b25250c749ee5e0c6190c20fa6b67
6,703
package study.yang.definedivideritemview; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; public class DefineDividerItem extends RecyclerView.ItemDecoration { //ๆฐดๅนณ public static final int HORIZONTAL = 0; //ๅž‚็›ด public static final int VERTICAL = 1; private static final String TAG = "DefineDividerItem"; //ๅˆ†ๅ‰ฒ็บฟDrawable private Drawable mDivider; //ๅˆ†ๅ‰ฒ็บฟไฝ็ฝฎ private int mOrientation = 1; private final Rect mBounds = new Rect(); /** * ่ฎพ็ฝฎๅˆ†ๅ‰ฒ็บฟ็š„ๆ–นๅ‘ * * @param orientation */ public void setOrientation(int orientation) { if (orientation != 0 && orientation != 1) { throw new IllegalArgumentException("Invalid orientation. It should be either HORIZONTAL or VERTICAL"); } else { this.mOrientation = orientation; } } /** * ่ฎพ็ฝฎๅˆ†ๅ‰ฒ็บฟ็š„ๆ ทๅผ * * @param drawable */ public void setDrawable(@NonNull Drawable drawable) { if (drawable == null) { throw new IllegalArgumentException("Drawable cannot be null."); } else { this.mDivider = drawable; } } @Override public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { if (parent.getLayoutManager() != null && this.mDivider != null) { if (this.mOrientation == 1) { drawVertical(c, parent); } else { drawHorizontal(c, parent); } } Log.e(TAG, "onDraw"); } /** * ็ป˜ๅˆถๅž‚็›ด็บฟ * * @param * @param parent */ private void drawVertical(Canvas canvas, RecyclerView parent) { canvas.save(); int left; int right; if (parent.getClipToPadding()) { left = parent.getPaddingLeft(); right = parent.getWidth() - parent.getPaddingRight(); canvas.clipRect(left, parent.getPaddingTop(), right, parent.getHeight() - parent.getPaddingBottom()); } else { left = 0; right = parent.getWidth(); } int childCount = parent.getChildCount(); for (int i = 0; i < childCount; ++i) { View child = parent.getChildAt(i); parent.getDecoratedBoundsWithMargins(child, this.mBounds); Log.e("====", "childLayoutๅธƒๅฑ€๏ผš๏ผš" + parent.getChildLayoutPosition(child) + "childAdapterๅธƒๅฑ€๏ผš๏ผš" + parent.getChildAdapterPosition(child)); //ๅญView็š„ๆต‹้‡้ซ˜ๅบฆ int childMeasuredHeight = child.getMeasuredHeight(); int bottom = this.mBounds.bottom + - childMeasuredHeight; int top = bottom - this.mDivider.getIntrinsicHeight() - childMeasuredHeight;//-child.getMeasuredHeight() //ๅฐ†mBounds็š„ไฝ็ฝฎไฟกๆฏๅ†ไผ ้€’็ป™mDivider็š„Bounds this.mDivider.setBounds(left, top, right, bottom); //็ป˜ๅˆถmDivider this.mDivider.draw(canvas); } canvas.restore(); } /** * ็ป˜ๅˆถๆฐดๅนณ็บฟ * * @param canvas * @param parent */ private void drawHorizontal(Canvas canvas, RecyclerView parent) { canvas.save(); int top; int bottom; if (parent.getClipToPadding()) { top = parent.getPaddingTop(); bottom = parent.getHeight() - parent.getPaddingBottom(); canvas.clipRect(parent.getLeft(), top, parent.getRight() - parent.getPaddingRight(), bottom); } else { top = 0; bottom = parent.getHeight(); } int childCount = parent.getChildCount(); for (int i = 0; i < childCount; ++i) { View child = parent.getChildAt(i); parent.getDecoratedBoundsWithMargins(child, this.mBounds); Log.e("====", "childLayoutๅธƒๅฑ€๏ผš๏ผš" + parent.getChildLayoutPosition(child) + "childAdapterๅธƒๅฑ€๏ผš๏ผš" + parent.getChildAdapterPosition(child)); //ๅญView็š„ๆต‹้‡ๅฎฝๅบฆ int measuredWidth = child.getMeasuredWidth(); int right = this.mBounds.right - measuredWidth; int left = right - this.mDivider.getIntrinsicWidth() - measuredWidth;//-child.getMeasuredHeight() //ๅฐ†mBounds็š„ไฝ็ฝฎไฟกๆฏๅ†ไผ ้€’็ป™mDivider็š„Bounds this.mDivider.setBounds(left, top, right, bottom); //็ป˜ๅˆถmDivider this.mDivider.draw(canvas); } canvas.restore(); } @Override public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { super.onDrawOver(c, parent, state); Log.e(TAG, "onDrawOver"); } @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); int position = layoutManager.getPosition(view); int childCount = layoutManager.getChildCount(); RecyclerView.Adapter parentAdapter = parent.getAdapter(); Log.e("====", childCount + "::getItemOffsets::" + position + "::getItemOffsets::" + parentAdapter.getItemCount()); int totalChildCount = parentAdapter.getItemCount() - 1; //่Žทๅ–mDivider็š„ๅ†…ๅœจ้ซ˜ๅบฆ if (mOrientation == VERTICAL) { int intrinsicHeight = mDivider.getIntrinsicHeight(); Log.e("====", "ๅ†…ๅœจ้ซ˜ๅบฆ" + intrinsicHeight); getItemVerticalOffsets(outRect, intrinsicHeight, position, totalChildCount); } else { int intrinsicWidth = mDivider.getIntrinsicWidth(); getItemHorizontalOffsets(outRect, intrinsicWidth, position, totalChildCount); } } /** * ่Žทๅ–ๆฐดๅนณ็š„ๆก็›ฎๅ็งป * * @param outRect * @param offsets * @param position * @param totalChildCount */ private void getItemHorizontalOffsets(Rect outRect, int offsets, int position, int totalChildCount) { if (position == totalChildCount) { //ไฟ่ฏๆœ€ๅŽไธ€ไธชๆก็›ฎ่ท็ฆปๅฑๅน•ๅบ•้ƒจไนŸๆœ‰้—ด้š” outRect.set(offsets, 0, offsets, 0); } else { outRect.set(offsets, 0, 0, 0); } } /** * ่Žทๅ–ๅž‚็›ด็š„ๆก็›ฎๅ็งป * * @param outRect * @param offsets ๅ็งปๅบฆ */ private void getItemVerticalOffsets(Rect outRect, int offsets, int position, int totalChildCount) { if (position == totalChildCount) { //ไฟ่ฏๆœ€ๅŽไธ€ไธชๆก็›ฎ่ท็ฆปๅฑๅน•ๅบ•้ƒจไนŸๆœ‰้—ด้š” outRect.set(0, offsets, 0, offsets); } else { outRect.set(0, offsets, 0, 0); } } }
33.515
145
0.602864
dc1a52ee4313b5c98fbfce3678d267242f9651c4
280
package pl.coderslab.spring01hibernate.repository.examples; import org.springframework.data.jpa.repository.JpaRepository; import pl.coderslab.spring01hibernate.entity.examples.Nauczyciel; public interface NauczycielRepository extends JpaRepository<Nauczyciel, Long> { }
31.111111
65
0.835714
395248541181fb6ec69e04c47af236cab4f06a1c
4,606
package com.bbva.kyof.vega.autodiscovery.publisher; import com.bbva.kyof.vega.autodiscovery.model.AutoDiscDaemonClientInfo; import com.bbva.kyof.vega.config.general.AutoDiscoveryConfig; import com.bbva.kyof.vega.msg.MsgType; import io.aeron.Aeron; import io.aeron.Publication; import lombok.extern.slf4j.Slf4j; import java.io.Closeable; /** * Implementation of auto-discovery sender handler for unicast auto-discovery type */ @Slf4j public class AutodiscUnicastSender extends AbstractAutodiscSender implements Closeable { /** Client info min send interval */ private static final long CLIENT_INFO_MIN_SEND_INTERVAL = 10; /** Client info max send interval */ private static final long CLIENT_INFO_MAX_SEND_INTERVAL = 500; /** Client info send interval increment factor */ private static final int CLIENT_INFO_SEND_INC_FACTOR = 2; /** * Information of the daemon client represented by the auto-discovery instance of the library and * that has to be periodically sent with the reception socket info of the client. * The daemon will use this information to send the adverts to the client. */ private volatile VariableSendRegisteredInfo<AutoDiscDaemonClientInfo> registeredDaemonClientInfo = null; /** Publication aeron socket used to send the messages */ private PublicationInfo publicationInfo; /** Manager for all the publishers of unicast daemon servers*/ private final IPublicationsManager publicationsManager; /** * Creates a new auto-discovery unicast sender * @param aeron the aeron instance * @param config the configuration for autodiscovery * @param daemonClientInfo the information of the daemon client with the reception socket information * @param pPublicationsManager PublicationsManager instance */ public AutodiscUnicastSender( final Aeron aeron, final AutoDiscoveryConfig config, final AutoDiscDaemonClientInfo daemonClientInfo, final IPublicationsManager pPublicationsManager) { super(aeron, config); this.registeredDaemonClientInfo = new VariableSendRegisteredInfo<>(daemonClientInfo, CLIENT_INFO_MIN_SEND_INTERVAL, CLIENT_INFO_MAX_SEND_INTERVAL, CLIENT_INFO_SEND_INC_FACTOR); this.publicationsManager = pPublicationsManager; // Create the unicast publication this.publicationInfo = this.getPublicationInfo(); } /** * Creates the Aeron publication object to send auto-discovery messages. * * @return the created Aeron publication */ private PublicationInfo getPublicationInfo() { return this.publicationsManager.getRandomPublicationInfo(); } @Override public Publication getPublication(){ //If the actual selected publicationInfo is null or it becomes disable, // and does exists another publication enabled, change it // It it does not exists another enabled, maintains the old disabled one // (to maintain the old environment) if( (this.publicationInfo == null || !this.publicationInfo.getEnabled()) && this.publicationsManager.hasEnabledPublications() ) { this.publicationInfo = publicationsManager.getRandomPublicationInfo(); } //If the publicationInfo is not null, return the publication if(this.publicationInfo != null) { return this.publicationInfo.getPublication(); } //In this case, it does not exists a valid publication, so return null return null; } @Override public int sendNextTopicAdverts() { // Get the daemon client info it if should be sent final AutoDiscDaemonClientInfo daemonClientInfo = this.registeredDaemonClientInfo.getIfShouldSendAndResetIfRequired(System.currentTimeMillis()); // Send the daemon client info to ALL the publications (to know if any disabled daemon is now enabled) // and to the rest of topic adverts return super.sendMessageIfNotNullToAllPublications (MsgType.AUTO_DISC_DAEMON_CLIENT_INFO, daemonClientInfo, this.publicationsManager.getPublicationsInfoArray()) + super.sendNextTopicAdverts(); } @Override public void close() { log.info("Closing auto discovery sender: publications"); for(int i = 0; i < this.publicationsManager.getPublicationsInfoArray().length; i++) { this.publicationsManager.getPublicationsInfoArray()[i].getPublication().close(); } super.close(); } }
39.706897
184
0.713634
a2022f99ffbf135cff6c722c28723a51e51ab9d2
992
package com.atguigu.gmall.pms.service.impl; import org.springframework.stereotype.Service; import java.util.Map; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.atguigu.gmall.common.bean.PageResultVo; import com.atguigu.gmall.common.bean.PageParamVo; import com.atguigu.gmall.pms.mapper.PmsCommentMapper; import com.atguigu.gmall.pms.entity.PmsCommentEntity; import com.atguigu.gmall.pms.service.PmsCommentService; @Service("pmsCommentService") public class PmsCommentServiceImpl extends ServiceImpl<PmsCommentMapper, PmsCommentEntity> implements PmsCommentService { @Override public PageResultVo queryPage(PageParamVo paramVo) { IPage<PmsCommentEntity> page = this.page( paramVo.getPage(), new QueryWrapper<PmsCommentEntity>() ); return new PageResultVo(page); } }
34.206897
121
0.777218
a775602fd1b381030c22e11f966e4c3a1d636ddf
2,302
package com.codi.superman.base.dao.impl; import com.codi.base.dao.BaseDAOImpl; import com.codi.superman.base.common.Const; import com.codi.superman.base.dao.SysRolePrivDao; import com.codi.superman.base.domain.SysRolePriv; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * sys role priv dao impl * * @author shi.pengyan * @date 2016-12-25 15:44 */ @Repository("sysRolePrivDao") public class SysRolePrivDaoImpl extends BaseDAOImpl<SysRolePriv> implements SysRolePrivDao { @Override public int insert(Long roleId, Long privId) { SysRolePriv sysRolePriv = new SysRolePriv(); sysRolePriv.setRoleId(roleId); sysRolePriv.setPrivId(privId); sysRolePriv.setState(Const.STATE_A); Date now = new Date(); sysRolePriv.setCreateDate(now); sysRolePriv.setUpdateDate(now); return this.insert(generateStatement("insert"), sysRolePriv); } @Override public int updateState(Long roleId, Long privId, String state) { SysRolePriv sysRolePriv = new SysRolePriv(); sysRolePriv.setRoleId(roleId); sysRolePriv.setPrivId(privId); sysRolePriv.setState(state); Date now = new Date(); sysRolePriv.setUpdateDate(now); return this.update(generateStatement("updateState"), sysRolePriv); } @Override public int delRolePriv(Long roleId, Long privId) { SysRolePriv sysRolePriv = new SysRolePriv(); sysRolePriv.setRoleId(roleId); sysRolePriv.setPrivId(privId); return this.delete(generateStatement("delRolePriv"), sysRolePriv); } @Override public Boolean checkRoleExist(Long roleId) { return this.getSqlSession().selectOne(generateStatement("checkRoleExist"), roleId); } @Override public Boolean checkPrivExist(Long privId) { return this.getSqlSession().selectOne(generateStatement("checkPrivExist"), privId); } @Override public Boolean checkRolePrivExist(Long roleId, Long privId) { Map<String, Long> map = new HashMap<>(); map.put("roleId", roleId); map.put("privId", privId); return this.getSqlSession().selectOne(generateStatement("checkRolePrivExist"), map); } }
29.896104
92
0.693745
36fc32aeb666c4301ddada6abaa4a579e70adf05
6,651
package edu.dartmouth.cs.battleroyalego; import android.Manifest; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.os.Build; import android.os.Looper; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseUser; public class MainActivity extends AppCompatActivity { LocationRequest mLocationRequest; FusedLocationProviderClient mFusedLocationClient; Location user_game_location; FirebaseUser currentUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final String userUID = getIntent().getStringExtra("firebaseUser"); System.out.println("userUID is: " +userUID); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(120000); // two minute interval mLocationRequest.setFastestInterval(120000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //Location Permission already granted //mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); mFusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { user_game_location = location; } } }); } else { //Request Location Permission checkLocationPermission(); } } else { mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); } Button startGame = findViewById(R.id.start_game); Button joinGame = findViewById(R.id.join_game); startGame.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MakeActivity.class); intent.putExtra("USER_LOCATION", user_game_location); intent.putExtra("GAME_LOCATION", user_game_location); intent.putExtra("USER_UID", userUID); startActivity(intent); } }); joinGame.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, JoinActivity.class); intent.putExtra("USER_LOCATION", user_game_location); intent.putExtra("USER_UID", userUID); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.settings){ Intent intent = new Intent(MainActivity.this, SettingsActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } LocationCallback mLocationCallback = new LocationCallback() { // @Override // public void onLocationResult(LocationResult locationResult) { // for (Location location : locationResult.getLocations()) { // user_game_location = location; // } // } }; public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; private void checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new AlertDialog.Builder(this) .setTitle("Location Permission Needed") .setMessage("This app needs the Location permission, please accept to use location functionality") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION ); } }) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION ); } } } }
41.055556
122
0.630432
22ec3531616e7033224f2e8d30fc653cb54e1932
2,947
package seedu.address.logic.commands; import static junit.framework.TestCase.fail; import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure; import java.io.File; import java.util.ArrayList; import java.util.List; import org.junit.Test; import seedu.address.commons.core.Messages; import seedu.address.commons.util.ImageMagickUtil; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.transformation.Transformation; import seedu.address.storage.JsonConvertArgsStorageTest; import seedu.address.testutil.ModelGenerator; public class CreateApplyCommandTest { @Test public void createOperationsSuccessfully() throws CommandException { if (ImageMagickUtil.getCommandSaveFolder() == null) { ImageMagickUtil.setTemperatyCommandForder(JsonConvertArgsStorageTest.TEST_DATA_FOLDER.toString()); } Transformation transformation = new Transformation("blur", "0x8"); List<Transformation> list = new ArrayList<>(); list.add(transformation); CreateApplyCommand command = new CreateApplyCommand("newOperation", list); command.execute(ModelGenerator.getDefaultModel(), null); //test the case with multiple transformations list.add(transformation); command = new CreateApplyCommand("newOperation", list); command.execute(ModelGenerator.getDefaultModel(), null); if (!new File(JsonConvertArgsStorageTest.TEST_DATA_FOLDER.toString()).exists()) { fail(); } } @Test public void createOperationsUnsuccessfully() throws CommandException { if (ImageMagickUtil.getCommandSaveFolder() == null) { ImageMagickUtil.setTemperatyCommandForder(JsonConvertArgsStorageTest.TEST_DATA_FOLDER.toString()); } Transformation transformation = new Transformation("blur", "0x8"); Transformation transformation2 = new Transformation("contrast", "0x8"); List<Transformation> list = new ArrayList<>(); list.add(transformation); list.add(transformation2); CreateApplyCommand command = new CreateApplyCommand("newOperation", list); assertCommandFailure(command, null, new CommandHistory(), Messages.MESSAGE_INVALID_OPERATION_ARGUMENTS); //test with different failure cases list.remove(transformation2); Transformation transformation3 = new Transformation("resize", "fake"); list.add(transformation3); command = new CreateApplyCommand("newOperation", list); assertCommandFailure(command, null, new CommandHistory(), Messages.MESSAGE_INVALID_OPERATION_ARGUMENTS); try { new CreateApplyCommand("newOperation", new ArrayList<>()); } catch (IllegalArgumentException e) { if (!e.getMessage().contains("Empty")) { fail(); } } } }
42.710145
112
0.715304
9827b81b265c327cb8d904b782145f7f43ab7ea6
1,410
// Generated by dagger.internal.codegen.ComponentProcessor (https://google.github.io/dagger). package com.battlelancer.seriesguide.modules; import com.uwetrottmann.trakt5.TraktV2; import com.uwetrottmann.trakt5.services.Recommendations; import dagger.internal.Factory; import dagger.internal.Preconditions; import javax.inject.Provider; public final class TraktModule_ProvideRecommendationsFactory implements Factory<Recommendations> { private final TraktModule module; private final Provider<TraktV2> traktProvider; public TraktModule_ProvideRecommendationsFactory( TraktModule module, Provider<TraktV2> traktProvider) { assert module != null; this.module = module; assert traktProvider != null; this.traktProvider = traktProvider; } @Override public Recommendations get() { return Preconditions.checkNotNull( module.provideRecommendations(traktProvider.get()), "Cannot return null from a non-@Nullable @Provides method"); } public static Factory<Recommendations> create( TraktModule module, Provider<TraktV2> traktProvider) { return new TraktModule_ProvideRecommendationsFactory(module, traktProvider); } /** Proxies {@link TraktModule#provideRecommendations(TraktV2)}. */ public static Recommendations proxyProvideRecommendations(TraktModule instance, TraktV2 trakt) { return instance.provideRecommendations(trakt); } }
35.25
98
0.78227
dfe018b781ea9ea26bb717a6e5918a7b19cd08a2
2,317
package li.cil.circuity.common.init; import li.cil.circuity.ModCircuity; import li.cil.circuity.common.Constants; import li.cil.circuity.common.Globals; import li.cil.circuity.common.item.ItemConfigurator; import li.cil.circuity.common.item.ItemEEPROM; import li.cil.circuity.common.item.ItemFloppyDisk; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraftforge.fml.common.registry.GameRegistry; public final class Items { public static Item busCable; public static Item busController; public static Item configurator; public static Item eeprom; public static Item eepromReader; public static Item floppyDisk; public static Item floppyDiskDrive; public static Item processorMips3; public static Item processorZ80; public static Item randomAccessMemory; public static Item redstoneController; public static Item screen; public static Item serialConsole; public static void init() { busCable = register(Blocks.busCable); busController = register(Blocks.busController); configurator = register(new ItemConfigurator(), Constants.CONFIGURATOR_NAME); eeprom = register(new ItemEEPROM(), Constants.EEPROM_NAME); eepromReader = register(Blocks.eepromReader); floppyDisk = register(new ItemFloppyDisk(), Constants.FLOPPY_DISK_NAME); floppyDiskDrive = register(Blocks.floppyDiskDrive); processorMips3 = register(Blocks.processorMips3); processorZ80 = register(Blocks.processorZ80); randomAccessMemory = register(Blocks.randomAccessMemory); redstoneController = register(Blocks.redstoneController); screen = register(Blocks.screen); serialConsole = register(Blocks.serialConsole); } private static Item register(final Block block) { return register(new ItemBlock(block), block.getRegistryName().getResourcePath()); } private static Item register(final Item item, final String name) { item.setCreativeTab(Globals.CREATIVE_TAB). setUnlocalizedName(name). setRegistryName(name); GameRegistry.register(item); ModCircuity.getProxy().handleRegisterItem(item); return item; } private Items() { } }
37.983607
89
0.729391
ac57b9d135ece9c4639fd472c48632a3b4424ab9
956
package ch.ethz.semdwhsearch.prototyp1.pages.elements.impl; import ch.ethz.semdwhsearch.prototyp1.actions.Params; import ch.ethz.semdwhsearch.prototyp1.localization.Dictionary; import ch.ethz.semdwhsearch.prototyp1.pages.elements.Element; /** * Query element. * * @author Ana Sima * */ public class SPARQLQueryElement implements Element { private final String query; public SPARQLQueryElement(String query) { this.query = query; } public void appendHtml(StringBuffer html, Dictionary dict) { html.append("<!-- query -->\n"); html.append("<div class='content'>\n"); // input String value = query == null ? "" : query; html.append("<textarea id='query' rows='120' cols='120' name='" + Params.Q + "' value='" + value + "' ></textarea>\n"); // submit html.append("<input type='submit' value='" + dict.go() + "' />\n"); html.append("</div>\n\n"); } public void appendHtmlClose(StringBuffer html, Dictionary dict) { } }
24.512821
121
0.682008
829dc6002e7823be3b494954fc12b3c97d422138
973
package com.sai.io; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; public class Example33 { public static void main(String[] args) { FileDescriptor fd = null; byte[] b = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58 }; try { FileOutputStream fos = new FileOutputStream("Record.txt"); FileInputStream fis = new FileInputStream("Record.txt"); fd = fos.getFD(); fos.write(b); fos.flush(); fd.sync();// confirms data to be written to the disk int value = 0; // for every available bytes while ((value = fis.read()) != -1) { char c = (char) value;// converts bytes to char System.out.print(c); } System.out.println("\nSync() successfully executed!!"); } catch (Exception e) { e.printStackTrace(); } } }
32.433333
70
0.536485
9f8505ba49a31ae62200ee002ce6ee80f42c8aff
551
package org.slf4j.impl; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import org.slf4j.helpers.NOPLogger; /** * Default NoOp logger binder implementation to satisfy minimum requirements. * * @author patrick.reinhart */ public enum StaticLoggerBinder implements ILoggerFactory { INSTANCE; public static StaticLoggerBinder getSingleton() { return StaticLoggerBinder.INSTANCE; } public ILoggerFactory getLoggerFactory() { return this; } @Override public Logger getLogger(String name) { return NOPLogger.NOP_LOGGER; } }
19.678571
77
0.774955
1b63eb80cc5aab4446b2e7be0867f43c35103d99
1,441
package models; import java.util.Comparator; public class VersionComparator implements Comparator<String> { private VersionComparator(){}; private static VersionComparator INSTANCE = new VersionComparator(); public static VersionComparator getInstance(){ return INSTANCE; } private static Double doubleValue(String s) { try { return Double.valueOf(s); } catch (NumberFormatException e) { return null; } } public int compareVersion(String str1, String str2){ String[] vals1 = str1.split("\\."); String[] vals2 = str2.split("\\."); int i = 0; while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])){ i++; } if (i < vals1.length && i < vals2.length){ int diff = Double.valueOf(vals1[i]).compareTo(Double.valueOf(vals2[i])); return Integer.signum(diff); } else { return Integer.signum(vals1.length - vals2.length); } } @Override public int compare(String s1, String s2) { Double d1 = doubleValue(s1); Double d2 = doubleValue(s2); if (d1 == null && d2 == null) { return s1.compareTo(s2); } else if (d1 == null) { return 1; } else if (d2 == null) { return -1; } else { return compareVersion(s1,s2); } } }
26.2
84
0.547536
7f0d1ee64e5d2b19268319f7b0cf3f11603ebec7
23,245
/*================================================================================ Copyright (c) 2013 Steve Jin. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. 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 VMWARE, INC. 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 com.vmware.vim25; import java.util.Arrays; import java.util.Calendar; /** * This data object type encapsulates configuration settings when creating or reconfiguring a virtual machine. * To support incremental changes, these properties are all optional. * If an optional property is unset, or any nested optional property is unset, the property will not be changed unless 'unset' is a valid value for the property. * To determine whether 'unset' is a valid value for a particular property, refer to the documentation for that property. * * @author Steve Jin (http://www.doublecloud.org) * @author Stefan Dilk <[email protected]> * @version 7.0.2 */ @SuppressWarnings("unused") public class VirtualMachineConfigSpec extends DynamicData { private String changeVersion; private String name; private String version; private Calendar createDate; private String uuid; private String instanceUuid; private Long[] npivNodeWorldWideName; private Long[] npivPortWorldWideName; private String npivWorldWideNameType; private Short npivDesiredNodeWwns; private Short npivDesiredPortWwns; private Boolean npivTemporaryDisabled; private Boolean npivOnNonRdmDisks; private String npivWorldWideNameOp; private String locationId; private String guestId; private String alternateGuestName; private String annotation; private VirtualMachineFileInfo files; private ToolsConfigInfo tools; private VirtualMachineFlagInfo flags; private VirtualMachineConsolePreferences consolePreferences; private VirtualMachineDefaultPowerOpInfo powerOpInfo; private Integer numCPUs; private VirtualMachineVcpuConfig[] vcpuConfig; private Integer numCoresPerSocket; private Long memoryMB; private Boolean memoryHotAddEnabled; private Boolean cpuHotAddEnabled; private Boolean cpuHotRemoveEnabled; private Boolean virtualICH7MPresent; private Boolean virtualSMCPresent; private VirtualDeviceConfigSpec[] deviceChange; private ResourceAllocationInfo cpuAllocation; private ResourceAllocationInfo memoryAllocation; private LatencySensitivity latencySensitivity; private VirtualMachineAffinityInfo cpuAffinity; @Deprecated private VirtualMachineAffinityInfo memoryAffinity; @Deprecated private VirtualMachineNetworkShaperInfo networkShaper; private VirtualMachineCpuIdInfoSpec[] cpuFeatureMask; private OptionValue[] extraConfig; private String swapPlacement; private VirtualMachineBootOptions bootOptions; private VmConfigSpec vAppConfig; private FaultToleranceConfigInfo ftInfo; private ReplicationConfigSpec repConfig; private Boolean vAppConfigRemoved; private Boolean vAssertsEnabled; private Boolean changeTrackingEnabled; private GuestOsDescriptorFirmwareType firmware; private Integer maxMksConnections; private Boolean guestAutoLockEnabled; private ManagedByInfo managedBy; private Boolean memoryReservationLockedToMax; private Boolean nestedHVEnabled; private Boolean vPMCEnabled; private ScheduledHardwareUpgradeInfo scheduledHardwareUpgradeInfo; private VirtualMachineProfileSpec[] vmProfile; private Boolean messageBusTunnelEnabled; private CryptoSpec crypto; private VirtualMachineConfigSpecEncryptedVMotionModes migrateEncryption; private VirtualMachineSgxInfo sgxInfo; private VirtualMachineConfigSpecEncryptedFtModes ftEncryptionMode; private VirtualMachineGuestMonitoringModeInfo guestMonitoringModeInfo; private Boolean sevEnabled; private Boolean pmemFailoverEnabled; @Override public String toString() { return "VirtualMachineConfigSpec{" + "changeVersion='" + changeVersion + '\'' + ", name='" + name + '\'' + ", version='" + version + '\'' + ", createDate=" + createDate + ", uuid='" + uuid + '\'' + ", instanceUuid='" + instanceUuid + '\'' + ", npivNodeWorldWideName=" + Arrays.toString(npivNodeWorldWideName) + ", npivPortWorldWideName=" + Arrays.toString(npivPortWorldWideName) + ", npivWorldWideNameType='" + npivWorldWideNameType + '\'' + ", npivDesiredNodeWwns=" + npivDesiredNodeWwns + ", npivDesiredPortWwns=" + npivDesiredPortWwns + ", npivTemporaryDisabled=" + npivTemporaryDisabled + ", npivOnNonRdmDisks=" + npivOnNonRdmDisks + ", npivWorldWideNameOp='" + npivWorldWideNameOp + '\'' + ", locationId='" + locationId + '\'' + ", guestId='" + guestId + '\'' + ", alternateGuestName='" + alternateGuestName + '\'' + ", annotation='" + annotation + '\'' + ", files=" + files + ", tools=" + tools + ", flags=" + flags + ", consolePreferences=" + consolePreferences + ", powerOpInfo=" + powerOpInfo + ", numCPUs=" + numCPUs + ", vcpuConfig=" + Arrays.toString(vcpuConfig) + ", numCoresPerSocket=" + numCoresPerSocket + ", memoryMB=" + memoryMB + ", memoryHotAddEnabled=" + memoryHotAddEnabled + ", cpuHotAddEnabled=" + cpuHotAddEnabled + ", cpuHotRemoveEnabled=" + cpuHotRemoveEnabled + ", virtualICH7MPresent=" + virtualICH7MPresent + ", virtualSMCPresent=" + virtualSMCPresent + ", deviceChange=" + Arrays.toString(deviceChange) + ", cpuAllocation=" + cpuAllocation + ", memoryAllocation=" + memoryAllocation + ", latencySensitivity=" + latencySensitivity + ", cpuAffinity=" + cpuAffinity + ", memoryAffinity=" + memoryAffinity + ", networkShaper=" + networkShaper + ", cpuFeatureMask=" + Arrays.toString(cpuFeatureMask) + ", extraConfig=" + Arrays.toString(extraConfig) + ", swapPlacement='" + swapPlacement + '\'' + ", bootOptions=" + bootOptions + ", vAppConfig=" + vAppConfig + ", ftInfo=" + ftInfo + ", repConfig=" + repConfig + ", vAppConfigRemoved=" + vAppConfigRemoved + ", vAssertsEnabled=" + vAssertsEnabled + ", changeTrackingEnabled=" + changeTrackingEnabled + ", firmware='" + firmware + '\'' + ", maxMksConnections=" + maxMksConnections + ", guestAutoLockEnabled=" + guestAutoLockEnabled + ", managedBy=" + managedBy + ", memoryReservationLockedToMax=" + memoryReservationLockedToMax + ", nestedHVEnabled=" + nestedHVEnabled + ", vPMCEnabled=" + vPMCEnabled + ", scheduledHardwareUpgradeInfo=" + scheduledHardwareUpgradeInfo + ", vmProfile=" + Arrays.toString(vmProfile) + ", messageBusTunnelEnabled=" + messageBusTunnelEnabled + ", crypto=" + crypto + ", migrateEncryption='" + migrateEncryption + '\'' + ", sgxInfo=" + sgxInfo + ", ftEncryptionMode=" + ftEncryptionMode + ", guestMonitoringModeInfo=" + guestMonitoringModeInfo + ", sevEnabled=" + sevEnabled + ", pmemFailoverEnabled=" + pmemFailoverEnabled + '}'; } public String getAlternateGuestName() { return alternateGuestName; } public void setAlternateGuestName(final String alternateGuestName) { this.alternateGuestName = alternateGuestName; } public String getAnnotation() { return annotation; } public void setAnnotation(final String annotation) { this.annotation = annotation; } public VirtualMachineBootOptions getBootOptions() { return bootOptions; } public void setBootOptions(final VirtualMachineBootOptions bootOptions) { this.bootOptions = bootOptions; } public Boolean getChangeTrackingEnabled() { return changeTrackingEnabled; } public void setChangeTrackingEnabled(final Boolean changeTrackingEnabled) { this.changeTrackingEnabled = changeTrackingEnabled; } public String getChangeVersion() { return changeVersion; } public void setChangeVersion(final String changeVersion) { this.changeVersion = changeVersion; } public VirtualMachineConsolePreferences getConsolePreferences() { return consolePreferences; } public void setConsolePreferences(final VirtualMachineConsolePreferences consolePreferences) { this.consolePreferences = consolePreferences; } public VirtualMachineAffinityInfo getCpuAffinity() { return cpuAffinity; } public void setCpuAffinity(final VirtualMachineAffinityInfo cpuAffinity) { this.cpuAffinity = cpuAffinity; } public ResourceAllocationInfo getCpuAllocation() { return cpuAllocation; } public void setCpuAllocation(final ResourceAllocationInfo cpuAllocation) { this.cpuAllocation = cpuAllocation; } public VirtualMachineCpuIdInfoSpec[] getCpuFeatureMask() { return cpuFeatureMask; } public void setCpuFeatureMask(final VirtualMachineCpuIdInfoSpec[] cpuFeatureMask) { this.cpuFeatureMask = cpuFeatureMask; } public Boolean getCpuHotAddEnabled() { return cpuHotAddEnabled; } public void setCpuHotAddEnabled(final Boolean cpuHotAddEnabled) { this.cpuHotAddEnabled = cpuHotAddEnabled; } public Boolean getCpuHotRemoveEnabled() { return cpuHotRemoveEnabled; } public void setCpuHotRemoveEnabled(final Boolean cpuHotRemoveEnabled) { this.cpuHotRemoveEnabled = cpuHotRemoveEnabled; } public Calendar getCreateDate() { return createDate; } public void setCreateDate(final Calendar createDate) { this.createDate = createDate; } public CryptoSpec getCrypto() { return crypto; } public void setCrypto(final CryptoSpec crypto) { this.crypto = crypto; } public VirtualDeviceConfigSpec[] getDeviceChange() { return deviceChange; } public void setDeviceChange(final VirtualDeviceConfigSpec[] deviceChange) { this.deviceChange = deviceChange; } public OptionValue[] getExtraConfig() { return extraConfig; } public void setExtraConfig(final OptionValue[] extraConfig) { this.extraConfig = extraConfig; } public VirtualMachineFileInfo getFiles() { return files; } public void setFiles(final VirtualMachineFileInfo files) { this.files = files; } public GuestOsDescriptorFirmwareType getFirmware() { return firmware; } public void setFirmware(final GuestOsDescriptorFirmwareType firmware) { this.firmware = firmware; } public VirtualMachineFlagInfo getFlags() { return flags; } public void setFlags(final VirtualMachineFlagInfo flags) { this.flags = flags; } public FaultToleranceConfigInfo getFtInfo() { return ftInfo; } public void setFtInfo(final FaultToleranceConfigInfo ftInfo) { this.ftInfo = ftInfo; } public Boolean getGuestAutoLockEnabled() { return guestAutoLockEnabled; } public void setGuestAutoLockEnabled(final Boolean guestAutoLockEnabled) { this.guestAutoLockEnabled = guestAutoLockEnabled; } public String getGuestId() { return guestId; } public void setGuestId(final String guestId) { this.guestId = guestId; } public String getInstanceUuid() { return instanceUuid; } public void setInstanceUuid(final String instanceUuid) { this.instanceUuid = instanceUuid; } public LatencySensitivity getLatencySensitivity() { return latencySensitivity; } public void setLatencySensitivity(final LatencySensitivity latencySensitivity) { this.latencySensitivity = latencySensitivity; } public String getLocationId() { return locationId; } public void setLocationId(final String locationId) { this.locationId = locationId; } public ManagedByInfo getManagedBy() { return managedBy; } public void setManagedBy(final ManagedByInfo managedBy) { this.managedBy = managedBy; } public Integer getMaxMksConnections() { return maxMksConnections; } public void setMaxMksConnections(final Integer maxMksConnections) { this.maxMksConnections = maxMksConnections; } public VirtualMachineAffinityInfo getMemoryAffinity() { return memoryAffinity; } public void setMemoryAffinity(final VirtualMachineAffinityInfo memoryAffinity) { this.memoryAffinity = memoryAffinity; } public ResourceAllocationInfo getMemoryAllocation() { return memoryAllocation; } public void setMemoryAllocation(final ResourceAllocationInfo memoryAllocation) { this.memoryAllocation = memoryAllocation; } public Boolean getMemoryHotAddEnabled() { return memoryHotAddEnabled; } public void setMemoryHotAddEnabled(final Boolean memoryHotAddEnabled) { this.memoryHotAddEnabled = memoryHotAddEnabled; } public Long getMemoryMB() { return memoryMB; } public void setMemoryMB(final Long memoryMB) { this.memoryMB = memoryMB; } public Boolean getMemoryReservationLockedToMax() { return memoryReservationLockedToMax; } public void setMemoryReservationLockedToMax(final Boolean memoryReservationLockedToMax) { this.memoryReservationLockedToMax = memoryReservationLockedToMax; } public Boolean getMessageBusTunnelEnabled() { return messageBusTunnelEnabled; } public void setMessageBusTunnelEnabled(final Boolean messageBusTunnelEnabled) { this.messageBusTunnelEnabled = messageBusTunnelEnabled; } public VirtualMachineConfigSpecEncryptedVMotionModes getMigrateEncryption() { return migrateEncryption; } public void setMigrateEncryption(final VirtualMachineConfigSpecEncryptedVMotionModes migrateEncryption) { this.migrateEncryption = migrateEncryption; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Boolean getNestedHVEnabled() { return nestedHVEnabled; } public void setNestedHVEnabled(final Boolean nestedHVEnabled) { this.nestedHVEnabled = nestedHVEnabled; } public VirtualMachineNetworkShaperInfo getNetworkShaper() { return networkShaper; } public void setNetworkShaper(final VirtualMachineNetworkShaperInfo networkShaper) { this.networkShaper = networkShaper; } public Short getNpivDesiredNodeWwns() { return npivDesiredNodeWwns; } public void setNpivDesiredNodeWwns(final Short npivDesiredNodeWwns) { this.npivDesiredNodeWwns = npivDesiredNodeWwns; } public Short getNpivDesiredPortWwns() { return npivDesiredPortWwns; } public void setNpivDesiredPortWwns(final Short npivDesiredPortWwns) { this.npivDesiredPortWwns = npivDesiredPortWwns; } public Long[] getNpivNodeWorldWideName() { return npivNodeWorldWideName; } public void setNpivNodeWorldWideName(final Long[] npivNodeWorldWideName) { this.npivNodeWorldWideName = npivNodeWorldWideName; } public Boolean getNpivOnNonRdmDisks() { return npivOnNonRdmDisks; } public void setNpivOnNonRdmDisks(final Boolean npivOnNonRdmDisks) { this.npivOnNonRdmDisks = npivOnNonRdmDisks; } public Long[] getNpivPortWorldWideName() { return npivPortWorldWideName; } public void setNpivPortWorldWideName(final Long[] npivPortWorldWideName) { this.npivPortWorldWideName = npivPortWorldWideName; } public Boolean getNpivTemporaryDisabled() { return npivTemporaryDisabled; } public void setNpivTemporaryDisabled(final Boolean npivTemporaryDisabled) { this.npivTemporaryDisabled = npivTemporaryDisabled; } public String getNpivWorldWideNameOp() { return npivWorldWideNameOp; } public void setNpivWorldWideNameOp(final String npivWorldWideNameOp) { this.npivWorldWideNameOp = npivWorldWideNameOp; } public String getNpivWorldWideNameType() { return npivWorldWideNameType; } public void setNpivWorldWideNameType(final String npivWorldWideNameType) { this.npivWorldWideNameType = npivWorldWideNameType; } public Integer getNumCoresPerSocket() { return numCoresPerSocket; } public void setNumCoresPerSocket(final Integer numCoresPerSocket) { this.numCoresPerSocket = numCoresPerSocket; } public Integer getNumCPUs() { return numCPUs; } public void setNumCPUs(final Integer numCPUs) { this.numCPUs = numCPUs; } public VirtualMachineDefaultPowerOpInfo getPowerOpInfo() { return powerOpInfo; } public void setPowerOpInfo(final VirtualMachineDefaultPowerOpInfo powerOpInfo) { this.powerOpInfo = powerOpInfo; } public ReplicationConfigSpec getRepConfig() { return repConfig; } public void setRepConfig(final ReplicationConfigSpec repConfig) { this.repConfig = repConfig; } public ScheduledHardwareUpgradeInfo getScheduledHardwareUpgradeInfo() { return scheduledHardwareUpgradeInfo; } public void setScheduledHardwareUpgradeInfo(final ScheduledHardwareUpgradeInfo scheduledHardwareUpgradeInfo) { this.scheduledHardwareUpgradeInfo = scheduledHardwareUpgradeInfo; } public String getSwapPlacement() { return swapPlacement; } public void setSwapPlacement(final String swapPlacement) { this.swapPlacement = swapPlacement; } public ToolsConfigInfo getTools() { return tools; } public void setTools(final ToolsConfigInfo tools) { this.tools = tools; } public String getUuid() { return uuid; } public void setUuid(final String uuid) { this.uuid = uuid; } public VmConfigSpec getvAppConfig() { return vAppConfig; } public void setvAppConfig(final VmConfigSpec vAppConfig) { this.vAppConfig = vAppConfig; } public Boolean getvAppConfigRemoved() { return vAppConfigRemoved; } public void setvAppConfigRemoved(final Boolean vAppConfigRemoved) { this.vAppConfigRemoved = vAppConfigRemoved; } public Boolean getvAssertsEnabled() { return vAssertsEnabled; } public void setvAssertsEnabled(final Boolean vAssertsEnabled) { this.vAssertsEnabled = vAssertsEnabled; } public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } public Boolean getVirtualICH7MPresent() { return virtualICH7MPresent; } public void setVirtualICH7MPresent(final Boolean virtualICH7MPresent) { this.virtualICH7MPresent = virtualICH7MPresent; } public Boolean getVirtualSMCPresent() { return virtualSMCPresent; } public void setVirtualSMCPresent(final Boolean virtualSMCPresent) { this.virtualSMCPresent = virtualSMCPresent; } public VirtualMachineProfileSpec[] getVmProfile() { return vmProfile; } public void setVmProfile(final VirtualMachineProfileSpec[] vmProfile) { this.vmProfile = vmProfile; } public Boolean getvPMCEnabled() { return vPMCEnabled; } public void setvPMCEnabled(final Boolean vPMCEnabled) { this.vPMCEnabled = vPMCEnabled; } public VirtualMachineSgxInfo getSgxInfo() { return sgxInfo; } public void setSgxInfo(final VirtualMachineSgxInfo sgxInfo) { this.sgxInfo = sgxInfo; } public VirtualMachineGuestMonitoringModeInfo getGuestMonitoringModeInfo() { return guestMonitoringModeInfo; } public void setGuestMonitoringModeInfo(final VirtualMachineGuestMonitoringModeInfo guestMonitoringModeInfo) { this.guestMonitoringModeInfo = guestMonitoringModeInfo; } public Boolean getSevEnabled() { return sevEnabled; } public void setSevEnabled(final Boolean sevEnabled) { this.sevEnabled = sevEnabled; } public VirtualMachineVcpuConfig[] getVcpuConfig() { return vcpuConfig; } public void setVcpuConfig(final VirtualMachineVcpuConfig[] vcpuConfig) { this.vcpuConfig = vcpuConfig; } public VirtualMachineConfigSpecEncryptedFtModes getFtEncryptionMode() { return ftEncryptionMode; } public void setFtEncryptionMode(final VirtualMachineConfigSpecEncryptedFtModes ftEncryptionMode) { this.ftEncryptionMode = ftEncryptionMode; } public Boolean getPmemFailoverEnabled() { return pmemFailoverEnabled; } public void setPmemFailoverEnabled(final Boolean pmemFailoverEnabled) { this.pmemFailoverEnabled = pmemFailoverEnabled; } }
32.374652
161
0.684147
4b251923f2b1ac9764f208630bfe51cd18222469
421
package com.beautifulsoup.chengfeng.controller.vo; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class WaterBrandVo { private Integer id; private String brand; private Long price; }
20.047619
52
0.812352
92202574760da9ea16d23265328e62ab76d6ccd9
1,364
package com.baomidou.springmvc.common; import com.baomidou.springmvc.listener.MyApplicationListener; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean.getClass() == MyApplicationListener.class) { MyApplicationListener s = (MyApplicationListener) bean; System.err.println("before postProcessBeforeInitialization name is:" + s.getName()); s.setName("MyApplicationListener"); System.err.println("before postProcessBeforeInitialization name is:" + s.getName()); return s; } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean.getClass() == MyApplicationListener.class) { MyApplicationListener s = (MyApplicationListener) bean; System.err.println("before postProcessAfterInitialization name is:" + s.getName()); s.setName("haha"); System.err.println("before postProcessAfterInitialization name is:" + s.getName()); return s; } return bean; } }
42.625
103
0.697214
e1b99b4bf709cefe3b94f294453c8309438df73a
1,750
/* * Copyright 2012 Daniel Rendall * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.danielrendall.metaphor.parsers; import com.google.common.collect.Lists; import uk.co.danielrendall.metaphor.*; import uk.co.danielrendall.metaphor.records.END; import uk.co.danielrendall.metaphor.records.LINE; import uk.co.danielrendall.metaphor.records.RULER; import java.io.PushbackInputStream; import java.util.List; /** * @author Daniel Rendall */ public class LINEParser extends Parser<LINE> { @Override protected LINE doParse(PushbackInputStream in) throws ParseException { Record.Options options = readOptions(in); Record.Nudge nudge = options.nudge() ? readNudge(in) : Record.NO_NUDGE; int lineSpacing = options.line_lspace() ? readSimple16BitInteger(in) : -1; RULER ruler = options.lp_ruler() ? (RULER)ParserRegistry.get(ParserRegistry.RULER).parse(in) : RULER.NO_RULER; List<Record> records = Lists.newArrayList(); if (!options.line_null()) { readRecordsToEnd(in, records); } return new LINE(options, nudge, lineSpacing, ruler, records); } @Override protected int getInitialByte() { return ParserRegistry.LINE; } }
35
118
0.718857
53ca188c545b233020c82094e6e6e26ae95267b4
1,370
package com.yangzg.crud.controller; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; /** * Created by Sam on 2019/12/3. */ @Controller public class HelloController { @GetMapping("/${hello.path:hello}") public String handle(Model model) { model.addAttribute("message", "Hello World!"); return "hello"; } @ResponseBody @GetMapping(value = "/consumes", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public Map<String, Object> consumes() { return new HashMap<String, Object>() { private static final long serialVersionUID = -6692761828144558364L; { put("name", "yzg"); put("age", 12); } }; } @ResponseBody @GetMapping(value = "/produces", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public Map<String, Object> produces() { return new HashMap<String, Object>() { private static final long serialVersionUID = -6692761828144558364L; { put("name", "yangzg"); put("age", 13); } }; } }
29.148936
86
0.631387
d004a4c2a7dac97c375ca94fb70b166ec8eea018
3,680
package tw.bill.java101.domain; import tw.bill.java101.domain.security.Role; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; /** * Created by bill33 on 2016/2/14. */ @Entity public class User extends AbstractDomainClass{ @Column(unique = true) private String email; private String nickName; private String passwordHash; @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinTable private List<Role> roles = new ArrayList<>(); @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinTable private List<Team> teams = new ArrayList<>(); private boolean enabled = true; @ElementCollection(targetClass = Hobby.class) @Enumerated(EnumType.STRING) private List<Hobby> hobbies; private Sex sex = Sex.MALE; private Degree degree; private String introduce; private Date birthday; public User() { } public User(String email, String nickName, String passwordHash) { this.email = email; this.nickName = nickName; this.passwordHash = passwordHash; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPasswordHash() { return passwordHash; } public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public void addRole(Role role){ if(!this.roles.contains(role)){ this.roles.add(role); } if(!role.getUsers().contains(this)){ role.getUsers().add(this); } } public void removeRole(Role role){ this.roles.remove(role); role.getUsers().remove(this); } public List<Team> getTeams() { return teams; } public void setTeams(List<Team> teams) { this.teams = teams; } public void addTeam(Team team){ if(!this.teams.contains(team)){ this.teams.add(team); } if(!team.getUsers().contains(this)){ team.getUsers().add(this); } } public void removeTeam(Team team){ this.teams.remove(team); team.getUsers().remove(this); } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public List<Hobby> getHobbies() { return hobbies; } public void setHobbies(List<Hobby> hobbies) { this.hobbies = hobbies; } public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; } public Degree getDegree() { return degree; } public void setDegree(Degree degree) { this.degree = degree; } public String getIntroduce() { return introduce; } public void setIntroduce(String introduce) { this.introduce = introduce; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
20.674157
92
0.606522
ca14d57ebf3dda1eb649d578ed9471cd0e2f092b
1,343
/** * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. */ package com.app.wechat.response; import com.alibaba.fastjson.annotation.JSONField; /** * <p>ๅŠŸ ่ƒฝ๏ผš็พคๅ‘ๆถˆๆฏ-ๆ นๆฎๆ ‡็ญพ่ฟ›่กŒ็พคๅ‘API็š„ๅ“ๅบ”ไฟกๆฏ</p> * <p>็‰ˆ ๆƒ๏ผšCopyright (c) 2017</p> * <p>ๅˆ›ๅปบๆ—ถ้—ด๏ผš2017ๅนด7ๆœˆ6ๆ—ฅ ไธ‹ๅˆ6:53:48</p> * * @author ็Ž‹ๅปบ * @version 1.0 */ public class WxMassSendAllResponse extends AbstractWxResponse { private static final long serialVersionUID = 1L; /** * ๆถˆๆฏๅ‘้€ไปปๅŠก็š„ID */ @JSONField(name = "msg_id") private Long msgId; /** * ๆถˆๆฏ็š„ๆ•ฐๆฎID๏ผŒ่ฏฅๅญ—ๆฎตๅชๆœ‰ๅœจ็พคๅ‘ๅ›พๆ–‡ๆถˆๆฏๆ—ถ๏ผŒๆ‰ไผšๅ‡บ็Žฐ * <p>ๅฏไปฅ็”จไบŽๅœจๅ›พๆ–‡ๅˆ†ๆžๆ•ฐๆฎๆŽฅๅฃไธญ๏ผŒ่Žทๅ–ๅˆฐๅฏนๅบ”็š„ๅ›พๆ–‡ๆถˆๆฏ็š„ๆ•ฐๆฎ๏ผŒๆ˜ฏๅ›พๆ–‡ๅˆ†ๆžๆ•ฐๆฎๆŽฅๅฃไธญ็š„msgidๅญ—ๆฎตไธญ็š„ๅ‰ๅŠ้ƒจๅˆ†<br/> * ่ฏฆ่งๅ›พๆ–‡ๅˆ†ๆžๆ•ฐๆฎๆŽฅๅฃไธญ็š„msgidๅญ—ๆฎต็š„ไป‹็ป</p> */ @JSONField(name = "msg_data_id") private Long msgDataId; public Long getMsgId() { return msgId; } public void setMsgId(Long msgId) { this.msgId = msgId; } public Long getMsgDataId() { return msgDataId; } public void setMsgDataId(Long msgDataId) { this.msgDataId = msgDataId; } }
25.339623
97
0.676098
383bc8edbc772988ed3ca9506a86677ee5960b0b
1,293
package service.external; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import com.azure.ai.textanalytics.models.DocumentSentiment; import model.azure.RetornoAzure; @Stateless @LocalBean public class APIAnaliseDeTexto { @EJB APIAnaliseDeTextoUnit unit; @TransactionAttribute(TransactionAttributeType.SUPPORTS) public RetornoAzure analiseDeSentimento(String texto) throws Exception { Future<DocumentSentiment> futureDocumentSentiment = this.unit.getDocumentSentiment(texto); DocumentSentiment documentSentiment = null; if (futureDocumentSentiment != null) { documentSentiment = futureDocumentSentiment.get(15, TimeUnit.SECONDS); RetornoAzure retornoAzure = new RetornoAzure(); retornoAzure.setSentiment(documentSentiment.getSentiment().toString()); retornoAzure.setPositiveScore(documentSentiment.getConfidenceScores().getPositive()); retornoAzure.setNeutralScore(documentSentiment.getConfidenceScores().getNeutral()); retornoAzure.setNegativeScore(documentSentiment.getConfidenceScores().getNegative()); return retornoAzure; } else { return null; } } }
28.108696
92
0.811292
9a047ad3506664745fd5f117b441a45162aaad16
132
package com.ne0fhyklabs.freeflight.drone; public interface DroneProxyConfigChangedReceiverDelegate { void onConfigChanged(); }
18.857143
56
0.825758
c2cb6a805ecce16b56854b094ea173d36a9125fe
1,404
package gnova.config.reader.xml; import gnova.core.annotation.NotNull; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DomHelper { @NotNull public static Element readElement(@NotNull String xml) throws DocumentException { Document doc = DocumentHelper.parseText(xml); return doc.getRootElement(); } public static Map<String, Object> subElements(@NotNull Element root) { Map<String, Object> cache = new HashMap<>(); List<Element> elements = root.elements(); for (Element element : elements) { Object o = cache.get(element.getName()); if (o == null) { cache.put(element.getName(), element); } else { if (o instanceof Element) { List<Element> list = new ArrayList<>(); list.add((Element) o); list.add(element); cache.put(element.getName(), list); } else { List<Element> list = (List<Element>) o; list.add(element); cache.put(element.getName(), list); } } } return cache; } }
29.87234
74
0.56339
a849618056d3e8600918a2ee994141641853f164
276
package com.dp.others.dependencyinjection; public class MyLegacyApplication { private EmailService email = new EmailService(); public void processMessages(String msg, String rec) { // do some msg validation, manipulation logic etc this.email.sendEmail(msg, rec); } }
25.090909
54
0.768116
57323ea9947c5f5d655538a13eefd1aae149d8de
1,474
package com.kgregorczyk.bank.controllers.dto; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.UUID; import lombok.Builder; import lombok.Getter; import spark.route.HttpMethod; /** Represents a link for HATEOAS responses. */ @Getter @Builder public class Link { private static final ImmutableList<Link> LINKS_FOR_ACCOUNTS = ImmutableList.of( Link.builder().rel("self").href("/api/account").method(HttpMethod.get).build(), Link.builder().rel("self").href("/api/account").method(HttpMethod.post).build(), Link.builder() .rel("self") .href("/api/account/transferMoney") .method(HttpMethod.post) .build()); private String rel; private String href; private HttpMethod method; public static List<Link> getLinksForAccounts() { return LINKS_FOR_ACCOUNTS; } public static List<Link> getLinksForAccount(UUID aggreagateUUID) { return getLinksForAccount(aggreagateUUID.toString()); } public static List<Link> getLinksForAccount(String aggregateUUID) { return ImmutableList.of( Link.builder() .rel("self") .href("/api/account/" + aggregateUUID) .method(HttpMethod.get) .build(), Link.builder() .rel("self") .href("/api/account/" + aggregateUUID + "/changeFullName") .method(HttpMethod.put) .build()); } }
28.901961
90
0.639756
4eb24527b06864330c125c2988a0092bead02a9a
12,128
/* * 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 eu.fusepool.enhancer.adapter.service; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilderException; import javax.ws.rs.core.UriInfo; import org.apache.clerezza.jaxrs.utils.TrailingSlash; import org.apache.clerezza.rdf.core.Graph; import org.apache.clerezza.rdf.core.Resource; import org.apache.clerezza.rdf.core.Triple; import org.apache.clerezza.rdf.core.UriRef; import org.apache.clerezza.rdf.core.serializedform.Parser; import org.apache.clerezza.rdf.core.serializedform.SupportedFormat; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.ConfigurationPolicy; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.json.simple.JSONObject; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Configuration service */ @Component(policy = ConfigurationPolicy.OPTIONAL, metatype = true, immediate = true) @Service(Object.class) @Property(name="javax.ws.rs", boolValue=true) @Path("fusepool/config") public class ConfigService { /** * Using slf4j for logging */ private final Logger log = LoggerFactory.getLogger(getClass()); public static final int DEFAULT_LDP_PORT = 8181; public static final String DEFAULT_LDP_PATH = "ldp/"; public static final String[] TRANSFORMER_REGISTRY_PATH = new String[]{"tr-ldpc"}; public static final String TRANSFORMER_ADAPTER_SERVICE = "eu.fusepool.enhancer.adapter.service.Transformers"; public static final String PROP_TRANSFORMER_REGISTRY_URI = "transformer.registry"; public static final String PROP_STANBOL_BASE_URI = "stanbol.base.uri"; public static final UriRef TRANSFORMER_REGISTRY_PREDICATE = new UriRef("http://vocab.fusepool.info/fp3#transformerRegistry"); @Reference private ConfigurationAdmin configAdmin; @Reference private Parser parser; @Activate protected void activate(ComponentContext context) throws ConfigurationException { log.info("> activating {}",getClass().getName()); } @Deactivate protected void deactivate(ComponentContext context) { log.info("> deactivating {}",getClass().getName()); } /** * {@link PUT} version of the {@link #config(String, String, String, UriInfo, HttpHeaders) config} * method */ @PUT @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Response configPut(@FormParam("ldp") String ldpBaseUri, @FormParam("stanbol") String stanbolBaseUri, @FormParam("fusepool") String platformUri, @Context final UriInfo uriInfo, @Context HttpHeaders headers) { return config(ldpBaseUri, stanbolBaseUri, platformUri, uriInfo, headers); } /** * {@link POST} version of the {@link #config(String, String, String, UriInfo, HttpHeaders) config} * method */ @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Response configPost(@FormParam("ldp") String ldpBaseUri, @FormParam("stanbol") String stanbolBaseUri, @FormParam("fusepool") String platformUri, @Context final UriInfo uriInfo, @Context HttpHeaders headers) { return config(ldpBaseUri, stanbolBaseUri, platformUri, uriInfo, headers); } /** * Configures this Stanbol instance for a Fusepool Plattform * @param ldpBaseUri allows to directly configure the LDP base URI * @param stanbolBaseUri allows to directly configure the Stanbol Base URI * @param platformUri The Fusepool Platform URI. A LDP context containing * all information about the Fusepool Platform. If present this has * preferrence over the ldpBaseUri * @param uriInfo * @param headers */ @GET @Produces(MediaType.APPLICATION_JSON) public Response config(@QueryParam("ldp") String ldpBaseUri, @QueryParam("stanbol") String stanbolBaseUri, @QueryParam("fusepool") String platformUri, @Context final UriInfo uriInfo, @Context HttpHeaders headers) { TrailingSlash.enforcePresent(uriInfo); String transformerRegistryUri; log.info("> configuration Reuqest"); URI baseUri = uriInfo.getBaseUri(); if(StringUtils.isBlank(stanbolBaseUri)){ log.debug(" ... using base URI of request for setting Stanbol base URI"); stanbolBaseUri = baseUri.toString(); } log.info(" - stanbol: {}", stanbolBaseUri); if(!StringUtils.isBlank(platformUri)){ log.info(" - fusepool: {}", platformUri); final URL platformURL; try { platformURL = new URL(platformUri); } catch (MalformedURLException e) { throw new WebApplicationException("The value of the 'fusepool' " + "parameter MUST BE a valid URL",e,Status.BAD_REQUEST); } final Graph fusepoolInfo; try { URLConnection con = platformURL.openConnection(); con.addRequestProperty("Accept",SupportedFormat.TURTLE); con.getInputStream(); fusepoolInfo = parser.parse(con.getInputStream(), con.getContentType()); } catch (IOException e) { throw new WebApplicationException("Unable to load Fusepool Platform " + "Information from the parsed URL '"+platformUri+"'!", e,Status.NOT_FOUND); } //TODO: collect the required infor from the Fusepool platform context Iterator<Triple> it = fusepoolInfo.filter(null, TRANSFORMER_REGISTRY_PREDICATE, null); if(it.hasNext()){ Resource val = it.next().getObject(); if(val instanceof UriRef){ transformerRegistryUri = ((UriRef)val).getUnicodeString(); } else { throw new WebApplicationException("Fusepool Platform " + "Information at '" + platformUri + "'has an invalid " + " Transformer Registry URI (value: '" + val+"', type: " + val.getClass() + ")!", Status.BAD_REQUEST); } } else { throw new WebApplicationException("Fusepool Platform " + "Information at '" + platformUri + "'is missing the " + "requred Transformer Registry URI (property: '" + TRANSFORMER_REGISTRY_PREDICATE+"')!", Status.BAD_REQUEST); } } else { //fall back to the LDP base URI log.info(" - no Fusepool Platform URI parsed in configuration request"); if(ldpBaseUri == null){ log.debug(" ... using default for the LDP base URI"); try { ldpBaseUri = new URI(baseUri.getScheme(), baseUri.getUserInfo(), baseUri.getHost(), DEFAULT_LDP_PORT, DEFAULT_LDP_PATH, null, null).toString(); } catch (URISyntaxException e) { throw new WebApplicationException(e); } } log.info(" - ldp base: {}", ldpBaseUri); try { transformerRegistryUri = UriBuilder.fromUri(new URI(ldpBaseUri)).segment(TRANSFORMER_REGISTRY_PATH).build().toString(); } catch (UriBuilderException e) { throw new WebApplicationException(e); } catch (URISyntaxException e) { throw new WebApplicationException("Value of the 'ldp' parameter needs to be a valid URI!",e, Status.BAD_REQUEST); } } log.info(" - transformer registry: {}", transformerRegistryUri); Configuration transformerAdapterConfig; try { transformerAdapterConfig = configAdmin.getConfiguration(TRANSFORMER_ADAPTER_SERVICE); } catch (IOException e) { log.warn("Unable to lookup configuration of the '"+TRANSFORMER_ADAPTER_SERVICE+",!",e); transformerAdapterConfig = null; } if(transformerAdapterConfig.getProperties() != null && stanbolBaseUri.equals(transformerAdapterConfig.getProperties().get(PROP_STANBOL_BASE_URI)) && transformerRegistryUri.equals(transformerAdapterConfig.getProperties().get(PROP_TRANSFORMER_REGISTRY_URI))){ //this request parses the same config as the existing one log.info(" ... parsed config already present (nothing to do)"); } else { if(transformerAdapterConfig.getProperties() != null) { log.info("> current config:"); log.info(" - stanbol: {}", transformerAdapterConfig.getProperties().get(PROP_STANBOL_BASE_URI)); log.info(" - tr-ldpc: {}", transformerAdapterConfig.getProperties().get(PROP_TRANSFORMER_REGISTRY_URI)); } else { log.info("> no config present"); } log.info(" ... updating configuration ..."); Dictionary<String, Object> config = new Hashtable<>(); config.put(PROP_STANBOL_BASE_URI, stanbolBaseUri); config.put(PROP_TRANSFORMER_REGISTRY_URI, transformerRegistryUri); try { transformerAdapterConfig.setBundleLocation(null); transformerAdapterConfig.update(config); } catch (IOException e) { throw new WebApplicationException("Unable to set configuration!", e); } log.info(" ... config {} updated!",transformerAdapterConfig); } Map<String,String> config = new HashMap<String, String>(); config.put(PROP_STANBOL_BASE_URI, stanbolBaseUri); config.put(PROP_TRANSFORMER_REGISTRY_URI, transformerRegistryUri); return Response.ok(JSONObject.toJSONString(config),MediaType.APPLICATION_JSON_TYPE).build(); } }
44.101818
135
0.655425
f625952ecf822bb7c7245c81d20f4056cd7ad637
24,456
package com.avaje.ebeaninternal.server.deploy.meta; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.Entity; import javax.persistence.MappedSuperclass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.avaje.ebean.annotation.ConcurrencyMode; import com.avaje.ebean.config.TableName; import com.avaje.ebean.config.dbplatform.IdGenerator; import com.avaje.ebean.config.dbplatform.IdType; import com.avaje.ebean.event.BeanFinder; import com.avaje.ebean.event.BeanPersistController; import com.avaje.ebean.event.BeanPersistListener; import com.avaje.ebean.event.BeanQueryAdapter; import com.avaje.ebeaninternal.server.core.CacheOptions; import com.avaje.ebeaninternal.server.deploy.BeanDescriptor.EntityType; import com.avaje.ebeaninternal.server.deploy.ChainedBeanPersistController; import com.avaje.ebeaninternal.server.deploy.ChainedBeanPersistListener; import com.avaje.ebeaninternal.server.deploy.ChainedBeanQueryAdapter; import com.avaje.ebeaninternal.server.deploy.CompoundUniqueContraint; import com.avaje.ebeaninternal.server.deploy.DRawSqlMeta; import com.avaje.ebeaninternal.server.deploy.DeployNamedQuery; import com.avaje.ebeaninternal.server.deploy.DeployNamedUpdate; import com.avaje.ebeaninternal.server.deploy.InheritInfo; import com.avaje.ebeaninternal.server.properties.BeanPropertyInfo; /** * Describes Beans including their deployment information. */ public class DeployBeanDescriptor<T> { static class PropOrder implements Comparator<DeployBeanProperty> { public int compare(DeployBeanProperty o1, DeployBeanProperty o2) { int v2 = o1.getSortOrder(); int v1 = o2.getSortOrder(); return (v1 < v2 ? -1 : (v1 == v2 ? 0 : 1)); } } private static final PropOrder PROP_ORDER = new PropOrder(); private static final String I_SCALAOBJECT = "scala.ScalaObject"; private static final Logger logger = LoggerFactory.getLogger(DeployBeanDescriptor.class); /** * Map of BeanProperty Linked so as to preserve order. */ private LinkedHashMap<String, DeployBeanProperty> propMap = new LinkedHashMap<String, DeployBeanProperty>(); private EntityType entityType; private final Map<String, DeployNamedQuery> namedQueries = new LinkedHashMap<String, DeployNamedQuery>(); private final Map<String, DeployNamedUpdate> namedUpdates = new LinkedHashMap<String, DeployNamedUpdate>(); private final Map<String, DRawSqlMeta> rawSqlMetas = new LinkedHashMap<String, DRawSqlMeta>(); private DeployBeanPropertyAssocOne<?> unidirectional; /** * Type of Identity generation strategy used. */ private IdType idType; /** * The name of an IdGenerator (optional). */ private String idGeneratorName; private IdGenerator idGenerator; /** * The database sequence name (optional). */ private String sequenceName; /** * Used with Identity columns but no getGeneratedKeys support. */ private String selectLastInsertedId; private String lazyFetchIncludes; /** * The concurrency mode for beans of this type. */ private ConcurrencyMode concurrencyMode; private boolean updateChangesOnly; /** * The tables this bean is dependent on. */ private String[] dependantTables; private List<CompoundUniqueContraint> compoundUniqueConstraints; /** * The base database table. */ private String baseTable; private TableName baseTableFull; /** * Used to provide mechanism to new EntityBean instances. Generated code * faster than reflection at this stage. */ private BeanPropertyInfo beanReflect; private String[] properties; /** * The EntityBean type used to create new EntityBeans. */ private Class<T> beanType; private List<BeanPersistController> persistControllers = new ArrayList<BeanPersistController>(2); private List<BeanPersistListener> persistListeners = new ArrayList<BeanPersistListener>(2); private List<BeanQueryAdapter> queryAdapters = new ArrayList<BeanQueryAdapter>(2); private CacheOptions cacheOptions = new CacheOptions(); /** * If set overrides the find implementation. Server side only. */ private BeanFinder<T> beanFinder; /** * The table joins for this bean. Server side only. */ private ArrayList<DeployTableJoin> tableJoinList = new ArrayList<DeployTableJoin>(2); /** * Inheritance information. Server side only. */ private InheritInfo inheritInfo; private String name; private boolean processedRawSqlExtend; /** * Construct the BeanDescriptor. */ public DeployBeanDescriptor(Class<T> beanType) { this.beanType = beanType; } /** * Return true if this beanType is an abstract class. */ public boolean isAbstract() { return Modifier.isAbstract(beanType.getModifiers()); } public boolean isScalaObject() { Class<?>[] interfaces = beanType.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { String iname = interfaces[i].getName(); if (I_SCALAOBJECT.equals(iname)) { return true; } } return false; } public Collection<DRawSqlMeta> getRawSqlMeta() { if (!processedRawSqlExtend) { rawSqlProcessExtend(); processedRawSqlExtend = true; } return rawSqlMetas.values(); } /** * Process the "extend" attributes of raw SQL. Aka inherit the query and * column mapping. */ private void rawSqlProcessExtend() { for (DRawSqlMeta rawSqlMeta : rawSqlMetas.values()) { String extend = rawSqlMeta.getExtend(); if (extend != null) { DRawSqlMeta parentQuery = rawSqlMetas.get(extend); if (parentQuery == null) { throw new RuntimeException("parent query [" + extend + "] not found for sql-select " + rawSqlMeta.getName()); } rawSqlMeta.extend(parentQuery); } } } public DeployBeanTable createDeployBeanTable() { DeployBeanTable beanTable = new DeployBeanTable(getBeanType()); beanTable.setBaseTable(baseTable); beanTable.setIdProperties(propertiesId()); return beanTable; } /** * Check all the properties to see if they all have read and write methods * (required if using "subclassing" but not for "enhancement"). */ public boolean checkReadAndWriteMethods() { boolean missingMethods = false; for (DeployBeanProperty prop : propMap.values()) { if (!prop.isTransient()) { String m = ""; if (prop.getReadMethod() == null) { m += " missing readMethod "; } if (prop.getWriteMethod() == null) { m += " missing writeMethod "; } if (!"".equals(m)) { m += ". Should it be transient?"; String msg = "Bean property " + getFullName() + "." + prop.getName() + " has " + m; logger.error(msg); missingMethods = true; } } } return !missingMethods; } public void setEntityType(EntityType entityType) { this.entityType = entityType; } public boolean isEmbedded() { return EntityType.EMBEDDED.equals(entityType); } public boolean isBaseTableType() { EntityType et = getEntityType(); return EntityType.ORM.equals(et); } public EntityType getEntityType() { if (entityType == null) { entityType = EntityType.ORM; } return entityType; } public void add(DRawSqlMeta rawSqlMeta) { rawSqlMetas.put(rawSqlMeta.getName(), rawSqlMeta); if ("default".equals(rawSqlMeta.getName())) { setEntityType(EntityType.SQL); } } public void add(DeployNamedUpdate namedUpdate) { namedUpdates.put(namedUpdate.getName(), namedUpdate); } public void add(DeployNamedQuery namedQuery) { namedQueries.put(namedQuery.getName(), namedQuery); if ("default".equals(namedQuery.getName())) { setEntityType(EntityType.SQL); } } public Map<String, DeployNamedQuery> getNamedQueries() { return namedQueries; } public Map<String, DeployNamedUpdate> getNamedUpdates() { return namedUpdates; } public String[] getProperties() { return properties; } public void setProperties(String[] props) { this.properties = props; } public BeanPropertyInfo getBeanReflect() { return beanReflect; } /** * Return the class type this BeanDescriptor describes. */ public Class<T> getBeanType() { return beanType; } /** * Set the BeanReflect used to create new instances of an EntityBean. This * could use reflection or code generation to do this. */ public void setBeanReflect(BeanPropertyInfo beanReflect) { this.beanReflect = beanReflect; } /** * Returns the Inheritance mapping information. This will be null if this type * of bean is not involved in any ORM inheritance mapping. */ public InheritInfo getInheritInfo() { return inheritInfo; } /** * Set the ORM inheritance mapping information. */ public void setInheritInfo(InheritInfo inheritInfo) { this.inheritInfo = inheritInfo; } /** * Return the cache options. */ public CacheOptions getCacheOptions() { return cacheOptions; } public boolean isNaturalKeyProperty(String name) { return name.equals(cacheOptions.getNaturalKey()); } public DeployBeanPropertyAssocOne<?> getUnidirectional() { return unidirectional; } public void setUnidirectional(DeployBeanPropertyAssocOne<?> unidirectional) { this.unidirectional = unidirectional; } /** * Return the concurrency mode used for beans of this type. */ public ConcurrencyMode getConcurrencyMode() { return concurrencyMode; } /** * Set the concurrency mode used for beans of this type. */ public void setConcurrencyMode(ConcurrencyMode concurrencyMode) { this.concurrencyMode = concurrencyMode; } public boolean isUpdateChangesOnly() { return updateChangesOnly; } public void setUpdateChangesOnly(boolean updateChangesOnly) { this.updateChangesOnly = updateChangesOnly; } /** * Return the tables this bean is dependant on. This implies that if any of * these tables are modified then cached beans may be invalidated. */ public String[] getDependantTables() { return dependantTables; } /** * Add a compound unique constraint. */ public void addCompoundUniqueConstraint(CompoundUniqueContraint c) { if (compoundUniqueConstraints == null) { compoundUniqueConstraints = new ArrayList<CompoundUniqueContraint>(); } compoundUniqueConstraints.add(c); } /** * Return the compound unique constraints (can be null). */ public CompoundUniqueContraint[] getCompoundUniqueConstraints() { if (compoundUniqueConstraints == null) { return null; } else { return compoundUniqueConstraints.toArray(new CompoundUniqueContraint[compoundUniqueConstraints.size()]); } } /** * Set the tables this bean is dependant on. This implies that if any of these * tables are modified then cached beans may be invalidated. */ public void setDependantTables(String[] dependantTables) { this.dependantTables = dependantTables; } /** * Return the beanFinder. Usually null unless overriding the finder. */ public BeanFinder<T> getBeanFinder() { return beanFinder; } /** * Set the BeanFinder to use for beans of this type. This is set to override * the finding from the default. */ public void setBeanFinder(BeanFinder<T> beanFinder) { this.beanFinder = beanFinder; } /** * Return the BeanPersistController (could be a chain of them, 1 or null). */ public BeanPersistController getPersistController() { if (persistControllers.size() == 0) { return null; } else if (persistControllers.size() == 1) { return persistControllers.get(0); } else { return new ChainedBeanPersistController(persistControllers); } } /** * Return the BeanPersistListener (could be a chain of them, 1 or null). */ public BeanPersistListener getPersistListener() { if (persistListeners.size() == 0) { return null; } else if (persistListeners.size() == 1) { return persistListeners.get(0); } else { return new ChainedBeanPersistListener(persistListeners); } } public BeanQueryAdapter getQueryAdapter() { if (queryAdapters.size() == 0) { return null; } else if (queryAdapters.size() == 1) { return queryAdapters.get(0); } else { return new ChainedBeanQueryAdapter(queryAdapters); } } /** * Set the Controller. */ public void addPersistController(BeanPersistController controller) { persistControllers.add(controller); } public void addPersistListener(BeanPersistListener listener) { persistListeners.add(listener); } public void addQueryAdapter(BeanQueryAdapter queryAdapter) { queryAdapters.add(queryAdapter); } /** * Return true if this bean type should use IdGeneration. * <p> * If this is false and the Id is null it is assumed that a database auto * increment feature is being used to populate the id. * </p> */ public boolean isUseIdGenerator() { return idType == IdType.GENERATOR; } /** * Return the base table. Only properties mapped to the base table are by * default persisted. */ public String getBaseTable() { return baseTable; } /** * Return the base table with full structure. */ public TableName getBaseTableFull() { return baseTableFull; } /** * Set the base table. Only properties mapped to the base table are by default * persisted. */ public void setBaseTable(TableName baseTableFull) { this.baseTableFull = baseTableFull; this.baseTable = baseTableFull == null ? null : baseTableFull.getQualifiedName(); } public void sortProperties() { ArrayList<DeployBeanProperty> list = new ArrayList<DeployBeanProperty>(); list.addAll(propMap.values()); Collections.sort(list, PROP_ORDER); propMap = new LinkedHashMap<String, DeployBeanProperty>(list.size()); for (int i = 0; i < list.size(); i++) { addBeanProperty(list.get(i)); } } /** * Add a bean property. */ public DeployBeanProperty addBeanProperty(DeployBeanProperty prop) { return propMap.put(prop.getName(), prop); } /** * Get a BeanProperty by its name. */ public DeployBeanProperty getBeanProperty(String propName) { return propMap.get(propName); } /** * Return the bean class name this descriptor is used for. * <p> * If this BeanDescriptor is for a table then this returns the table name * instead. * </p> */ public String getFullName() { return beanType.getName(); } /** * Return the bean short name. */ public String getName() { return name; } /** * Set the bean shortName. */ public void setName(String name) { this.name = name; } /** * Return the identity generation type. */ public IdType getIdType() { return idType; } /** * Set the identity generation type. */ public void setIdType(IdType idType) { this.idType = idType; } /** * Return the DB sequence name (can be null). */ public String getSequenceName() { return sequenceName; } /** * Set the DB sequence name. */ public void setSequenceName(String sequenceName) { this.sequenceName = sequenceName; } /** * Return the SQL used to return the last inserted Id. * <p> * Used with Identity columns where getGeneratedKeys is not supported. * </p> */ public String getSelectLastInsertedId() { return selectLastInsertedId; } /** * Set the SQL used to return the last inserted Id. */ public void setSelectLastInsertedId(String selectLastInsertedId) { this.selectLastInsertedId = selectLastInsertedId; } /** * Return the name of the IdGenerator that should be used with this type of * bean. A null value could be used to specify the 'default' IdGenerator. */ public String getIdGeneratorName() { return idGeneratorName; } /** * Set the name of the IdGenerator that should be used with this type of bean. */ public void setIdGeneratorName(String idGeneratorName) { this.idGeneratorName = idGeneratorName; } /** * Return the actual IdGenerator for this bean type (can be null). */ public IdGenerator getIdGenerator() { return idGenerator; } /** * Set the actual IdGenerator for this bean type. */ public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; if (idGenerator != null && idGenerator.isDbSequence()) { setSequenceName(idGenerator.getName()); } } /** * Return the includes for getReference(). */ public String getLazyFetchIncludes() { return lazyFetchIncludes; } /** * Set includes to use for lazy loading by getReference(). Note queries also * build references and includes on the actual association are used for those * references. */ public void setLazyFetchIncludes(String lazyFetchIncludes) { if (lazyFetchIncludes != null && lazyFetchIncludes.length() > 0) { this.lazyFetchIncludes = lazyFetchIncludes; } } /** * Summary description. */ public String toString() { return getFullName(); } /** * Add a TableJoin to this type of bean. For Secondary table properties. */ public void addTableJoin(DeployTableJoin join) { tableJoinList.add(join); } public List<DeployTableJoin> getTableJoins() { return tableJoinList; } /** * Return a collection of all BeanProperty deployment information. */ public Collection<DeployBeanProperty> propertiesAll() { return propMap.values(); } /** * Return the defaultSelectClause using FetchType.LAZY and FetchType.EAGER. */ public String getDefaultSelectClause() { StringBuilder sb = new StringBuilder(); boolean hasLazyFetch = false; for (DeployBeanProperty prop : propMap.values()) { if (prop.isTransient()) { // ignore transient props etc } else if (prop instanceof DeployBeanPropertyAssocMany<?>) { // ignore the associated many properties } else { if (prop.isFetchEager()) { sb.append(prop.getName()).append(","); } else { hasLazyFetch = true; } } } if (!hasLazyFetch) { return null; } String selectClause = sb.toString(); return selectClause.substring(0, selectClause.length() - 1); } /** * Parse the include separating by comma or semicolon. */ public Set<String> parseDefaultSelectClause(String rawList) { if (rawList == null) { return null; } String[] res = rawList.split(","); LinkedHashSet<String> set = new LinkedHashSet<String>(res.length + 3); String temp = null; for (int i = 0; i < res.length; i++) { temp = res[i].trim(); if (temp.length() > 0) { set.add(temp); } } return Collections.unmodifiableSet(set); } /** * Return the Primary Key column assuming it is a single column (not * compound). This is for the purpose of defining a sequence name. */ public String getSinglePrimaryKeyColumn() { List<DeployBeanProperty> ids = propertiesId(); if (ids.size() == 1) { DeployBeanProperty p = ids.get(0); if (p instanceof DeployBeanPropertyAssoc<?>) { // its a compound primary key return null; } else { return p.getDbColumn(); } } return null; } /** * Return the BeanProperty that make up the unique id. * <p> * The order of these properties can be relied on to be consistent if the bean * itself doesn't change or the xml deployment order does not change. * </p> */ public List<DeployBeanProperty> propertiesId() { ArrayList<DeployBeanProperty> list = new ArrayList<DeployBeanProperty>(2); for (DeployBeanProperty prop : propMap.values()) { if (prop.isId()) { list.add(prop); } } return list; } public DeployBeanPropertyAssocOne<?> findJoinToTable(String tableName) { List<DeployBeanPropertyAssocOne<?>> assocOne = propertiesAssocOne(); for (DeployBeanPropertyAssocOne<?> prop : assocOne) { DeployTableJoin tableJoin = prop.getTableJoin(); if (tableJoin != null && tableJoin.getTable().equalsIgnoreCase(tableName)) { return prop; } } return null; } /** * Return an Iterator of BeanPropertyAssocOne that are not embedded. These are * effectively joined beans. For ManyToOne and OneToOne associations. */ public List<DeployBeanPropertyAssocOne<?>> propertiesAssocOne() { ArrayList<DeployBeanPropertyAssocOne<?>> list = new ArrayList<DeployBeanPropertyAssocOne<?>>(); for (DeployBeanProperty prop : propMap.values()) { if (prop instanceof DeployBeanPropertyAssocOne<?>) { if (!prop.isEmbedded()) { list.add((DeployBeanPropertyAssocOne<?>) prop); } } } return list; } /** * Return BeanPropertyAssocMany for this descriptor. */ public List<DeployBeanPropertyAssocMany<?>> propertiesAssocMany() { ArrayList<DeployBeanPropertyAssocMany<?>> list = new ArrayList<DeployBeanPropertyAssocMany<?>>(); for (DeployBeanProperty prop : propMap.values()) { if (prop instanceof DeployBeanPropertyAssocMany<?>) { list.add((DeployBeanPropertyAssocMany<?>) prop); } } return list; } /** * Returns 'Version' properties on this bean. These are 'Counter' or 'Update * Timestamp' type properties. Note version properties can also be on embedded * beans rather than on the bean itself. */ public List<DeployBeanProperty> propertiesVersion() { ArrayList<DeployBeanProperty> list = new ArrayList<DeployBeanProperty>(); for (DeployBeanProperty prop : propMap.values()) { if (prop instanceof DeployBeanPropertyAssoc<?> == false) { if (!prop.isId() && prop.isVersionColumn()) { list.add(prop); } } } return list; } /** * base properties without the unique id properties. */ public List<DeployBeanProperty> propertiesBase() { ArrayList<DeployBeanProperty> list = new ArrayList<DeployBeanProperty>(); for (DeployBeanProperty prop : propMap.values()) { if (prop instanceof DeployBeanPropertyAssoc<?> == false) { if (!prop.isId()) { list.add(prop); } } } return list; } /** * Check the mapping for class inheritance */ public void checkInheritanceMapping() { if (inheritInfo == null) { checkInheritance(getBeanType()); } } /** * Check valid mapping annotations on the class hierarchy. */ private void checkInheritance(Class<?> beanType) { Class<?> parent = beanType.getSuperclass(); if (parent == null || Object.class.equals(parent)) { // all good return; } if (parent.isAnnotationPresent(Entity.class)) { String msg = "Checking "+getBeanType()+" and found "+parent+" that has @Entity annotation rather than MappedSuperclass?"; throw new IllegalStateException(msg); } if (parent.isAnnotationPresent(MappedSuperclass.class)) { // continue checking checkInheritance(parent); } } }
27.447811
128
0.655626
f2944a980d4721c3fc2115f152befd21a99e8ccd
5,421
/* * * 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.wso2.andes.info.test; import junit.framework.TestCase; import org.wso2.andes.info.util.IniFileReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.Properties; /** * Test the Loading of the ini file reader by first writing * out a correct ini file. */ public class IniFileReaderTest extends TestCase { public void testLoad() { IniFileReader ifr = new IniFileReader(); File iniFile = null; try { iniFile = File.createTempFile("temp", "ini"); iniFile.deleteOnExit(); BufferedWriter writer = new BufferedWriter(new FileWriter(iniFile)); writer.write("# Global Comment1\n"); writer.write("globalprop1=globalval1\n"); writer.write("globalprop2=globalval2\n"); writer.write("\n"); writer.write("[Section1] # Comment on Section\n"); writer.write("key1=val1 # Comment on Value\n"); writer.write("key2=val2\n"); writer.write("\n"); writer.write("#Section2 Comment\n"); writer.write("[Section2]\n"); writer.write("key3=val3\n"); writer.write("key4=val4\n"); writer.write("key5=val5\n"); writer.write("\n"); writer.write("[Section3]\n"); writer.write("key6=val6\n"); writer.write("key7=val7\n"); writer.write("\n"); writer.close(); } catch (IOException e) { e.printStackTrace(); fail("Unable to create temporary File"); } ifr.load(iniFile.getAbsolutePath()); Map<String, Properties> sections = ifr.getSections(); assertNotNull("Sections not null", sections); assertEquals("Have 4 sections", sections.keySet().size(), 4); assertTrue("Get globalprop1", sections.get("").getProperty("globalprop1").equals("globalval1")); assertTrue("Get globalprop2", sections.get("").getProperty("globalprop2").equals("globalval2")); assertNotNull("Section1 not null", sections.get("Section1")); assertEquals("Section1 has 2 properties", sections.get("Section1").size(), 2); assertTrue("Section1 key1 has val1", sections.get("Section1").getProperty("key1").equals("val1")); assertTrue("Section1 key2 has val2", sections.get("Section1").getProperty("key2").equals("val2")); assertEquals("Section2 has 3 properties", sections.get("Section2").size(), 3); assertTrue("Section2 key3 has val3", sections.get("Section2").getProperty("key3").equals("val3")); assertTrue("Section2 key4 has val4", sections.get("Section2").getProperty("key4").equals("val4")); assertTrue("Section2 key5 has val5", sections.get("Section2").getProperty("key5").equals("val5")); assertEquals("Section3 has 2 properties", sections.get("Section3").size(), 2); assertTrue("Section3 key6 has val6", sections.get("Section3").getProperty("key6").equals("val6")); assertTrue("Section3 key7 has val7", sections.get("Section3").getProperty("key7").equals("val7")); } /** * Test to ensure that the loading of a file with an unclosed section header * fails to parse. * * Section needs to be fully enclosed in square brackets '[<name>]' */ public void testIncompleteSection1Load() { IniFileReader ifr = new IniFileReader(); File iniFile = null; try { iniFile = File.createTempFile(getName(), "ini"); iniFile.deleteOnExit(); BufferedWriter writer = new BufferedWriter(new FileWriter(iniFile)); writer.write("# Global Comment1\n"); writer.write("globalprop1=globalval1\n"); writer.write("globalprop2=globalval2\n"); writer.write("\n"); writer.write("[Section1\n"); // Note '[Section1' not complete writer.write("key1=val1\n"); writer.write("key2=val2\n"); writer.write("\n"); writer.close(); } catch (IOException e) { e.printStackTrace(); fail("Unable to create temporary File"); } try { ifr.load(iniFile.getAbsolutePath()); fail("File should fail to parse"); } catch (IllegalArgumentException iae) { assertEquals("Incorrect Exception", "Section1 is not closed", iae.getMessage()); } } }
39.569343
106
0.61889
9d9775389e8c2b2146c1587faeca5cfe3cc2d647
667
package uk.gov.dvsa.motr.web.analytics; public enum DataLayerMessageId { TRADE_API_CLIENT_EXCEPTION, VRM_VALIDATION_ERROR, CHANNEL_SELECTION_VALIDATION_ERROR, EMAIL_VALIDATION_ERROR, PHONE_NUMBER_VALIDATION_ERROR, CODE_ALREADY_RESENT, CODE_INCORRECT_3_TIMES, INVALID_CONFIRMATION_CODE_MESSAGE, CONFIRMATION_CODE_DOESNT_EXIST_MESSAGE, VEHICLE_NOT_FOUND, VEHICLE_MOT_TEST_EXPIRED, VEHICLE_MOT_TEST_DUE, VEHICLE_ANNUAL_TEST_EXPIRED, VEHICLE_ANNUAL_TEST_DUE, ANNUAL_TEST_DATE_UNKNOWN, TRAILER_NOT_FOUND, TRAILER_ANNUAL_TEST_DUE, TRAILER_ANNUAL_TEST_EXPIRED, TRAILER_WITHOUT_FIRST_ANNUAL_TEST }
27.791667
43
0.806597
945b2b6449b46ee797bd4c07811a79c09d729e7c
1,903
/******************************************************************************* * Copyright (c) 2009, 2019 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.data; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; /** * Additional data input methods for compact storage of data structures. * * @see CompactDataOutput */ public class CompactDataInput extends DataInputStream { /** * Creates a new {@link CompactDataInput} that uses the specified underlying * input stream. * * @param in * underlying input stream */ public CompactDataInput(final InputStream in) { super(in); } /** * Reads a variable length representation of an integer value. * * @return read value * @throws IOException * if thrown by the underlying stream */ public int readVarInt() throws IOException { final int value = 0xFF & readByte(); if ((value & 0x80) == 0) { return value; } return (value & 0x7F) | (readVarInt() << 7); } /** * Reads a boolean array. * * @return boolean array * @throws IOException * if thrown by the underlying stream */ public boolean[] readBooleanArray() throws IOException { final boolean[] value = new boolean[readVarInt()]; int buffer = 0; for (int i = 0; i < value.length; i++) { if ((i % 8) == 0) { buffer = readByte(); } value[i] = (buffer & 0x01) != 0; buffer >>>= 1; } return value; } }
26.430556
81
0.603783
147f6864b18cb1718a8a6587346698c294a45a5d
332
package messages; import java.io.Serializable; public class MessageExample extends Message implements Serializable { private String data = null; public MessageExample() { super(MSG_TYPE.MSG_EXAMPLE); } public String getData() { return data; } public void setData(String data) { this.data = data; } }
16.6
69
0.701807
197b0e006d079b5f4c3ff5a2c6c99473d6dbd4b9
1,326
package com.larksuite.oapi.core.card.mode; public class Header { public static final String X_LARK_REQUEST_TIMESTAMP = "X-Lark-Request-Timestamp"; public static final String X_LARK_REQUEST_NONCE = "X-Lark-Request-Nonce"; public static final String X_LARK_SIGNATURE = "X-Lark-Signature"; public static final String X_REFRESH_TOKEN = "X-Refresh-Token"; private final String timestamp; private final String nonce; private final String signature; private final String refreshToken; public Header(String timestamp, String nonce, String signature, String refreshToken) { this.timestamp = timestamp; this.nonce = nonce; this.signature = signature; this.refreshToken = refreshToken; } public String getTimestamp() { return timestamp; } public String getNonce() { return nonce; } public String getSignature() { return signature; } public String getRefreshToken() { return refreshToken; } @Override public String toString() { return "{" + "timestamp='" + timestamp + '\'' + ", nonce='" + nonce + '\'' + ", signature='" + signature + '\'' + ", refreshToken='" + refreshToken + '\'' + '}'; } }
28.212766
90
0.607843
8a6f0d7a1c2c93e7c30d03957eff4a11165ba471
572
package org.abigballofmud.datax.plugin.writer.hdfspluswriter.constants; /** * <p>description</p> * * @author abigballofmud 2019-9-25 14:01:31 */ public final class Constant { private Constant() { throw new IllegalStateException("constant class!"); } public static final String DEFAULT_ENCODING = "UTF-8"; public static final String DEFAULT_NULL_FORMAT = "\\N"; public static final String DOUBLE_QUOTATION = "\""; public static final String TMP_FILE_PATH = "%s__%s%s"; public static final String FULL_FILE_PATH = "%s%s%s__%s"; }
27.238095
71
0.695804
bf63fa41a45eb3131649c544cfdd1effd3385b08
1,554
package resnyx.methods.message; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import resnyx.Answer; import resnyx.ReplyMethod; import resnyx.Types; import resnyx.model.InputMedia; import resnyx.model.InputMediaPhoto; import resnyx.model.InputMediaVideo; import resnyx.model.Message; /** * Use this method to send a group of photos or videos as an album. * On success, an array of the sent Messages is returned. */ @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public final class SendMediaGroup extends ReplyMethod<List<Message>> { public static final String METHOD = "sendMediaGroup"; /** * Unique identifier for the target chat or username of the * target channel (in the format @channelusername) */ @JsonProperty("chat_id") private Long chatId; /** * A JSON-serialized array describing photos and videos to be sent, must include 2โ€“10 items. * Array of {@link InputMediaPhoto} and {@link InputMediaVideo} */ private List<InputMedia> media; public SendMediaGroup(String token, Long chatId, List<InputMedia> media) { super(token); this.chatId = chatId; this.media = media; } @Override protected String method() { return METHOD; } @Override protected TypeReference<Answer<List<Message>>> type() { return Types.ARR_OF_MESSAGES; } }
26.793103
96
0.71879
669d254df63f5e55661f88c45f449b0b4184c9b6
128
package com.iamcodder.otelrezervasyon.Interface; public interface RoomTypeInterface { void buttonNumber(int position); }
16
48
0.796875
e9c772e71099c0a821b8fba4903a1b19fae7b868
1,297
package uk.ac.ebi.pride.toolsuite.gui.action.impl; import uk.ac.ebi.pride.toolsuite.gui.PrideInspector; import uk.ac.ebi.pride.toolsuite.gui.PrideInspectorContext; import uk.ac.ebi.pride.toolsuite.gui.action.PrideAction; import javax.help.CSH; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Open Help manuel. * * User: rwang * Date: 18-Aug-2010 * Time: 11:41:13 */ public class OpenHelpAction extends PrideAction { private String helpIndex; public OpenHelpAction(String name, Icon icon, String helpIndex) { super(name, icon); this.helpIndex = helpIndex; } public OpenHelpAction(String name, Icon icon, String helpIndex, int acceleratorKey) { super(name, icon); setAccelerator(acceleratorKey); this.helpIndex = helpIndex; } @Override public void actionPerformed(ActionEvent e) { PrideInspectorContext context = (PrideInspectorContext)PrideInspector.getInstance().getDesktopContext(); CSH.setHelpIDString(PrideInspector.getInstance().getMainComponent(), helpIndex); ActionListener listener = new CSH.DisplayHelpFromSource(context.getMainHelpBroker()); listener.actionPerformed(e); } }
30.162791
113
0.70239
93b2311cf610067f333a9197cdedcab1e1696831
811
package fr.imie.training.cdi13.dav.thread.exo1; import java.util.ArrayList; import java.util.List; public class Exo1 { public static void main(String[] args) { List<Counter> terminateList = new ArrayList<>(); Thread t1 = new Counter("Compteur 1", 20, terminateList); Thread t2 = new Counter("Compteur 2", 10, terminateList); Thread t3 = new Counter("Compteur 3", 15, terminateList); t1.start(); t2.start(); t3.start(); while (t1.isAlive() || t2.isAlive() || t3.isAlive()) { try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Ordre des FINISH"); for (Counter counter : terminateList) { System.out.println(counter.getNom()); } } }
23.171429
60
0.633785
149a904edc21783012b78ad23a1d5646fb8d208e
557
package com.epi; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class SimpleWebServer { // @include public static class SingleThreadWebServer { public static final int PORT = 8080; public static void main(String[] args) throws IOException { ServerSocket serversock = new ServerSocket(PORT); for (;;) { Socket sock = serversock.accept(); processReq(sock); } } // @exclude static void processReq(Socket sock) { return; } // @include } // @exclude }
23.208333
63
0.658887
7030a1d4debeb8fa410b9474bbfe106d7a798d31
1,267
package stark.android.appbase.base; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; /** * Created by jihongwen on 15/12/11. */ public abstract class BaseRelativeLayout<T> extends RelativeLayout { protected Context mContext; protected String referer; public BaseRelativeLayout(Context context) { super(context); init(context); } public BaseRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public BaseRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { mContext = context; View.inflate(context, getViewLayout(), this); if (isInEditMode()) { return; } createView(); } protected int dpToPx(int dps) { return Math.round(getResources().getDisplayMetrics().density * dps); } public abstract int getViewLayout(); public abstract void createView(); public abstract void bindView(T t, String referer); public abstract void unbind(Context context); }
23.036364
86
0.670087
af9ffc25986655b50ac745f7616fe34f2e3caae3
1,468
package org.abimon.mods.minecraft.minegate.reactor; import org.abimon.mods.minecraft.minegate.MineGate; import org.abimon.mods.minecraft.minegate.tileentity.TileEntityNaquadahReactor; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; public class NaquadahFuelCell extends NaquadahReactorComponent { float naquadahContent = 3; public NaquadahFuelCell(TileEntityNaquadahReactor reactor, float naquadahContent) { super(reactor); this.naquadahContent = naquadahContent; } @Override public float getPowerModifier() { return 1; } @Override public float getFuelValue() { return naquadahContent; } @Override public float useFuel(float fuel) { if(naquadahContent >= fuel){ naquadahContent -= fuel; fuel = 0; } else{ fuel -= naquadahContent; naquadahContent = 0; } return fuel; } public ResourceLocation getResourceLocation(){ return new ResourceLocation(MineGate.MODID + ":textures/reactor/naquadah_cell_" + (naquadahContent > 2.9 ? "full" : naquadahContent >= 2 ? "mostly_full" : naquadahContent >= 1.25 ? "half_full" : naquadahContent > 0.2 ? "mostly_empty" : "empty") + ".png"); } @Override public void onTick() { } @Override public ItemStack getItemStackForComponent() { return naquadahContent > 0 ? new ItemStack(MineGate.naquadahFuelCell, 1, (int) (Short.MAX_VALUE - (naquadahContent * 10922))) : null; } @Override public float getFuelConsumption() { return 1; } }
24.065574
257
0.739101
10956648c9d7f27b270e06adcb5fc5f563acdc0b
2,364
import complex.*; public class TestComplex { public TestComplex() { Complex z1,z2,z3,z4,z5; z1=new Complex(1.0,1.0); z2=new Complex(2.0,-3.0); z3=new Complex(); z4=new Complex(-5.3); z5=new Complex(0.0,3.6); System.out.println("z1="+z1+" modulus(z1)="+z1.modulus()+ " argument(z1)="+z1.argument()+ " conjugate(z1)="+z1.conjugate()+ "\nrealPart(z1)="+z1.getRealPart()+ " imaginaryPart(z1)="+z1.getImaginaryPart()); System.out.println("\nz2="+z2+" modulus(z2)="+z2.modulus()+ " argument(z2)="+z2.argument()+ " conjugate(z2)="+z2.conjugate()+ "\nrealPart(z2)="+z2.getRealPart()+ " imaginaryPart(z2)="+z2.getImaginaryPart()); System.out.println("\nz3="+z3+" modulus(z2)="+z3.modulus()+ " argument(z3)="+z3.argument()+ " conjugate(z3)="+z3.conjugate()+ "\nrealPart(z3)="+z3.getRealPart()+ " imaginaryPart(z3)="+z3.getImaginaryPart()); System.out.println("\nz4="+z4+" modulus(z4)="+z4.modulus()+ " argument(z4)="+z4.argument()+ " conjugate(z4)="+z4.conjugate()+ "\nrealPart(z4)="+z4.getRealPart()+ " imaginaryPart(z4)="+z4.getImaginaryPart()); System.out.println("\nz5="+z5+" modulus(z5)="+z5.modulus()+ " argument(z5)="+z5.argument()+ " conjugate(z5)="+z5.conjugate()+ "\nrealPart(z5)="+z5.getRealPart()+ " imaginaryPart(z5)="+z5.getImaginaryPart()); System.out.println(""+z1+" * "+z2+"="+z1.multiply(z2)); System.out.println(""+z1+" / "+z2+"="+z1.divide(z2)); System.out.println(""+z1+" + "+z2+"="+z1.add(z2)); System.out.println(""+z1+" - "+z2+"="+z1.subtract(z2)); try { z2=new Complex(0.0); System.out.println(""+z1+"/"+z2+"="+z1.divide(z2)); } catch(ComplexDivideByZeroRuntimeException e) { System.out.println("Attempt to divide "+z1+" by zero."); e.printStackTrace(); } System.out.println(""+z1+"/"+z2+"="+z1.divide(z2)); } public static void main(String [] args) { new TestComplex(); } }
45.461538
68
0.494924
3073546afac9076b06a3c9368939887fa3368714
3,044
package com.gzlk.android.isp.holder.archive; import android.graphics.Color; import android.view.View; import com.gzlk.android.isp.R; import com.gzlk.android.isp.fragment.base.BaseFragment; import com.gzlk.android.isp.fragment.archive.ArchiveDetailsFragment; import com.gzlk.android.isp.helper.ClipboardHelper; import com.gzlk.android.isp.helper.StringHelper; import com.gzlk.android.isp.helper.TooltipHelper; import com.gzlk.android.isp.holder.BaseViewHolder; import com.gzlk.android.isp.lib.view.ExpandableTextView; import com.gzlk.android.isp.model.archive.Comment; import com.hlk.hlklib.lib.emoji.EmojiUtility; import com.hlk.hlklib.lib.inject.ViewId; import com.hlk.hlklib.lib.inject.ViewUtility; import com.hlk.hlklib.lib.view.CorneredView; /** * <b>ๅŠŸ่ƒฝๆ่ฟฐ๏ผš</b>่ฏ„่ฎบViewHolder<br /> * <b>ๅˆ›ๅปบไฝœ่€…๏ผš</b>Hsiang Leekwok <br /> * <b>ๅˆ›ๅปบๆ—ถ้—ด๏ผš</b>2017/05/01 22:22 <br /> * <b>ไฝœ่€…้‚ฎ็ฎฑ๏ผš</b>[email protected] <br /> * <b>ๆœ€ๆ–ฐ็‰ˆๆœฌ๏ผš</b>Version: 1.0.0 <br /> * <b>ไฟฎๆ”นๆ—ถ้—ด๏ผš</b>2017/05/01 22:22 <br /> * <b>ไฟฎๆ”นไบบๅ‘˜๏ผš</b><br /> * <b>ไฟฎๆ”นๅค‡ๆณจ๏ผš</b><br /> */ public class ArchiveCommentViewHolder extends BaseViewHolder { @ViewId(R.id.ui_holder_view_document_comment_container) private CorneredView container; @ViewId(R.id.ui_holder_view_document_comment_content) private ExpandableTextView contentTextView; public ArchiveCommentViewHolder(final View itemView, final BaseFragment fragment) { super(itemView, fragment); ViewUtility.bind(this, itemView); container.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { container.setNormalColor(getColor(R.color.textColorHintLightLight)); fragment.showTooltip(v, R.id.ui_tooltip_document_comment, false, TooltipHelper.TYPE_CENTER, onClickListener); return true; } }); } private View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { container.setNormalColor(Color.WHITE); log("clicked: " + v); switch (v.getId()) { case R.id.ui_tooltip_menu_document_comment_copy: Comment comment = ((ArchiveDetailsFragment) fragment()).getFromPosition(getAdapterPosition()); if (null != comment) { ClipboardHelper.copyToClipboard(v.getContext(), comment.getContent()); } break; case R.id.ui_tooltip_menu_document_comment_delete: // ๅˆ ้™คๆœฌๆก่ฏ„่ฎบ ((ArchiveDetailsFragment) fragment()).deleteComment(getAdapterPosition()); break; } } }; public void showContent(Comment comment) { String content = StringHelper.getString(R.string.ui_text_document_comment_content, comment.getUserName(), comment.getContent()); contentTextView.setText(EmojiUtility.getEmojiString(itemView.getContext(), content, true)); } }
40.052632
136
0.671156
4544d3cb91991ad060c1a8d0c368078feae0d963
1,237
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class P01PermutationsWithoutRepetitionSwap { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] values = reader.readLine().split(" "); permute(0, values); } private static void permute(int index, String[] elements) { if (index == elements.length) { print(elements); return; } permute(index + 1, elements); for (int i = index + 1; i < elements.length; i++) { swap(i, index, elements); permute(index + 1, elements); swap(i, index, elements); } } private static void swap(int i, int index, String[] values) { String temp = values[i]; values[i] = values[index]; values[index] = temp; } private static void print(String[] values) { for (int i = 0; i < values.length; i++) { System.out.print(values[i]); if(i!= values.length-1){ System.out.print(" "); } } System.out.println(); } }
26.891304
85
0.560226
34a98c15119212bc9c9062433773ed5b5da1f999
5,520
/* * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.awt.Font; import java.awt.FontFormatException; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Paths; /** * @test * @key headful * @bug 6522586 * @summary Enforce limits on font creation * @run main/othervm -Djava.security.manager=allow BigFont 1 A.ttf * @run main/othervm -Djava.security.manager=allow BigFont 2 A.ttf */ public class BigFont { static private class SizedInputStream extends InputStream { int size; int cnt = 0; SizedInputStream(int size) { this.size = size; } public int read() { if (cnt < size) { cnt++; return 0; } else { return -1; } } public int getCurrentSize() { return cnt; } } static String id; static String fileName; public static void main(final String[] args) { id = args[0]; fileName = args[1]; System.out.println("Applet " + id + " "+ Thread.currentThread().getThreadGroup()); if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } // Larger than size for a single font. int fontSize = 64 * 1000 * 1000; SizedInputStream sis = new SizedInputStream(fontSize); try { Font font = Font.createFont(Font.TRUETYPE_FONT, sis); } catch (Throwable t) { t.printStackTrace(); if (t instanceof FontFormatException || fontSize <= sis.getCurrentSize()) { System.out.println(sis.getCurrentSize()); System.out.println(t); throw new RuntimeException("Allowed file to be too large."); } } // The following part of the test was verified manually but // is impractical to enable because it requires a fairly large // valid font to be part of the test, and we can't easily include // that, nor dependably reference one from the applet environment. /* if (fileName == null) { return; } int size = getFileSize(fileName); if (size == 0) { return; } int fontCnt = 1000 * 1000 * 1000 / size; loadMany(size, fontCnt, fileName); System.gc(); System.gc(); fontCnt = fontCnt / 2; System.out.println("Applet " + id + " load more."); loadMany(size, fontCnt, fileName); */ System.out.println("Applet " + id + " finished."); } int getFileSize(String fileName) { try { String path = Paths.get(System.getProperty("test.src", "."), fileName).toAbsolutePath().normalize() .toString(); URL url = new URL(path); InputStream inStream = url.openStream(); BufferedInputStream fontStream = new BufferedInputStream(inStream); int size = 0; while (fontStream.read() != -1) { size++; } fontStream.close(); return size; } catch (IOException e) { return 0; } } void loadMany(int oneFont, int fontCnt, String fileName) { System.out.println("fontcnt= " + fontCnt); Font[] fonts = new Font[fontCnt]; int totalSize = 0; boolean gotException = false; for (int i=0; i<fontCnt; i++) { try { String path = Paths.get(System.getProperty("test.src", "."), fileName).toAbsolutePath().normalize() .toString(); URL url = new URL(path); InputStream inStream = url.openStream(); BufferedInputStream fontStream = new BufferedInputStream(inStream); fonts[i] = Font.createFont(Font.TRUETYPE_FONT, fontStream); totalSize += oneFont; fontStream.close(); } catch (Throwable t) { gotException = true; System.out.println("Applet " + id + " " + t); } } if (!gotException) { throw new RuntimeException("No expected exception"); } } }
34.285714
79
0.565036
dbc93b6064e4d824fa0a3ae7e262c7a40185ba33
453
package net.unit8.waitt.mojo.component; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.classworlds.realm.ClassRealm; /** * * @author kawasima */ public interface ArtifactResolver { ClassRealm resolve(Artifact artifact, ClassRealm parent); void setProject(MavenProject project); void setSession(MavenSession session); }
26.647059
61
0.790287
856f65ab1d5330b684cfb2fee2128c35edccf220
5,285
package bugger.dataAccessInterface.SQLDataAccess.dao; import bugger.dataAccessInterface.DataProxy; import bugger.dataAccessInterface.SQLDataAccess.SQL_Connector; import bugger.dataAccessInterface.SQLDataAccess.SQL_DataAccess; import bugger.dataAccessInterface.dao.IpermissionAccess; import bugger.dataModel.serverModel.Permission; import bugger.dataModel.serverModel.User; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class SQL_PermissionAccess extends SQL_DAO<Permission> implements IpermissionAccess { @Override public boolean CreatePermission(Permission permission) { boolean returnValue = false; if(!GetPermissionExists(permission.permissionID)) { returnValue = InsertPermissionIntoTable(permission); } return (returnValue); } private boolean InsertPermissionIntoTable(Permission permission) { boolean returnValue = false; try { Connection connect = SQL_Connector.GetDatabaseConnection(); Statement statement = connect.createStatement(); statement.executeUpdate("INSERT INTO Permission(permissionID,permissionName,discription) VALUES ('" + permission.permissionID + "','" + permission.permissionName + "','" + permission.discription + "')"); connect.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return(returnValue); } @Override public boolean GetPermissionExists(String permissionID) { return (GetByParameter(permissionID,"permissionID") != null); } @Override public boolean AddPermissionToUser(String permissionID,String userID) { boolean returnValue = false; //System.out.println(userID + "/" + permissionID); //System.out.println("Valid UserID and PermissionID: " + GetPermissionExists(permissionID) + "<- | ->" + DataProxy.GetUserExistsByID(userID)); if(GetPermissionExists(permissionID) && DataProxy.GetUserExistsByID(userID)) { try { Connection connect = SQL_Connector.GetDatabaseConnection(); Statement statement = connect.createStatement(); statement.executeUpdate("INSERT INTO " + SQL_DataAccess.table_user_permission + "(" + Permission.param_permissionID + "," + User.param_userID + ") VALUES ('" + permissionID + "','" + userID + "')"); connect.close(); returnValue = true; } catch (Exception e) { System.out.println(e.getMessage()); } } return (returnValue); } @Override public Permission GetByParameter(String query, String parameter) { return(GetByParameter(query,parameter,SQL_DataAccess.table_permission)); } @Override public List<Permission> GetUserPermissionList(String userID) { List<Permission> returnValue = new ArrayList<>(); try { Connection connect = SQL_Connector.GetDatabaseConnection(); Statement statement = connect.createStatement(); //Get the permissions ResultSet result = statement.executeQuery("SELECT * FROM " + SQL_DataAccess.table_user_permission + " LEFT JOIN " + SQL_DataAccess.table_permission + " ON " + SQL_DataAccess.table_user_permission + "." + Permission.param_permissionID + " = " + SQL_DataAccess.table_permission + "." + Permission.param_permissionID + " WHERE " + User.param_userID + " = '" + userID + "'"); while(result.next()) { String permissionID = result.getString(Permission.param_permissionID); String permissionName = result.getString(Permission.param_permissionName); String discription = result.getString(Permission.param_discription); if(permissionID != null && permissionName != null && discription != null) { returnValue.add(new Permission(permissionID,permissionName,discription)); } } connect.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } return returnValue; } public boolean CheckForValidID(String id) { boolean returnValue = false; try { Connection connect = SQL_DataAccess.GetDatabaseConnection(); Statement statement = connect.createStatement(); ResultSet result = statement.executeQuery("SELECT * FROM UserPermission WHERE " + Permission.param_permissionID + " = '" + id + "'" ); //Check that we have a result - if we do, then the id is taken returnValue = !result.next(); connect.close(); } catch (Exception e) { System.out.println("Cannot find user! Exception: " + e.getMessage()); e.printStackTrace(); } return (returnValue); } @Override protected Permission ParseSQLDataSet(ResultSet resultSet) throws SQLException { Permission returnValue = null; //Check that we have a result if(resultSet.next()) { //If we find the result, get it put together String permissionID = resultSet.getString(Permission.param_permissionID); String permissionName = resultSet.getString(Permission.param_permissionName); String discription = resultSet.getString(Permission.param_discription); if(permissionID != null && permissionName != null && discription != null) { returnValue = new Permission(permissionID,permissionName,discription); } } return returnValue; } }
28.722826
144
0.714853
a78ad1355442cfe19c35a550e509e4331b17deea
258
package dev.sgora.mesheditor.ui; import javafx.scene.control.Label; public class CopyableLabel extends Label { public CopyableLabel() { } public CopyableLabel(CopyableLabel label) { setFont(label.getFont()); setTextFill(label.getTextFill()); } }
17.2
44
0.751938
3da9e49bc66f068f74442ba100ad87ca0d3735ee
999
package com.airxiechao.clusterkeeper.service; import com.airxiechao.clusterkeeper.repository.DataStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * ่Š‚็‚นๅ†…่ฟ่กŒ็š„ๅบ”็”จ็จ‹ๅบ็›ธๅ…ณๆ–นๆณ• */ @Service public class AppService { private static final Logger logger = LoggerFactory.getLogger(AppService.class); @Autowired private DataStore dataStore; /** * ่ฟ”ๅ›žๆ˜ฏๅฆๅฏ็”จ * @return */ public boolean getAvailable(){ /** * TODO๏ผšๆทปๅŠ ๆฃ€ๆŸฅไธป่Š‚็‚นๅŠŸ่ƒฝๆ˜ฏๅฆๅœจ่ฟ่กŒ็š„ไปฃ็  */ return true; } /** * ่ฟ”ๅ›žๆ˜ฏๅฆ่‡ณๅฐ‘ๆœ‰ไธ€ไธชไธป่Š‚็‚นๆœๅŠกๅฏ็”จ * @return */ public boolean isSomeoneOfMasterAvailable(){ /** * TODO๏ผšๆทปๅŠ ๆฃ€ๆŸฅๆ˜ฏๅฆๆœ‰ไธป่Š‚็‚นๆŸไบ›ๅŠŸ่ƒฝๅœจ่ฟ่กŒ็š„ไปฃ็  */ return false; } /** * ่ฎพ็ฝฎๆ˜ฏๅฆๅฏ็”จ * @param available */ public void setAvailable(boolean available){ /** * TODO๏ผšๆทปๅŠ ๅฏๅŠจๆˆ–ๅœๆญขไธป่Š‚็‚นๅŠŸ่ƒฝ็š„ไปฃ็  */ } }
18.163636
83
0.618619
ef7124df12d22f758f0dfc5d80ab0dfdc5a1c94d
3,762
package sonar.logistics.network.packets; import io.netty.buffer.ByteBuf; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.Constants; import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import sonar.core.SonarCore; import sonar.core.helpers.NBTHelper; import sonar.core.helpers.NBTHelper.SyncType; import sonar.logistics.api.core.tiles.displays.info.InfoUUID; import sonar.logistics.api.core.tiles.readers.ClientLocalProvider; import sonar.logistics.base.ClientInfoHandler; import java.util.ArrayList; import java.util.List; import java.util.Map; public class PacketLocalProviders implements IMessage { public List<ClientLocalProvider> viewables; public int screenIdentity; public PacketLocalProviders() {} public PacketLocalProviders(List<ClientLocalProvider> viewables, int screenIdentity) { this.viewables = viewables; this.screenIdentity = screenIdentity; } @Override public void fromBytes(ByteBuf buf) { screenIdentity = buf.readInt(); NBTTagCompound tag = ByteBufUtils.readTag(buf); viewables = new ArrayList<>(); if (tag.hasKey("monitors")) { NBTTagList tagList = tag.getTagList("monitors", Constants.NBT.TAG_COMPOUND); for (int i = 0; i < tagList.tagCount(); i++) { viewables.add(NBTHelper.instanceNBTSyncable(ClientLocalProvider.class, tagList.getCompoundTagAt(i))); } } } @Override public void toBytes(ByteBuf buf) { buf.writeInt(screenIdentity); NBTTagCompound tag = new NBTTagCompound(); NBTTagList tagList = new NBTTagList(); viewables.forEach(emitter -> tagList.appendTag(emitter.writeData(new NBTTagCompound(), SyncType.SAVE))); if (!tagList.hasNoTags()) { tag.setTag("monitors", tagList); } ByteBufUtils.writeTag(buf, tag); } public static class Handler implements IMessageHandler<PacketLocalProviders, IMessage> { @Override public IMessage onMessage(PacketLocalProviders message, MessageContext ctx) { if (ctx.side == Side.CLIENT) { SonarCore.proxy.getThreadListener(ctx.side).addScheduledTask(() -> { Map<Integer, List<ClientLocalProvider>> monitors = ClientInfoHandler.instance().clientLogicMonitors; if (monitors.get(message.screenIdentity) == null) { monitors.put(message.screenIdentity, message.viewables); } else { monitors.get(message.screenIdentity).clear(); monitors.get(message.screenIdentity).addAll(message.viewables); } List<Object> cache = new ArrayList<>(); for (ClientLocalProvider clientMonitor : message.viewables) { /* ILogicListenable monitor = clientMonitor.getViewable(); if (monitor != null && monitor instanceof IInfoProvider) { int hashCode = monitor.getIdentity(); cache.add(monitor); for (int i = 0; i < ((IInfoProvider) monitor).getMaxInfo(); i++) { cache.add(new InfoUUID(hashCode, i)); } } */ int hashCode = clientMonitor.identity.getObject(); cache.add(clientMonitor); for (int i = 0; i < 4; i++) { cache.add(new InfoUUID(hashCode, i)); } } Map<Integer, List<Object>> sortedMonitors = ClientInfoHandler.instance().sortedLogicMonitors; if (sortedMonitors.get(message.screenIdentity) == null) { sortedMonitors.put(message.screenIdentity, cache); } else { sortedMonitors.get(message.screenIdentity).clear(); sortedMonitors.get(message.screenIdentity).addAll(cache); } }); } return null; } } }
34.833333
106
0.729931
944bba02360603a7390762b7c457ca579c719544
17,208
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.storage.queue; import com.azure.core.credentials.TokenCredential; import com.azure.core.http.HttpClient; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.policy.AddDatePolicy; import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLoggingPolicy; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.http.policy.RequestIdPolicy; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.implementation.http.policy.spi.HttpPolicyProviders; import com.azure.core.implementation.util.ImplUtils; import com.azure.core.util.configuration.Configuration; import com.azure.core.util.configuration.ConfigurationManager; import com.azure.core.util.logging.ClientLogger; import com.azure.storage.common.Utility; import com.azure.storage.common.credentials.SASTokenCredential; import com.azure.storage.common.credentials.SharedKeyCredential; import com.azure.storage.common.policy.SASTokenCredentialPolicy; import com.azure.storage.common.policy.SharedKeyCredentialPolicy; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; /** * This class provides a fluent builder API to help aid the configuration and instantiation of the {@link QueueClient QueueClients} * and {@link QueueAsyncClient QueueAsyncClients}, calling {@link QueueClientBuilder#buildClient() buildClient} constructs an * instance of QueueClient and calling {@link QueueClientBuilder#buildAsyncClient() buildAsyncClient} constructs an instance of * QueueAsyncClient. * * <p>The client needs the endpoint of the Azure Storage Queue service, name of the queue, and authorization credentials. * {@link QueueClientBuilder#endpoint(String) endpoint} gives the builder the endpoint and may give the builder the * {@link QueueClientBuilder#queueName(String) queueName} and a {@link SASTokenCredential} that authorizes the client.</p> * * <p><strong>Instantiating a synchronous Queue Client with SAS token</strong></p> * {@codesnippet com.azure.storage.queue.queueClient.instantiation.sastoken} * * <p><strong>Instantiating an Asynchronous Queue Client with SAS token</strong></p> * {@codesnippet com.azure.storage.queue.queueAsyncClient.instantiation.sastoken} * * <p>If the {@code endpoint} doesn't contain the queue name or {@code SASTokenCredential} they may be set using * {@link QueueClientBuilder#queueName(String) queueName} and {@link QueueClientBuilder#credential(SASTokenCredential) credential} * together with endpoint..</p> * * <p><strong>Instantiating a synchronous Queue Client with credential</strong></p> * {@codesnippet com.azure.storage.queue.queueClient.instantiation.credential} * * <p><strong>Instantiating an Asynchronous Queue Client with credential</strong></p> * {@codesnippet com.azure.storage.queue.queueAsyncClient.instantiation.credential} * * <p>Another way to authenticate the client is using a {@link SharedKeyCredential}. To create a SharedKeyCredential * a connection string from the Storage Queue service must be used. Set the SharedKeyCredential with * {@link QueueClientBuilder#connectionString(String) connectionString}. If the builder has both a SASTokenCredential and * SharedKeyCredential the SharedKeyCredential will be preferred when authorizing requests sent to the service.</p> * * <p><strong>Instantiating a synchronous Queue Client with connection string.</strong></p> * {@codesnippet com.azure.storage.queue.queueClient.instantiation.connectionstring} * * <p><strong>Instantiating an Asynchronous Queue Client with connection string.</strong></p> * {@codesnippet com.azure.storage.queue.queueAsyncClient.instantiation.connectionstring} * * @see QueueClient * @see QueueAsyncClient * @see SASTokenCredential * @see SharedKeyCredential */ public final class QueueClientBuilder { private static final ClientLogger LOGGER = new ClientLogger(QueueClientBuilder.class); private static final String ACCOUNT_NAME = "accountname"; private final List<HttpPipelinePolicy> policies; private URL endpoint; private String queueName; private SASTokenCredential sasTokenCredential; private SharedKeyCredential sharedKeyCredential; private TokenCredential bearerTokenCredential; private HttpClient httpClient; private HttpPipeline pipeline; private HttpLogDetailLevel logLevel; private RetryPolicy retryPolicy; private Configuration configuration; /** * Creates a builder instance that is able to configure and construct {@link QueueClient QueueClients} * and {@link QueueAsyncClient QueueAsyncClients}. */ public QueueClientBuilder() { retryPolicy = new RetryPolicy(); logLevel = HttpLogDetailLevel.NONE; policies = new ArrayList<>(); configuration = ConfigurationManager.getConfiguration(); } /** * Creates a {@link QueueClient} based on options set in the builder. Every time {@code buildClient()} is * called a new instance of {@link QueueClient} is created. * * <p> * If {@link QueueClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline}, * {@link QueueClientBuilder#endpoint(String) endpoint}, and * {@link QueueClientBuilder#queueName(String) queueName} are used to create the {@link QueueAsyncClient client}. * All other builder settings are ignored. * </p> * * @return A QueueClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} or {@code queueName} have not been set. * @throws IllegalStateException If neither a {@link SharedKeyCredential} or {@link SASTokenCredential} has been set. */ public QueueClient buildClient() { return new QueueClient(buildAsyncClient()); } /** * Creates a {@link QueueAsyncClient} based on options set in the builder. Every time {@code buildAsyncClient()} is * called a new instance of {@link QueueAsyncClient} is created. * * <p> * If {@link QueueClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline}, * {@link QueueClientBuilder#endpoint(String) endpoint}, and * {@link QueueClientBuilder#queueName(String) queueName} are used to create the {@link QueueAsyncClient client}. * All other builder settings are ignored. * </p> * * @return A QueueAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} or {@code queueName} have not been set. * @throws IllegalArgumentException If neither a {@link SharedKeyCredential} or {@link SASTokenCredential} has been set. */ public QueueAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint); Objects.requireNonNull(queueName); if (sasTokenCredential == null && sharedKeyCredential == null && bearerTokenCredential == null) { LOGGER.logExceptionAsError(new IllegalArgumentException("Credentials are required for authorization")); return null; } if (pipeline != null) { return new QueueAsyncClient(endpoint, pipeline, queueName); } // Closest to API goes first, closest to wire goes last. final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(QueueConfiguration.NAME, QueueConfiguration.VERSION, configuration)); policies.add(new RequestIdPolicy()); policies.add(new AddDatePolicy()); if (sharedKeyCredential != null) { policies.add(new SharedKeyCredentialPolicy(sharedKeyCredential)); } else if (bearerTokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(bearerTokenCredential, String.format("%s/.default", endpoint))); } else if (sasTokenCredential != null) { policies.add(new SASTokenCredentialPolicy(sasTokenCredential)); } HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(logLevel)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new QueueAsyncClient(endpoint, pipeline, queueName); } /** * Sets the endpoint for the Azure Storage Queue instance that the client will interact with. * * <p>The first path segment, if the endpoint contains path segments, will be assumed to be the name of the queue * that the client will interact with.</p> * * <p>Query parameters of the endpoint will be parsed using {@link SASTokenCredential#fromQueryParameters(Map)} in an * attempt to generate a {@link SASTokenCredential} to authenticate requests sent to the service.</p> * * @param endpoint The URL of the Azure Storage Queue instance to send service requests to and receive responses from. * @return the updated QueueClientBuilder object * @throws IllegalArgumentException If {@code endpoint} isn't a proper URL */ public QueueClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint); try { URL fullURL = new URL(endpoint); this.endpoint = new URL(fullURL.getProtocol() + "://" + fullURL.getHost()); // Attempt to get the queue name from the URL passed String[] pathSegments = fullURL.getPath().split("/", 2); if (pathSegments.length == 2 && !ImplUtils.isNullOrEmpty(pathSegments[1])) { this.queueName = pathSegments[1]; } // Attempt to get the SAS token from the URL passed this.sasTokenCredential = SASTokenCredential.fromQueryParameters(Utility.parseQueryString(fullURL.getQuery())); if (this.sasTokenCredential != null) { this.sharedKeyCredential = null; this.bearerTokenCredential = null; } } catch (MalformedURLException ex) { LOGGER.logExceptionAsError(new IllegalArgumentException("The Azure Storage Queue endpoint url is malformed. Endpoint: " + endpoint)); return null; } return this; } /** * Sets the name of the queue that the client will interact with. * * @param queueName Name of the queue * @return the updated QueueClientBuilder object * @throws NullPointerException If {@code queueName} is {@code null}. */ public QueueClientBuilder queueName(String queueName) { this.queueName = Objects.requireNonNull(queueName); return this; } /** * Sets the {@link SASTokenCredential} used to authenticate requests sent to the Queue. * * @param credential SAS token credential generated from the Storage account that authorizes requests * @return the updated QueueClientBuilder object * @throws NullPointerException If {@code credential} is {@code null}. */ public QueueClientBuilder credential(SASTokenCredential credential) { this.sasTokenCredential = Objects.requireNonNull(credential); this.sharedKeyCredential = null; this.bearerTokenCredential = null; return this; } /** * Sets the {@link SharedKeyCredential} used to authenticate requests sent to the Queue. * * @param credential Shared key credential can retrieve from the Storage account that authorizes requests * @return the updated QueueServiceClientBuilder object * @throws NullPointerException If {@code credential} is {@code null}. */ public QueueClientBuilder credential(SharedKeyCredential credential) { this.sharedKeyCredential = Objects.requireNonNull(credential); this.sasTokenCredential = null; this.bearerTokenCredential = null; return this; } /** * Sets the {@link TokenCredential} used to authenticate requests sent to the Queue service. * @param credential authorization credential * @return the updated QueueServiceClientBuilder object * @throws NullPointerException If {@code credential} is {@code null} */ public QueueClientBuilder credential(TokenCredential credential) { this.bearerTokenCredential = Objects.requireNonNull(credential); this.sharedKeyCredential = null; this.sasTokenCredential = null; return this; } /** * Creates a {@link SharedKeyCredential} from the {@code connectionString} used to authenticate requests sent to the * Queue service. * * @param connectionString Connection string from the Access Keys section in the Storage account * @return the updated QueueClientBuilder object * @throws NullPointerException If {@code connectionString} is {@code null}. */ public QueueClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString); this.sharedKeyCredential = SharedKeyCredential.fromConnectionString(connectionString); getEndPointFromConnectionString(connectionString); return this; } private void getEndPointFromConnectionString(String connectionString) { HashMap<String, String> connectionStringPieces = new HashMap<>(); for (String connectionStringPiece : connectionString.split(";")) { String[] kvp = connectionStringPiece.split("=", 2); connectionStringPieces.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } String accountName = connectionStringPieces.get(ACCOUNT_NAME); try { this.endpoint = new URL(String.format("https://%s.queue.core.windows.net", accountName)); } catch (MalformedURLException e) { LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("There is no valid account for the connection string. " + "Connection String: %s", connectionString))); } } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param httpClient The HTTP client to use for requests. * @return The updated QueueClientBuilder object. * @throws NullPointerException If {@code httpClient} is {@code null}. */ public QueueClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient); return this; } /** * Adds a policy to the set of existing policies that are executed after the {@link RetryPolicy}. * * @param pipelinePolicy The retry policy for service requests. * @return The updated QueueClientBuilder object. * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ public QueueClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { Objects.requireNonNull(pipelinePolicy); this.policies.add(pipelinePolicy); return this; } /** * Sets the logging level for HTTP requests and responses. * * @param logLevel The amount of logging output when sending and receiving HTTP requests/responses. * @return The updated QueueClientBuilder object. */ public QueueClientBuilder httpLogDetailLevel(HttpLogDetailLevel logLevel) { this.logLevel = logLevel; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link QueueClientBuilder#endpoint(String) endpoint} * and {@link QueueClientBuilder#queueName(String) queueName} when building clients. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated QueueClientBuilder object. * @throws NullPointerException If {@code pipeline} is {@code null}. */ public QueueClientBuilder pipeline(HttpPipeline pipeline) { Objects.requireNonNull(pipeline); this.pipeline = pipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the {@link ConfigurationManager#getConfiguration() global * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. * * @param configuration The configuration store used to * @return The updated QueueClientBuilder object. */ public QueueClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } }
46.258065
145
0.71705
9167894dc86cb5f7d38d5a3599e251906059dceb
349
package com.vvnc.movies; class RemovedItemsInfo { private int startPosition; private int count; RemovedItemsInfo(int startIndex, int count) { this.startPosition = startIndex; this.count = count; } int getStartPosition() { return startPosition; } int getCount() { return count; } }
17.45
49
0.621777
0c2c03d40590e31d6069b532044a79673f17ebe2
900
package commands; import java.util.ArrayList; import java.util.LinkedList; import model.Data; public class SetPalette extends Command{ public static final String ARG_TYPE = "Constant"; public SetPalette(Data data) { super(data); myArgs = new ArrayList<String>(); myArgTypes = new LinkedList<String>(); myArgTypes.add(ARG_TYPE); myArgTypes.add(ARG_TYPE); myArgTypes.add(ARG_TYPE); myArgTypes.add(ARG_TYPE); } @Override public double execute() throws Exception { int[] rgb = new int[3]; for(int i = 0; i < rgb.length; i++) { double arg = Double.parseDouble(myArgs.get(i+1)); if (arg < 0 || arg > 255) { throw new RuntimeException("RGB values must a nonnegative integer less than 256"); } rgb[i] = doubleToInt(arg); } double index = Double.parseDouble(myArgs.get(0)); myData.addColor(doubleToInt(index), rgb[0], rgb[1], rgb[2]); return index; } }
23.684211
86
0.688889
b707cb4c5d0b0190b3f1d6a70124dd006627fd3c
1,021
package com.nag.android.stm; import java.util.Arrays; import java.util.Comparator; import android.content.Context; import android.graphics.Point; import android.os.AsyncTask; import android.widget.ArrayAdapter; public class ASyncThumbnailUpdater extends AsyncTask<Context,ThumbnailInfo,Void>{ private ArrayAdapter<ThumbnailInfo> adapter; private Point size; ASyncThumbnailUpdater(ArrayAdapter<ThumbnailInfo>adapter, Point size){ this.adapter = adapter; this.size = size; } @Override protected Void doInBackground(Context... context) { String[] files = context[0].fileList(); Arrays.sort(files, new Comparator<String>(){ @Override public int compare(String lhs, String rhs) { return -lhs.compareTo(rhs); } }); for(String filename : files){ synchronized(ASyncPictureUpdater.lock){ this.publishProgress(new ThumbnailInfo(context[0], size, filename)); } } return null; } @Override protected void onProgressUpdate(ThumbnailInfo... result) { adapter.add(result[0]); } }
24.309524
81
0.746327
9563508047449ac2dc46dfc9b877ebaa55c5a106
360
//,temp,sample_4035.java,2,8,temp,sample_4095.java,2,11 //,3 public class xxx { private void printDocumentsReport(Set<File> docs, Set<File> duplicate, Set<File> missing) { getLog().info("================================================================================"); getLog().info(""); getLog().info(""); for (File file : docs) { log.info("t t"); } } };
24
98
0.511111
15369637a57e6e89a3673d546322082672f1f983
1,665
package wt; import edu.mines.jtk.util.*; import edu.mines.jtk.awt.ColorMap; import edu.mines.jtk.dsp.Sampling; import edu.mines.jtk.dsp.SincInterp; import edu.mines.jtk.dsp.SincInterp.Extrapolation; import static edu.mines.jtk.util.ArrayMath.*; /** * Computes a linear extrapolation of a 1D curve in a least squares sense. * * @author Andrew Munoz, Colorado School of Mines * @version 11.23.13 */ public class LinearExtrapolator { public LinearExtrapolator(int m) { _m = m; } public float[] extrapolateFirst( double fx, double fy, Sampling sx, double[] y) { return extrapolateFirst(sx.getDelta(),fx,fy,sx.getValues(),y); } public float[] extrapolateLast( double lx, double ly, Sampling sx, double[] y) { return extrapolateLast(sx.getDelta(),lx,ly,sx.getValues(),y); } public float[] extrapolateFirst( double dx, double fx, double fy, double[] x, double[] y) { double lx = x[x.length-1]; double ly = y[y.length-1]; return extrapolate(dx,fx,fy,lx,ly,x,y); } public float[] extrapolateLast( double dx, double lx, double ly, double[] x, double[] y) { double fx = x[0]; double fy = y[0]; return extrapolate(dx,fx,fy,lx,ly,x,y); } public float[] extrapolate( double dx, double fx, double fy, double lx, double ly, double[] x, double[] y) { int nb = x.length; Check.argument(nb==y.length,"x and y lengths must be equal"); int nf = (int)floor(fx/dx); int nl = nb-(int)ceil(lx/dx); int ne = nf+nb+nl; double[] xn = new double[ne]; return new float[nb]; } private int _m; };
21.346154
75
0.627628
7ec6ef06c9da3a9e167c60ab37a0383592cdbe82
333
package harshwinds.noisemaker; import java.util.List; /** * Represents a player of sounds with an indicator of the index of the * order the sounds are being played in relation to other sounds being * played * * @author harshwinds */ @FunctionalInterface interface Player { void play(final int index, List<Sound> sounds); }
20.8125
70
0.744745
b3f4b4a16ea7a473965c734fb4cda93590566ee8
718
package uk.gov.ida.rp.testrp.builders; import uk.gov.ida.rp.testrp.contract.Cycle3DatasetDto; import java.util.HashMap; import java.util.Map; public class Cycle3DatasetDtoBuilder { private Map<String, String> attributes = new HashMap<>(); public static Cycle3DatasetDtoBuilder aCycle3DatasetDto() { return new Cycle3DatasetDtoBuilder(); } public Cycle3DatasetDto build() { if (!attributes.isEmpty()) { attributes.put("test-name", "test-value"); } return Cycle3DatasetDto.createFromData(attributes); } public Cycle3DatasetDtoBuilder addCycle3Data(String name, String value) { attributes.put(name, value); return this; } }
23.933333
77
0.685237
60b17b10877cff31f998bd28d2d806504803316c
34,067
/* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.data; import javax.xml.namespace.QName; import org.junit.Test; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.Constants; import com.siemens.ct.exi.core.EncodingOptions; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.main.QuickTestConfiguration; public class GeneralTestCase extends AbstractTestCase { public GeneralTestCase() { super("General Test Cases"); } public static void setupQuickTest() { // GeneralTestCase.setConfigurationPerson ( ); // GeneralTestCase.setConfigurationPersonAdjusted ( ); // GeneralTestCase.setConfigurationPersonal ( ); // GeneralTestCase.setConfigurationUnbounded ( ); // GeneralTestCase.setConfigurationDatatypeInteger(); // GeneralTestCase.setConfigurationDatatypeFloat(); // GeneralTestCase.setConfigurationDatatypes(); // GeneralTestCase.setConfigurationDatatypes2 ( ); // GeneralTestCase.setConfigurationOrder ( ); // GeneralTestCase.setConfigurationRandj(); // GeneralTestCase.setConfigurationPurchaseOrder ( ); // GeneralTestCase.setConfigurationTest1 ( ); // GeneralTestCase.setConfigurationTest1Pfx ( ); // GeneralTestCase.setConfigurationTest2 ( ); // GeneralTestCase.setConfigurationTest3(); // GeneralTestCase.setConfigurationTest4 ( ); // GeneralTestCase.setConfigurationTest5 ( ); // GeneralTestCase.setConfigurationComplexStructure ( ); // GeneralTestCase.setConfigurationSimpleContent ( ); // GeneralTestCase.setConfigurationEmptyContent ( ); // GeneralTestCase.setConfigurationAttributes ( ); // GeneralTestCase.setConfigurationPI1 ( ); // GeneralTestCase.setConfigurationDocType(); // GeneralTestCase.setConfigurationDocType0 ( ); // GeneralTestCase.setConfigurationDocType1 ( ); // GeneralTestCase.setConfigurationDocType2 ( ); // GeneralTestCase.setConfigurationDocType3 ( ); // GeneralTestCase.setConfigurationEntityReference1(); // GeneralTestCase.setConfigurationEntityReference2(); GeneralTestCase.setConfigurationEntityReference3(); // GeneralTestCase.setConfigurationEntityReferenceUnresolved1(); // GeneralTestCase.setConfigurationCData1(); // GeneralTestCase.setConfigurationPatterns ( ); // GeneralTestCase.setConfigurationStringTable1 ( ); // GeneralTestCase.setConfigurationStringTable2 ( ); } protected void setUp() throws Exception { // #1 (default) testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createDefault()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); // #1 (DTDs) testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createDefault()); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1).getFidelityOptions() .setFidelity(FidelityOptions.FEATURE_DTD, true); // #1 (Prefixes&PIs) testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createDefault()); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1).getFidelityOptions() .setFidelity(FidelityOptions.FEATURE_PREFIX, true); testCaseOptions.get(testCaseOptions.size() - 1).getFidelityOptions() .setFidelity(FidelityOptions.FEATURE_PI, true); // #2 testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BYTE_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createDefault()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); // #3 testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.PRE_COMPRESSION); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createDefault()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); // #4 testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.COMPRESSION); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createDefault()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); // #5 (all) testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createAll()); testCaseOptions.get(testCaseOptions.size() - 1).getEncodingOptions() .setOption(EncodingOptions.INCLUDE_XSI_SCHEMALOCATION); // testCaseOptions.get(testCaseOptions.size()-1).getFidelityOptions().setFidelity( // FidelityOptions.FEATURE_XSI_SCHEMALOCATION, true); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(true); // #6 testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.COMPRESSION); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createAll()); testCaseOptions.get(testCaseOptions.size() - 1).getEncodingOptions() .setOption(EncodingOptions.INCLUDE_XSI_SCHEMALOCATION); // testCaseOptions.get(testCaseOptions.size()-1).getFidelityOptions().setFidelity( // FidelityOptions.FEATURE_XSI_SCHEMALOCATION, true); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(true); // #7 (strict) testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createStrict()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1).setSchemaInformedOnly( true); // #7b (strict & lexical-values) testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createStrict()); testCaseOptions.get(testCaseOptions.size() - 1).getFidelityOptions() .setFidelity(FidelityOptions.FEATURE_LEXICAL_VALUE, true); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1).setSchemaInformedOnly( true); // #7c (strict & lexical-values) testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createStrict()); testCaseOptions.get(testCaseOptions.size() - 1).getFidelityOptions() .setFidelity(FidelityOptions.FEATURE_LEXICAL_VALUE, true); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1).getEncodingOptions() .setOption(EncodingOptions.INCLUDE_OPTIONS); testCaseOptions.get(testCaseOptions.size() - 1).getEncodingOptions() .setOption(EncodingOptions.INCLUDE_SCHEMA_ID); testCaseOptions.get(testCaseOptions.size() - 1).setSchemaInformedOnly( true); // #8 testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.COMPRESSION); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createStrict()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1).setSchemaInformedOnly( true); // #9 BlockSize testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.COMPRESSION); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createStrict()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1).setSchemaInformedOnly( true); testCaseOptions.get(testCaseOptions.size() - 1).setBlockSize(200); // #9 BlockSize testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.COMPRESSION); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createAll()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1).setSchemaInformedOnly( true); testCaseOptions.get(testCaseOptions.size() - 1).setBlockSize(200); // #10 BlockSize & valueMaxLength & valuePartitionCapacity testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.COMPRESSION); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createAll()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1).setBlockSize(200); testCaseOptions.get(testCaseOptions.size() - 1).setValueMaxLength(8); testCaseOptions.get(testCaseOptions.size() - 1) .setValuePartitionCapacity(16); // #11 valuePartitionCapacity testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createAll()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1) .setValuePartitionCapacity(5); // #11a valuePartitionCapacity + Header Cookie & Options & SchemaId testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createAll()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1) .setValuePartitionCapacity(4); testCaseOptions.get(testCaseOptions.size() - 1).getEncodingOptions() .setOption(EncodingOptions.INCLUDE_COOKIE); testCaseOptions.get(testCaseOptions.size() - 1).getEncodingOptions() .setOption(EncodingOptions.INCLUDE_OPTIONS); testCaseOptions.get(testCaseOptions.size() - 1).getEncodingOptions() .setOption(EncodingOptions.INCLUDE_SCHEMA_ID); // #12 dtr map testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createDefault()); QName[] dtrTypes = { new QName(Constants.XML_SCHEMA_NS_URI, "integer") }; QName[] dtrRepresentations = { new QName(Constants.W3C_EXI_NS_URI, "string") }; testCaseOptions.get(testCaseOptions.size() - 1) .setDatatypeRepresentationMap(dtrTypes, dtrRepresentations); // #13a localValuePartitions testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createAll()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1) .setLocalValuePartitions(false); // #13b localValuePartitions + valuePartitionCapacity testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createAll()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1) .setValuePartitionCapacity(4); testCaseOptions.get(testCaseOptions.size() - 1) .setLocalValuePartitions(false); // #14 grammar restrictions, needs schema-informed mode! testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size() - 1).setCodingMode( CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size() - 1).setFidelityOptions( FidelityOptions.createDefault()); testCaseOptions.get(testCaseOptions.size() - 1).setFragments(false); testCaseOptions.get(testCaseOptions.size() - 1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size() - 1) .setMaximumNumberOfBuiltInProductions(0); testCaseOptions.get(testCaseOptions.size() - 1).setSchemaLocation(""); // xsd-types // only // // #13 UCD Profile // testCaseOptions.add(new TestCaseOption()); // testCaseOptions.get(testCaseOptions.size()-1).setCodingMode(CodingMode.BIT_PACKED); // testCaseOptions.get(testCaseOptions.size()-1).setFidelityOptions( // FidelityOptions.createDefault()); // testCaseOptions.get(testCaseOptions.size()-1).setFragments(false); // testCaseOptions.get(testCaseOptions.size()-1).setXmlEqual(false); // testCaseOptions.get(testCaseOptions.size()-1).setProfile(EXIFactory.UCD_PROFILE); // // // #13 UCD Profile Byte-Aligned // testCaseOptions.add(new TestCaseOption()); // testCaseOptions.get(testCaseOptions.size()-1).setCodingMode(CodingMode.BYTE_PACKED); // testCaseOptions.get(testCaseOptions.size()-1).setFidelityOptions( // FidelityOptions.createDefault()); // testCaseOptions.get(testCaseOptions.size()-1).setFragments(false); // testCaseOptions.get(testCaseOptions.size()-1).setXmlEqual(false); // testCaseOptions.get(testCaseOptions.size()-1).setProfile(EXIFactory.UCD_PROFILE); // #15 (default + non-evolving grammars) testCaseOptions.add(new TestCaseOption()); testCaseOptions.get(testCaseOptions.size()-1).setCodingMode(CodingMode.BIT_PACKED); testCaseOptions.get(testCaseOptions.size()-1).setFidelityOptions( FidelityOptions.createDefault()); testCaseOptions.get(testCaseOptions.size()-1).setFragments(false); testCaseOptions.get(testCaseOptions.size()-1).setXmlEqual(false); testCaseOptions.get(testCaseOptions.size()-1).setUsingNonEvolvingGrammars(true); } @Test public void testEntityReference1() throws Exception { // set up configuration setConfigurationEntityReference1(); // Strict & LexicalValues is not working (Prefixes required) FidelityOptions noValidOptions = FidelityOptions.createStrict(); noValidOptions.setFidelity(FidelityOptions.FEATURE_LEXICAL_VALUE, true); // execute test _test(noValidOptions); } @Test public void testPerson() throws Exception { // set up configuration setConfigurationPerson(); // execute test _test(); } public static void setConfigurationPerson() { QuickTestConfiguration.setXsdLocation("./data/general/person.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/person.xml"); QuickTestConfiguration.setExiLocation("./out/general/person.exi"); } @Test public void testPersonAdjusted() throws Exception { // set up configuration setConfigurationPersonAdjusted(); // execute test _test(); } public static void setConfigurationPersonAdjusted() { QuickTestConfiguration.setXsdLocation("./data/general/person.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/person_adjusted.xml"); QuickTestConfiguration .setExiLocation("./out/general/person_adjusted.exi"); } @Test public void testPersonal() throws Exception { // set up configuration setConfigurationPersonal(); // execute test _test(); } public static void setConfigurationPersonal() { QuickTestConfiguration.setXsdLocation("./data/general/personal.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/personal.xml"); QuickTestConfiguration.setExiLocation("./out/general/personal.exi"); } @Test public void testUnbounded() throws Exception { // set up configuration setConfigurationUnbounded(); // execute test _test(); } public static void setConfigurationUnbounded() { QuickTestConfiguration.setXsdLocation("./data/general/unbounded.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/unbounded.xml"); QuickTestConfiguration.setExiLocation("./out/general/unbounded.exi"); } @Test public void testDatatypeInteger() throws Exception { // set up configuration setConfigurationDatatypeInteger(); // execute test _test(); } public static void setConfigurationDatatypeInteger() { QuickTestConfiguration .setXsdLocation("./data/general/datatypeInteger.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/datatypeInteger.xml"); QuickTestConfiguration .setExiLocation("./out/general/datatypeInteger.exi"); } @Test public void testDatatypeFloat() throws Exception { // set up configuration setConfigurationDatatypeFloat(); // execute test _test(); } public static void setConfigurationDatatypeFloat() { QuickTestConfiguration .setXsdLocation("./data/general/datatypeFloat.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/datatypeFloat.xml"); QuickTestConfiguration .setExiLocation("./out/general/datatypeFloat.exi"); } @Test public void testDatatypes() throws Exception { // set up configuration setConfigurationDatatypes(); // execute test _test(); } public static void setConfigurationDatatypes() { QuickTestConfiguration.setXsdLocation("./data/general/datatypes.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/datatypes.xml"); QuickTestConfiguration.setExiLocation("./out/general/datatypes.exi"); } @Test public void testDatatypes2() throws Exception { // set up configuration setConfigurationDatatypes2(); // execute test _test(); } public static void setConfigurationDatatypes2() { QuickTestConfiguration.setXsdLocation("./data/general/datatypes2.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/datatypes2.xml"); QuickTestConfiguration.setExiLocation("./out/general/datatypes2.exi"); } @Test public void testOrder() throws Exception { // set up configuration setConfigurationOrder(); // execute test _test(); } public static void setConfigurationOrder() { QuickTestConfiguration.setXsdLocation("./data/general/order.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/order.xml"); QuickTestConfiguration.setExiLocation("./out/general/order.exi"); } @Test public void testComplexStructure() throws Exception { // set up configuration setConfigurationComplexStructure(); // execute test _test(); } public static void setConfigurationComplexStructure() { QuickTestConfiguration .setXsdLocation("./data/general/complex-structure.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/complex-structure.xml"); QuickTestConfiguration .setExiLocation("./out/general/complex-structure.exi"); } @Test public void testSimpleContent() throws Exception { // set up configuration setConfigurationSimpleContent(); // execute test _test(); } public static void setConfigurationSimpleContent() { QuickTestConfiguration .setXsdLocation("./data/general/simpleContent.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/simpleContent.xml"); QuickTestConfiguration .setExiLocation("./out/general/simpleContent.xml.exi"); } @Test public void testEmptyContent() throws Exception { // set up configuration setConfigurationEmptyContent(); // execute test _test(); } public static void setConfigurationEmptyContent() { QuickTestConfiguration .setXsdLocation("./data/general/emptyContent.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/emptyContent.xml"); QuickTestConfiguration .setExiLocation("./out/general/emptyContent.xml.exi"); } @Test public void testAttributes() throws Exception { // set up configuration setConfigurationAttributes(); // execute test _test(); } public static void setConfigurationAttributes() { QuickTestConfiguration.setXsdLocation("./data/general/attributes.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/attributes.xml"); QuickTestConfiguration .setExiLocation("./out/general/attributes.xml.exi"); } @Test public void testPostalRandj() throws Exception { // set up configuration setConfigurationRandj(); // execute test _test(); } public static void setConfigurationRandj() { QuickTestConfiguration.setXsdLocation("./data/general/randj.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/randj.xml"); QuickTestConfiguration.setExiLocation("./out/general/randj.exi"); } @Test public void testPurchaseOrder() throws Exception { // set up configuration setConfigurationPurchaseOrder(); // execute test _test(); } public static void setConfigurationPurchaseOrder() { QuickTestConfiguration.setXsdLocation("./data/general/po.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/po.xml"); QuickTestConfiguration.setExiLocation("./out/general/po.xml.exi"); } @Test public void testXMLTest1() throws Exception { // set up configuration setConfigurationTest1(); // execute test _test(); } public static void setConfigurationTest1() { QuickTestConfiguration.setXsdLocation("./data/general/test1.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/test1.xml"); QuickTestConfiguration.setExiLocation("./out/general/test1.exi"); } @Test public void testXMLTest1Pfx() throws Exception { // set up configuration setConfigurationTest1Pfx(); // execute test _test(); } public static void setConfigurationTest1Pfx() { QuickTestConfiguration.setXsdLocation("./data/general/test1.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/test1_pfx.xml"); QuickTestConfiguration.setExiLocation("./out/general/test1_pfx.exi"); } @Test public void testXMLTest2() throws Exception { // set up configuration setConfigurationTest2(); // execute test _test(); } public static void setConfigurationTest2() { QuickTestConfiguration.setXsdLocation("./data/general/test2.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/test2.xml"); QuickTestConfiguration.setExiLocation("./out/general/test2.exi"); } @Test public void testXMLTest3() throws Exception { // set up configuration setConfigurationTest3(); // execute test _test(); } public static void setConfigurationTest3() { QuickTestConfiguration.setXsdLocation("./data/general/test3.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/test3.xml"); QuickTestConfiguration.setExiLocation("./out/general/test3.exi"); } @Test public void testXMLTest4() throws Exception { // set up configuration setConfigurationTest4(); // execute test _test(); } public static void setConfigurationTest4() { QuickTestConfiguration.setXsdLocation("./data/general/test4.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/test4.xml"); QuickTestConfiguration.setExiLocation("./out/general/test4.xml.exi"); } @Test public void testXMLTest5() throws Exception { // set up configuration setConfigurationTest5(); // execute test _test(); } public static void setConfigurationTest5() { QuickTestConfiguration.setXsdLocation("./data/general/test5.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/test5.xml"); QuickTestConfiguration.setExiLocation("./out/general/test5.xml.exi"); } @Test public void testPI1() throws Exception { // set up configuration setConfigurationPI1(); // execute test _test(); } public static void setConfigurationPI1() { QuickTestConfiguration.setXsdLocation("./data/general/pi1.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/pi1.xml"); QuickTestConfiguration.setExiLocation("./out/general/pi1.xml.exi"); } // @Test // public void testDoc10() throws Exception { // // set up configuration // setConfigurationDoc10(); // // // execute test // _test(); // } // // public static void setConfigurationDoc10() { // QuickTestConfiguration.setXsdLocation("./data/general/docType.xsd"); // QuickTestConfiguration.setXmlLocation("./data/general/doc-10.xml"); // QuickTestConfiguration.setExiLocation("./out/general/doc-10.xml.exi"); // } @Test public void testDocType() throws Exception { // set up configuration setConfigurationDocType(); // execute test _test(); } public static void setConfigurationDocType() { QuickTestConfiguration.setXsdLocation("./data/general/docType.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/docType.xml"); QuickTestConfiguration.setExiLocation("./out/general/docType.xml.exi"); } @Test public void testDocType0() throws Exception { // set up configuration setConfigurationDocType0(); // execute test _test(); } public static void setConfigurationDocType0() { QuickTestConfiguration.setXsdLocation("./data/general/docType.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/docType0.xml"); QuickTestConfiguration.setExiLocation("./out/general/docType0.xml.exi"); } @Test public void testDocType1() throws Exception { // set up configuration setConfigurationDocType1(); // execute test _test(); } public static void setConfigurationDocType1() { QuickTestConfiguration.setXsdLocation("./data/general/docType.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/docType1.xml"); QuickTestConfiguration.setExiLocation("./out/general/docType1.xml.exi"); } @Test public void testDocType2() throws Exception { // set up configuration setConfigurationDocType2(); // execute test _test(); } public static void setConfigurationDocType2() { QuickTestConfiguration.setXsdLocation("./data/general/docType.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/docType2.xml"); QuickTestConfiguration.setExiLocation("./out/general/docType2.xml.exi"); } @Test public void testDocType3() throws Exception { // set up configuration setConfigurationDocType3(); // execute test _test(); } public static void setConfigurationDocType3() { QuickTestConfiguration.setXsdLocation("./data/general/docType.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/docType3.xml"); QuickTestConfiguration.setExiLocation("./out/general/docType3.xml.exi"); } public static void setConfigurationEntityReference1() { QuickTestConfiguration.setXsdLocation("./data/general/empty.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/entityReference1.xml"); QuickTestConfiguration .setExiLocation("./out/general/entityReference1.xml.exi"); } public static void setConfigurationEntityReference2() { QuickTestConfiguration.setXsdLocation("./data/general/empty.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/entityReference2.xml"); QuickTestConfiguration .setExiLocation("./out/general/entityReference2.xml.exi"); } @Test public void testEntityReference2() throws Exception { // set up configuration setConfigurationEntityReference2(); // Strict & LexicalValues is not working (Prefixes required) FidelityOptions noValidOptions = FidelityOptions.createStrict(); noValidOptions.setFidelity(FidelityOptions.FEATURE_LEXICAL_VALUE, true); // execute test _test(noValidOptions); } // @Test // public void testEntityReferenceUnresolved1() throws Exception { // // set up configuration // setConfigurationEntityReferenceUnresolved1(); // // // execute test // _test(); // } // // public static void setConfigurationEntityReferenceUnresolved1() { // QuickTestConfiguration.setXsdLocation("./data/general/empty.xsd"); // QuickTestConfiguration // .setXmlLocation("./data/general/entityReferenceUnresolved1.xml"); // QuickTestConfiguration // .setExiLocation("./out/general/entityReferenceUnresolved1.xml.exi"); // } public static void setConfigurationEntityReference3() { QuickTestConfiguration.setXsdLocation("./data/general/empty.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/entityReference3.xml"); QuickTestConfiguration .setExiLocation("./out/general/entityReference3.xml.exi"); } @Test public void testEntityReference3() throws Exception { // set up configuration setConfigurationEntityReference3(); // Strict & LexicalValues is not working (Prefixes required) FidelityOptions noValidOptions = FidelityOptions.createStrict(); noValidOptions.setFidelity(FidelityOptions.FEATURE_LEXICAL_VALUE, true); // execute test _test(noValidOptions); } @Test public void xtestCData1() throws Exception { // set up configuration setConfigurationCData1(); // execute test _test(); } public static void setConfigurationCData1() { QuickTestConfiguration.setXsdLocation("./data/general/empty.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/cdata1.xml"); QuickTestConfiguration.setExiLocation("./out/general/cdata1.xml.exi"); } @Test public void testPatterns() throws Exception { // set up configuration setConfigurationPatterns(); // execute test _test(); } public static void setConfigurationPatterns() { QuickTestConfiguration.setXsdLocation("./data/general/patterns.xsd"); QuickTestConfiguration.setXmlLocation("./data/general/patterns.xml"); QuickTestConfiguration.setExiLocation("./out/general/patterns.xml.exi"); } @Test public void testStringTable1() throws Exception { // set up configuration setConfigurationStringTable1(); // execute test _test(); } public static void setConfigurationStringTable1() { QuickTestConfiguration .setXsdLocation("./data/general/stringTable1.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/stringTable1.xml"); QuickTestConfiguration .setExiLocation("./out/general/stringTable1.xml.exi"); } @Test public void testStringTable2() throws Exception { // set up configuration setConfigurationStringTable2(); // execute test _test(); } public static void setConfigurationStringTable2() { QuickTestConfiguration .setXsdLocation("./data/general/stringTable2.xsd"); QuickTestConfiguration .setXmlLocation("./data/general/stringTable2.xml"); QuickTestConfiguration .setExiLocation("./out/general/stringTable2.xml.exi"); } }
35.822292
90
0.738192
f6e386c039bd8f8426ac93f72c31c0a3bc226aea
18,015
/** * <copyright> * </copyright> * * */ package de.darwinspl.preferences.resource.dwprofile.ui; import java.io.IOException; import java.io.StringReader; import java.util.Iterator; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.ListenerList; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.AbstractInformationControl; import org.eclipse.jface.text.IDelayedInputChangeProvider; import org.eclipse.jface.text.IInformationControlExtension2; import org.eclipse.jface.text.IInputChangedListener; import org.eclipse.jface.text.TextPresentation; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTError; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.LocationListener; import org.eclipse.swt.browser.OpenWindowListener; import org.eclipse.swt.browser.ProgressAdapter; import org.eclipse.swt.browser.ProgressEvent; import org.eclipse.swt.browser.WindowEvent; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.graphics.TextStyle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Slider; /** * <p> * Displays HTML information in a {@link Browser} widget. * </p> * <p> * <p> * </p> * <p> * This IInformationControlExtension2 expects {@link #setInput(Object)} to be * called with an argument of type BrowserInformationControlInput. * </p> * <p> * </p> * </p> * <p> * <p>Moved into this package from * <code>org.eclipse.jface.internal.text.revisions</code>.</p> * </p> * <p> * <p>This class may be instantiated; it is not intended to be subclassed.</p> * </p> * <p> * <p>Current problems: * </p> * <p> * <ul> * </p> * <p> * <li>the size computation is too small</li> * </p> * <p> * <li>focusLost event is not sent - see * https://bugs.eclipse.org/bugs/show_bug.cgi?id=84532</li> * </p> * <p> * </ul> * </p> * <p> * </p> * </p> * * @since 3.2 */ public class DwprofileBrowserInformationControl extends AbstractInformationControl implements IInformationControlExtension2, IDelayedInputChangeProvider { /** * <p> * Tells whether the SWT Browser widget and hence this information control is * available. * </p> * * @param parent the parent component used for checking or <code>null</code> if * none * * @return <code>true</code> if this control is available */ public static boolean isAvailable(Composite parent) { if (!fgAvailabilityChecked) { try { Browser browser= new Browser(parent, SWT.NONE); browser.dispose(); fgIsAvailable= true; Slider sliderV= new Slider(parent, SWT.VERTICAL); Slider sliderH= new Slider(parent, SWT.HORIZONTAL); int width= sliderV.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; int height= sliderH.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; fgScrollBarSize= new Point(width, height); sliderV.dispose(); sliderH.dispose(); } catch (SWTError er) { fgIsAvailable= false; } finally { fgAvailabilityChecked= true; } } return fgIsAvailable; } /** * Minimal size constraints. */ private static final int MIN_WIDTH = 80; private static final int MIN_HEIGHT = 50; /** * Availability checking cache. */ private static boolean fgIsAvailable = false; private static boolean fgAvailabilityChecked = false; /** * Cached scroll bar width and height */ private static Point fgScrollBarSize; /** * The control's browser widget */ private Browser fBrowser; /** * Tells whether the browser has content */ private boolean fBrowserHasContent; /** * Text layout used to approximate size of content when rendered in browser */ private TextLayout fTextLayout; /** * Bold text style */ private TextStyle fBoldStyle; private de.darwinspl.preferences.resource.dwprofile.ui.DwprofileDocBrowserInformationControlInput fInput; /** * <code>true</code> iff the browser has completed loading of the last input set * via {@link #setInformation(String)}. */ private boolean fCompleted = false; /** * The listener to be notified when a delayed location changing event happened. */ private IInputChangedListener fDelayedInputChangeListener; /** * The listeners to be notified when the input changed. */ private ListenerList fInputChangeListeners = new ListenerList(ListenerList.IDENTITY); /** * The symbolic name of the font used for size computations, or <code>null</code> * to use dialog font. */ private final String fSymbolicFontName; /** * <p> * Creates a browser information control with the given shell as parent. * </p> * * @param parent the parent shell * @param symbolicFontName the symbolic name of the font used for size computations * @param resizable <code>true</code> if the control should be resizable */ public DwprofileBrowserInformationControl(Shell parent, String symbolicFontName, boolean resizable) { super(parent, resizable); fSymbolicFontName= symbolicFontName; create(); } /** * <p> * Creates a browser information control with the given shell as parent. * </p> * * @param parent the parent shell * @param symbolicFontName the symbolic name of the font used for size computations * @param statusFieldText the text to be used in the optional status field or * <code>null</code> if the status field should be hidden */ public DwprofileBrowserInformationControl(Shell parent, String symbolicFontName, String statusFieldText) { super(parent, statusFieldText); fSymbolicFontName= symbolicFontName; create(); } /** * <p> * Creates a browser information control with the given shell as parent. * </p> * * @param parent the parent shell * @param symbolicFontName the symbolic name of the font used for size computations * @param toolBarManager the manager or <code>null</code> if toolbar is not desired * * @since 3.4 */ public DwprofileBrowserInformationControl(Shell parent, String symbolicFontName, ToolBarManager toolBarManager) { super(parent, toolBarManager); fSymbolicFontName= symbolicFontName; create(); } /** * * @see org.eclipse.jface.text.AbstractInformationControl#createContent(Composite) */ protected void createContent(Composite parent) { fBrowser= new Browser(parent, SWT.NONE); Display display= getShell().getDisplay(); fBrowser.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); fBrowser.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fBrowser.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC dispose(); // XXX: Just hide? Would avoid constant recreations. } public void keyReleased(KeyEvent e) {} }); fBrowser.addProgressListener(new ProgressAdapter() { public void completed(ProgressEvent event) { fCompleted= true; } }); fBrowser.addOpenWindowListener(new OpenWindowListener() { public void open(WindowEvent event) { event.required= true; // Cancel opening of new windows } }); // Replace browser's built-in context menu with none fBrowser.setMenu(new Menu(getShell(), SWT.NONE)); createTextLayout(); } /** * {@inheritDoc} This control can handle {@link String}(no handle) and */ public void setInput(Object input) { Assert.isLegal(input == null || input instanceof String || input instanceof de.darwinspl.preferences.resource.dwprofile.ui.DwprofileDocBrowserInformationControlInput); if (input instanceof String) { setInformation((String)input); return; } fInput= (de.darwinspl.preferences.resource.dwprofile.ui.DwprofileDocBrowserInformationControlInput) input; String content= null; if (fInput != null) content= fInput.getHtml(); fBrowserHasContent= content != null && content.length() > 0; if (!fBrowserHasContent) content= "<html><body ></html>"; boolean RTL= (getShell().getStyle() & SWT.RIGHT_TO_LEFT) != 0; boolean resizable= isResizable(); // The default "overflow:auto" would not result in a predictable width for the // client area and the re-wrapping would cause visual noise String[] styles= null; if (RTL && resizable) { styles= new String[] { "direction:rtl;", "overflow:scroll;", "word-wrap:break-word;" }; } else if (RTL && !resizable) { styles= new String[] { "direction:rtl;", "overflow:hidden;", "word-wrap:break-word;" }; } else if (!resizable) { // XXX: In IE, "word-wrap: break-word;" causes bogus wrapping even in non-broken // words :-(see e.g. Javadoc of String). Re-check whether we really still need // this now that the Javadoc Hover header already sets this style. styles= new String[] { "overflow:hidden;"/*, "word-wrap: break-word;"*/ }; } else { styles= new String[] { "overflow:scroll;" }; } StringBuffer buffer= new StringBuffer(content); de.darwinspl.preferences.resource.dwprofile.ui.DwprofileHTMLPrinter.insertStyles(buffer, styles); content= buffer.toString(); // XXX: Should add some JavaScript here that shows something like "(continued...)" // or "..." at the end of the visible area when the page overflowed with // "overflow:hidden;". fCompleted= false; fBrowser.setText(content); Object[] listeners= fInputChangeListeners.getListeners(); for (int i= 0; i < listeners.length; i++) { ((IInputChangedListener)listeners[i]).inputChanged(fInput); } } public void setVisible(boolean visible) { Shell shell= getShell(); if (shell.isVisible() == visible) { return; } if (!visible) { super.setVisible(false); setInput(null); return; } // The Browser widget flickers when made visible while it is not completely // loaded. The fix is to delay the call to setVisible until either loading is // completed (see ProgressListener in constructor), or a timeout has been reached. final Display display = shell.getDisplay(); // Make sure the display wakes from sleep after timeout: display.timerExec(100, new Runnable() { public void run() { fCompleted= true; } }); while (!fCompleted) { // Drive the event loop to process the events required to load the browser // widget's contents: if (!display.readAndDispatch()) { display.sleep(); } } shell = getShell(); if (shell == null || shell.isDisposed()) { return; } // Avoids flickering when replacing hovers, especially on Vista in ON_CLICK mode. // Causes flickering on GTK. Carbon does not care. if ("win32".equals(SWT.getPlatform())) { shell.moveAbove(null); } super.setVisible(true); } /** * * @see AbstractInformationControl#setSize(int, int) */ public void setSize(int width, int height) { fBrowser.setRedraw(false); // avoid flickering try { super.setSize(width, height); } finally { fBrowser.setRedraw(true); } } /** * <p> * Creates and initializes the text layout used to compute the size hint. * </p> * * @since 3.2 */ private void createTextLayout() { fTextLayout= new TextLayout(fBrowser.getDisplay()); // Initialize fonts String symbolicFontName= fSymbolicFontName == null ? JFaceResources.DIALOG_FONT : fSymbolicFontName; Font font = JFaceResources.getFont(symbolicFontName); fTextLayout.setFont(font); fTextLayout.setWidth(-1); font = JFaceResources.getFontRegistry().getBold(symbolicFontName); fBoldStyle = new TextStyle(font, null, null); // Compute and set tab width fTextLayout.setText(" "); int tabWidth = fTextLayout.getBounds().width; fTextLayout.setTabs(new int[] {tabWidth}); fTextLayout.setText(""); } public void dispose() { if (fTextLayout != null) { fTextLayout.dispose(); fTextLayout = null; } fBrowser = null; super.dispose(); } public Point computeSizeHint() { Point sizeConstraints = getSizeConstraints(); Rectangle trim = computeTrim(); int height = trim.height; TextPresentation presentation= new TextPresentation(); String text; try { text = de.darwinspl.preferences.resource.dwprofile.ui.DwprofileHTMLPrinter.html2text(new StringReader(fInput.getHtml()), presentation); } catch (IOException e) { text = ""; } fTextLayout.setText(text); fTextLayout.setWidth(sizeConstraints == null ? SWT.DEFAULT : sizeConstraints.x - trim.width); Iterator<?> iter= presentation.getAllStyleRangeIterator(); while (iter.hasNext()) { StyleRange sr= (StyleRange)iter.next(); if (sr.fontStyle == SWT.BOLD) { fTextLayout.setStyle(fBoldStyle, sr.start, sr.start + sr.length - 1); } } Rectangle bounds= fTextLayout.getBounds(); // does not return minimum width, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=217446 int lineCount= fTextLayout.getLineCount(); int textWidth= 0; for (int i= 0; i < lineCount; i++) { Rectangle rect= fTextLayout.getLineBounds(i); int lineWidth= rect.x + rect.width; if (i == 0) { lineWidth += fInput.getLeadingImageWidth(); } textWidth= Math.max(textWidth, lineWidth); } bounds.width= textWidth; fTextLayout.setText(""); int minWidth= bounds.width; height= height + bounds.height; // Add some air to accommodate for different browser renderings minWidth+= 15; height+= 15; // Apply max size constraints if (sizeConstraints != null) { if (sizeConstraints.x != SWT.DEFAULT) { minWidth= Math.min(sizeConstraints.x, minWidth + trim.width); } if (sizeConstraints.y != SWT.DEFAULT) { height= Math.min(sizeConstraints.y, height); } } // Ensure minimal size int width= Math.max(MIN_WIDTH, minWidth); height= Math.max(MIN_HEIGHT, height); Point windowSize = new Point(width, height); return windowSize; } /** * * @see org.eclipse.jface.text.IInformationControlExtension3#computeTrim() */ public Rectangle computeTrim() { Rectangle trim = super.computeTrim(); if (isResizable()) { boolean RTL = (getShell().getStyle() & SWT.RIGHT_TO_LEFT) != 0; if (RTL) { trim.x-= fgScrollBarSize.x; } trim.width+= fgScrollBarSize.x; trim.height+= fgScrollBarSize.y; } return trim; } /** * <p> * Adds the listener to the collection of listeners who will be notified when the * current location has changed or is about to change. * </p> * * @param listener the location listener * * @since 3.4 */ public void addLocationListener(LocationListener listener) { fBrowser.addLocationListener(listener); } public void setForegroundColor(Color foreground) { super.setForegroundColor(foreground); fBrowser.setForeground(foreground); } public void setBackgroundColor(Color background) { super.setBackgroundColor(background); fBrowser.setBackground(background); } public boolean hasContents() { return fBrowserHasContent; } /** * <p> * Adds a listener for input changes to this input change provider. Has no effect * if an identical listener is already registered. * </p> * * @param inputChangeListener the listener to add * * @since 3.4 */ public void addInputChangeListener(IInputChangedListener inputChangeListener) { Assert.isNotNull(inputChangeListener); fInputChangeListeners.add(inputChangeListener); } /** * <p> * Removes the given input change listener from this input change provider. Has no * effect if an identical listener is not registered. * </p> * * @param inputChangeListener the listener to remove * * @since 3.4 */ public void removeInputChangeListener(IInputChangedListener inputChangeListener) { fInputChangeListeners.remove(inputChangeListener); } /** * * @see * IDelayedInputChangeProvider#setDelayedInputChangeListener(IInputChangedListener) * * @since 3.4 */ public void setDelayedInputChangeListener(IInputChangedListener inputChangeListener) { fDelayedInputChangeListener= inputChangeListener; } /** * <p> * Tells whether a delayed input change listener is registered. * </p> * * @return <code>true</code> iff a delayed input change listener is currently * registered * * @since 3.4 */ public boolean hasDelayedInputChangeListener() { return fDelayedInputChangeListener != null; } /** * <p> * Notifies listeners of a delayed input change. * </p> * * @param newInput the new input, or <code>null</code> to request cancellation * * @since 3.4 */ public void notifyDelayedInputChange(Object newInput) { if (fDelayedInputChangeListener != null) fDelayedInputChangeListener.inputChanged(newInput); } /** * * @see java.lang.Object#toString() * * @since 3.4 */ public String toString() { String style= (getShell().getStyle() & SWT.RESIZE) == 0 ? "fixed" : "resizeable"; return super.toString() + " - style: " + style; } /** * * @return the current browser input or <code>null</code> */ public de.darwinspl.preferences.resource.dwprofile.ui.DwprofileDocBrowserInformationControlInput getInput() { return fInput; } /** * * @see * org.eclipse.jface.text.IInformationControlExtension5#computeSizeConstraints(int, * int) */ public Point computeSizeConstraints(int widthInChars, int heightInChars) { if (fSymbolicFontName == null) { return null; } GC gc= new GC(fBrowser); Font font= fSymbolicFontName == null ? JFaceResources.getDialogFont() : JFaceResources.getFont(fSymbolicFontName); gc.setFont(font); int width= gc.getFontMetrics().getAverageCharWidth(); int height= gc.getFontMetrics().getHeight(); gc.dispose(); return new Point(widthInChars * width, heightInChars * height); } }
28.370079
169
0.705579
4c664ed1049d48c52d16ab5ee88ff1737f004e97
141
package nl.buildforce.sequoia.jpa.metadata.core.edm.mapper.api; public interface JPAJavaFunction extends JPAFunction, JPAJavaOperation { }
23.5
72
0.829787
59c063bd757fdd92aa025e30cc1ad09a462af31e
3,385
package com.gamecodeschool.notetoself; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { // Temporary code //Note mTempNote = new Note(); private List<Note> noteList = new ArrayList<>(); private RecyclerView recyclerView; private NoteAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) //.setAction("Action", null).show(); DialogNewNote dialog = new DialogNewNote(); dialog.show(getSupportFragmentManager(), ""); } }); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); mAdapter = new NoteAdapter(this, noteList); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); // Add a neat dividing line between items in the list recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); // set the adapter recyclerView.setAdapter(mAdapter); } public void createNewNote(Note n){ // Temporary code //mTempNote = n; noteList.add(n); mAdapter.notifyDataSetChanged(); } public void showNote(int noteToShow){ DialogShowNote dialog = new DialogShowNote(); dialog.sendNoteSelected(noteList.get(noteToShow)); dialog.show(getSupportFragmentManager(), ""); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
32.548077
102
0.69099
ab574a9574132c5d49c5ad2c5f526c93b9f4d473
3,187
/* * Copyright 2019 Confluent Inc. * * Licensed under the Confluent Community License (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.confluent.io/confluent-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package io.confluent.ksql.rest.client; import io.confluent.ksql.rest.Errors; import io.confluent.ksql.rest.entity.KsqlErrorMessage; import java.util.Optional; import java.util.function.Function; import javax.naming.AuthenticationException; import javax.ws.rs.core.Response; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpStatus.Code; public final class KsqlClientUtil { private KsqlClientUtil() { } public static <T> RestResponse<T> toRestResponse( final Response response, final String path, final Function<Response, T> mapper ) { final Code statusCode = HttpStatus.getCode(response.getStatus()); return statusCode == Code.OK ? RestResponse.successful(statusCode, mapper.apply(response)) : createErrorResponse(path, response); } private static <T> RestResponse<T> createErrorResponse( final String path, final Response response ) { final Code statusCode = HttpStatus.getCode(response.getStatus()); final Optional<KsqlErrorMessage> errorMessage = tryReadErrorMessage(response); if (errorMessage.isPresent()) { return RestResponse.erroneous(statusCode, errorMessage.get()); } if (statusCode == Code.NOT_FOUND) { return RestResponse.erroneous(statusCode, "Path not found. Path='" + path + "'. " + "Check your ksql http url to make sure you are connecting to a ksql server." ); } if (statusCode == Code.UNAUTHORIZED) { return RestResponse.erroneous(statusCode, unauthorizedErrorMsg()); } if (statusCode == Code.FORBIDDEN) { return RestResponse.erroneous(statusCode, forbiddenErrorMsg()); } return RestResponse.erroneous( statusCode, "The server returned an unexpected error: " + response.getStatusInfo().getReasonPhrase()); } private static Optional<KsqlErrorMessage> tryReadErrorMessage(final Response response) { try { return Optional.ofNullable(response.readEntity(KsqlErrorMessage.class)); } catch (final Exception e) { return Optional.empty(); } } private static KsqlErrorMessage unauthorizedErrorMsg() { return new KsqlErrorMessage( Errors.ERROR_CODE_UNAUTHORIZED, new AuthenticationException( "Could not authenticate successfully with the supplied credentials.") ); } private static KsqlErrorMessage forbiddenErrorMsg() { return new KsqlErrorMessage( Errors.ERROR_CODE_FORBIDDEN, new AuthenticationException("You are forbidden from using this cluster.") ); } }
32.85567
92
0.713524
1c0a1aec3d6b02a629d2ac505c214ba22d1221f7
3,457
// Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.tensorflowlite; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.tensorflowlite.global.tensorflowlite.*; // A structure representing an instance of a node. // This structure only exhibits the inputs, outputs, user defined data and some // node properties (like statefulness), not other features like the type. @Properties(inherit = org.bytedeco.tensorflowlite.presets.tensorflowlite.class) public class TfLiteNode extends Pointer { static { Loader.load(); } /** Default native constructor. */ public TfLiteNode() { super((Pointer)null); allocate(); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public TfLiteNode(long size) { super((Pointer)null); allocateArray(size); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public TfLiteNode(Pointer p) { super(p); } private native void allocate(); private native void allocateArray(long size); @Override public TfLiteNode position(long position) { return (TfLiteNode)super.position(position); } @Override public TfLiteNode getPointer(long i) { return new TfLiteNode((Pointer)this).offsetAddress(i); } // Inputs to this node expressed as indices into the simulator's tensors. public native TfLiteIntArray inputs(); public native TfLiteNode inputs(TfLiteIntArray setter); // Outputs to this node expressed as indices into the simulator's tensors. public native TfLiteIntArray outputs(); public native TfLiteNode outputs(TfLiteIntArray setter); // intermediate tensors to this node expressed as indices into the simulator's // tensors. public native TfLiteIntArray intermediates(); public native TfLiteNode intermediates(TfLiteIntArray setter); // Temporary tensors uses during the computations. This usually contains no // tensors, but ops are allowed to change that if they need scratch space of // any sort. public native TfLiteIntArray temporaries(); public native TfLiteNode temporaries(TfLiteIntArray setter); // Opaque data provided by the node implementer through `Registration.init`. public native Pointer user_data(); public native TfLiteNode user_data(Pointer setter); // Opaque data provided to the node if the node is a builtin. This is usually // a structure defined in builtin_op_data.h public native Pointer builtin_data(); public native TfLiteNode builtin_data(Pointer setter); // Custom initial data. This is the opaque data provided in the flatbuffer. // WARNING: This is an experimental interface that is subject to change. public native @Const Pointer custom_initial_data(); public native TfLiteNode custom_initial_data(Pointer setter); public native int custom_initial_data_size(); public native TfLiteNode custom_initial_data_size(int setter); // The pointer to the delegate. This is non-null only when the node is // created by calling `interpreter.ModifyGraphWithDelegate`. // WARNING: This is an experimental interface that is subject to change. public native TfLiteDelegate delegate(); public native TfLiteNode delegate(TfLiteDelegate setter); // Whether this op might have side effect (e.g. stateful op). public native @Cast("bool") boolean might_have_side_effect(); public native TfLiteNode might_have_side_effect(boolean setter); }
50.838235
128
0.764536
9c92be02d31f300d9ba1dbccce37c2966e289041
1,028
package com.github.jumpt57.configuration.modules; import com.github.jumpt57.filters.HeaderCORSFilter; import com.github.jumpt57.filters.LogFilter; import com.github.jumpt57.filters.MyPersistFilter; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.guice.EndpointsModule; import com.google.inject.persist.jpa.JpaPersistModule; import org.reflections.Reflections; import java.util.Set; public class ServletsModule extends EndpointsModule { private static final String ROOT = "/_ah/api/*"; @Override public void configureServlets() { super.configureServlets(); install(new JpaPersistModule("PersistenceModule")); filter(ROOT).through(MyPersistFilter.class); filter(ROOT).through(LogFilter.class); filter(ROOT).through(HeaderCORSFilter.class); Reflections reflections = new Reflections("com.github"); Set<Class<?>> endpoints = reflections.getTypesAnnotatedWith(Api.class); configureEndpoints(ROOT, endpoints); } }
30.235294
79
0.747082
72f57fa779899f68efb1a94a8e8253361825b356
479
package nl.vu.cs.ajira.examples.aurora.examples; import nl.vu.cs.ajira.examples.aurora.api.ExecutionPath; import nl.vu.cs.ajira.examples.aurora.api.JobGenerator; import nl.vu.cs.ajira.submissions.Job; public abstract class AuroraExample { public final Job generateExample() { ExecutionPath path = ExecutionPath.getExecutionPath(); generatePath(path); return JobGenerator.generateJobFrom(path); } protected abstract void generatePath(ExecutionPath path); }
26.611111
59
0.780793
e0369cf86172ba31fa612314ff576d0b0794ee14
1,942
package ru.itmo.wp.servlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.file.Files; public class StaticServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String uri = request.getRequestURI(); String[] literals = uri.split("[+]"); String MIMEtype = ""; for (String current : literals) { if (!current.startsWith("/")) { current = "/" + current; } if (MIMEtype.equals("")) { MIMEtype = getContentTypeFromName(current); } File file = new File("./src/main/webapp/static" + current); if (!file.isFile()) { file = new File(getServletContext().getRealPath("/static" + current)); } if (file.isFile()) { OutputStream outputStream = response.getOutputStream(); Files.copy(file.toPath(), outputStream); outputStream.flush(); response.setContentType(MIMEtype); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } } private String getContentTypeFromName(String name) { name = name.toLowerCase(); if (name.endsWith(".png")) { return "image/png"; } if (name.endsWith(".jpg")) { return "image/jpeg"; } if (name.endsWith(".html")) { return "text/html"; } if (name.endsWith(".css")) { return "text/css"; } if (name.endsWith(".js")) { return "application/javascript"; } throw new IllegalArgumentException("Can't find content type for '" + name + "'."); } }
28.144928
103
0.548919
4621bf2d58f1f659cf6ec1a3238e1e8d7322807c
11,416
package com.sp.member; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.util.UrlPathHelper; import com.sp.client.Client; @Controller("memberController") public class MemberController { @Autowired private MemberService service; // ๋กœ๊ทธ์ธ @RequestMapping(value = "/member/login", method = RequestMethod.GET) public String loginForm(HttpServletRequest req, Model model) { /*String AppVer = req.getServerName().substring(20); model.addAttribute("AppVer", AppVer);*/ return "/member/login"; } @RequestMapping(value = "/member/login", method = RequestMethod.POST) public String loginSubmit( @RequestParam String userId, @RequestParam String userPwd, HttpServletRequest req, HttpSession session, Model model) { Member dto = service.loginMember(userId); if (dto == null || !userPwd.equals(dto.getUserPwd())) { model.addAttribute("message", "์•„์ด๋”” ๋˜๋Š” ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); return "/member/login"; } String browser = ""; String userAgent = req.getHeader("User-Agent"); try { // ๋ธŒ๋ผ์šฐ์ € ์ข…๋ฅ˜ if (userAgent.indexOf("Trident") > -1 || userAgent.indexOf("MSIE") > -1) { // IE if (userAgent.indexOf("Trident/7") > -1) { browser = "IE 11"; } else if (userAgent.indexOf("Trident/6") > -1) { browser = "IE 10"; } else if (userAgent.indexOf("Trident/5") > -1) { browser = "IE 9"; } else if (userAgent.indexOf("Trident/4") > -1) { browser = "IE 8"; } else if (userAgent.indexOf("Edge") > -1) { browser = "IE Edge"; } } else if (userAgent.indexOf("Whale") > -1) { // ๋„ค์ด๋ฒ„ WHALE browser = "WHALE " + userAgent.split("Whale/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) { // ์˜คํŽ˜๋ผ if (userAgent.indexOf("Opera") > -1) { browser = "OPERA " + userAgent.split("Opera/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("OPR") > -1) { browser = "OPERA " + userAgent.split("OPR/")[1].toString().split(" ")[0].toString(); } } else if (userAgent.indexOf("Firefox") > -1) { // ํŒŒ์ด์–ดํญ์Šค browser = "FIREFOX " + userAgent.split("Firefox/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1) { // ์‚ฌํŒŒ๋ฆฌ browser = "SAFARI " + userAgent.split("Safari/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("Chrome") > -1) { // ํฌ๋กฌ browser = "CHROME " + userAgent.split("Chrome/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("Edg") > -1) { // Edge browser = "Edge " + userAgent.split("Edg/")[1].toString().split(" ")[0].toString(); } dto.setBrowser(browser); dto.setIpAddr(req.getRemoteAddr()); service.insertLog(dto); } catch (Exception e) { e.printStackTrace(); } SessionInfo info = new SessionInfo(); info.setUserId(dto.getUserId()); info.setUserName(dto.getUserName()); System.out.println(info.getUserId() + "===================๋กœ๊ทธ์ธ"); System.out.println(dto.getIpAddr() + "++++++++++++++ip"); System.out.println(dto.getBrowser() + "=====๋ธŒ๋ผ์šฐ์ €"); session.setAttribute("member", info); return "redirect:/main"; } // ๋กœ๊ทธ์•„์›ƒ // ์„ธ์…˜ ๋Š๊ธธ ๋•Œ, ๋กœ๊ทธ์•„์›ƒ ๋ฒ„ํŠผ ๋ˆŒ๋ €์„ ๋•Œ @RequestMapping(value = "/member/logout") public String logout( @RequestParam(value = "userId", required = false) String userId, HttpServletRequest request, HttpSession session) { Member dto = service.loginMember(userId); String browser = ""; String userAgent = request.getHeader("User-Agent"); try { // ๋ธŒ๋ผ์šฐ์ € ์ข…๋ฅ˜ if (userAgent.indexOf("Trident") > -1 || userAgent.indexOf("MSIE") > -1) { // IE if (userAgent.indexOf("Trident/7") > -1) { browser = "IE 11"; } else if (userAgent.indexOf("Trident/6") > -1) { browser = "IE 10"; } else if (userAgent.indexOf("Trident/5") > -1) { browser = "IE 9"; } else if (userAgent.indexOf("Trident/4") > -1) { browser = "IE 8"; } else if (userAgent.indexOf("Edge") > -1) { browser = "IE Edge"; } } else if (userAgent.indexOf("Whale") > -1) { // ๋„ค์ด๋ฒ„ WHALE browser = "WHALE " + userAgent.split("Whale/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) { // ์˜คํŽ˜๋ผ if (userAgent.indexOf("Opera") > -1) { browser = "OPERA " + userAgent.split("Opera/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("OPR") > -1) { browser = "OPERA " + userAgent.split("OPR/")[1].toString().split(" ")[0].toString(); } } else if (userAgent.indexOf("Firefox") > -1) { // ํŒŒ์ด์–ดํญ์Šค browser = "FIREFOX " + userAgent.split("Firefox/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1) { // ์‚ฌํŒŒ๋ฆฌ browser = "SAFARI " + userAgent.split("Safari/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("Chrome") > -1) { // ํฌ๋กฌ browser = "CHROME " + userAgent.split("Chrome/")[1].toString().split(" ")[0].toString(); } else if (userAgent.indexOf("Edg") > -1) { // Edge browser = "Edge " + userAgent.split("Edg/")[1].toString().split(" ")[0].toString(); } session = request.getSession(); dto.setBrowser(browser); dto.setIpAddr(request.getRemoteAddr()); service.insertLogOut(dto); } catch (Exception e) { e.printStackTrace(); } System.out.println(userId + "================๋กœ๊ทธ์•„์›ƒ"); System.out.println(dto.getBrowser() + "=====๋กœ๊ทธ์•„์›ƒ๋ธŒ๋ผ์šฐ์ €"); session.removeAttribute("member"); session.invalidate(); return "redirect:/member/login"; } public void browser() { } // ํšŒ์›๊ฐ€์ž… @RequestMapping(value = {"/member/created", "/client/created"}) public String createdForm(Member dto, HttpServletRequest request, RedirectAttributes reAttr, Model model) { UrlPathHelper urls = new UrlPathHelper(); String url = urls.getOriginatingServletPath(request); String returnUrl = ""; if ("/member/created".equals(url)) { returnUrl = "/member/created"; } else if ("/client/created".equals(url)) { // uuid ๋ฐ›๊ธฐ String pcUid = request.getParameter("uuid"); System.out.println("1.if๋ฌธ ๋ฐ–์—----------------" + pcUid); if (pcUid == null || pcUid.equals("")) { StringBuilder sb = new StringBuilder(); sb.append("๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ํ•ด์ฃผ์„ธ์š”.<br>"); sb.append("์•„๋ž˜ ํ™•์ธ ๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ์ฃผ์„ธ์š”."); reAttr.addFlashAttribute("message", sb.toString()); System.out.println("2.if๋ฌธ ์•ˆ์—----------------" + pcUid); return "redirect:/client/complete"; } System.out.println("3.if๋ฌธ ์•ˆ์—----------------" + pcUid); model.addAttribute("pcUid", pcUid); returnUrl = "/member/created"; } // sido ๋ฆฌ์ŠคํŠธ List<Member> sidoList = service.readSido(); model.addAttribute("mode", "created"); model.addAttribute("sidoList", sidoList); model.addAttribute("url", url); return returnUrl; } @RequestMapping(value = {"/member/created", "/client/created"}, method = RequestMethod.POST) public String createdSubmit(Member member, Client client, HttpServletRequest request, final RedirectAttributes reAttr, Model model) { UrlPathHelper urls = new UrlPathHelper(); String url = urls.getOriginatingServletPath(request); String returnUrl = ""; try { member.setPhone(member.getPhone().replaceAll("-", "")); String phone1 = member.getPhone().substring(0, 3); String phone2 = member.getPhone().substring(3, 7); String phone3 = member.getPhone().substring(7); member.setPhone(phone1 + "-" + phone2 + "-" + phone3); if ("/member/created".equals(url)) { service.insertMember(member); returnUrl = "redirect:/member/complete"; } else if ("/client/created".equals(url)) { service.insertMember(member); service.insertClient(client); returnUrl = "redirect:/client/complete"; } } catch (Exception e) { model.addAttribute("mode", "member"); model.addAttribute("url", url); } StringBuilder sb = new StringBuilder(); sb.append(member.getUserName() + "๋‹˜ ๊ฐ€์ž…์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.<br>"); if (url.equals("/client/created")) { sb.append("์•„๋ž˜ ํ™•์ธ ๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ์ฃผ์„ธ์š”."); } reAttr.addFlashAttribute("message", sb.toString()); return returnUrl; } @RequestMapping(value = {"/member/complete", "/client/complete"}) public String complete(@ModelAttribute("message") String message, HttpServletRequest request, Model model) throws Exception { if (message == null || message.length() == 0) { return "redirect:/member/complete"; } UrlPathHelper urls = new UrlPathHelper(); String url = urls.getOriginatingServletPath(request); String returnUrl = ""; if ("/member/complete".equals(url)) { returnUrl = "/member/complete"; } else if ("/client/complete".equals(url)) { returnUrl = "/member/complete"; } model.addAttribute("url", url); return returnUrl; } // ํšŒ์› ์•„์ด๋”” ์ค‘๋ณต ์ฒดํฌ @RequestMapping(value = "/member/userIdCheck", method = RequestMethod.POST) @ResponseBody public Map<String, Object> userIdCheck(@RequestParam(value = "userId") String userId) throws Exception { Member dto = service.readMember(userId); String p = "true"; if (dto != null) { p = "false"; } Map<String, Object> model = new HashMap<>(); model.put("passed", p); return model; } // ํด๋ผ์ด์–ธํŠธ ์•„์ด๋”” ์ค‘๋ณต ์ฒดํฌ /* @RequestMapping(value = "/client/clientUserIdCheck", method = RequestMethod.POST) @ResponseBody public Map<String, Object> clientUserIdCheck(@RequestParam(value = "userId") String userId) throws Exception { Member dto = service.readMember(userId); String p = "true"; if (dto != null) { p = "false"; } Map<String, Object> model = new HashMap<>(); model.put("passed", p); return model; }*/ // ์‹œ๊ตฐ๊ตฌ ๋ชฉ๋ก @RequestMapping(value = "/member/sigungu", method = RequestMethod.POST) @ResponseBody public List<String> sigungu(@RequestParam String sido) throws Exception { List<String> sigunguList = null; try { sigunguList = service.readSiGunGu(sido); } catch (Exception e) { e.printStackTrace(); } return sigunguList; } // ์๋ฉด๋™ ๋ชฉ๋ก @RequestMapping(value = "/member/eupmyundong", method = RequestMethod.POST) @ResponseBody public List<String> eupmyundong(@RequestParam String sigungu) throws Exception { List<String> eupmyundongList = null; try { eupmyundongList = service.readEupMyunDong(sigungu); } catch (Exception e) { e.printStackTrace(); } return eupmyundongList; } // ๋„๋กœ๋ช… ๋ชฉ๋ก @RequestMapping(value = "/member/doro", method = RequestMethod.POST) @ResponseBody public List<String> doro(@RequestParam String sigungu) throws Exception { List<String> doroList = null; try { doroList = service.readDoro(sigungu); } catch (Exception e) { e.printStackTrace(); } return doroList; } }
30.361702
134
0.649439
cd18acb6059f720cd4a3c1d41d78d1f32b27a8e6
585
package com.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * Created by happyyangyuan at 2017/11/20 */ @RestController public class HiController { @Autowired private CallServiceHi hiServiceCaller; @RequestMapping("hi") public String hi(@RequestParam(required = false) String name) { return hiServiceCaller.sayHiFromClientOne(name); } }
27.857143
67
0.779487
57da36bcc9dc0c40963c273a1fa2a184ace0bf4a
2,423
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.batch.protocol.models; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * Defines values for TaskState. */ public enum TaskState { /** The task is queued and able to run, but is not currently assigned to a compute node. A task enters this state when it is created, when it is enabled after being disabled, or when it is awaiting a retry after a failed run. */ ACTIVE("active"), /** The task has been assigned to a compute node, but is waiting for a required Job Preparation task to complete on the node. If the Job Preparation task succeeds, the task will move to running. If the Job Preparation task fails, the task will return to active and will be eligible to be assigned to a different node. */ PREPARING("preparing"), /** The task is running on a compute node. This includes task-level preparation such as downloading resource files or deploying application packages specified on the task - it does not necessarily mean that the task command line has started executing. */ RUNNING("running"), /** The task is no longer eligible to run, usually because the task has finished successfully, or the task has finished unsuccessfully and has exhausted its retry limit. A task is also marked as completed if an error occurred launching the task, or when the task has been terminated. */ COMPLETED("completed"); /** The actual serialized value for a TaskState instance. */ private String value; TaskState(String value) { this.value = value; } /** * Parses a serialized value to a TaskState instance. * * @param value the serialized value to parse. * @return the parsed TaskState object, or null if unable to parse. */ @JsonCreator public static TaskState fromString(String value) { TaskState[] items = TaskState.values(); for (TaskState item : items) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return null; } @JsonValue @Override public String toString() { return this.value; } }
40.383333
324
0.700784
f40ad64367cce4fec957724b78d3fe2550629f16
3,363
package adj.felix.hadoop.mr.join; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Partitioner; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.MultipleInputs; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import adj.felix.hadoop.pojo.TextPair; public class MRJoinOfMapper { /* userId,userName,userAge */ static class JoinUserMapper extends Mapper<LongWritable, Text, TextPair, Text> { @Override protected void map(LongWritable key, Text line, Context context) throws IOException, InterruptedException { String[] words = line.toString().split(","); context.write(new TextPair(words[0], "0"), new Text(words[1] + "," + words[2])); } } /* userId,userInfo */ static class JoinInfoMapper extends Mapper<LongWritable, Text, TextPair, Text> { @Override protected void map(LongWritable key, Text line, Context context) throws IOException, InterruptedException { String[] words = line.toString().split(","); context.write(new TextPair(words[0], "1"), new Text(words[1])); } } static class JoinReducer extends Reducer<TextPair, Text, Text, Text> { @Override protected void reduce(TextPair key, Iterable<Text> values, Context context) throws IOException, InterruptedException { Iterator<Text> iter = values.iterator(); Text user = iter.next(); while (iter.hasNext()) { Text value = new Text(user + "\t" + iter.next().toString()); context.write(key.getFirst(), value); } } } static class KeyPartitioner extends Partitioner<TextPair, Text> { @Override public int getPartition(TextPair key, Text value, int numPartitions) { return (key.getFirst().hashCode() & Integer.MAX_VALUE) % numPartitions; } } @SuppressWarnings("rawtypes") static class KeyComparator extends WritableComparator { public KeyComparator() { super(TextPair.class, true); } @Override public int compare(WritableComparable a, WritableComparable b) { TextPair ip1 = (TextPair) a; TextPair ip2 = (TextPair) b; int cmp = ip1.getFirst().compareTo(ip2.getFirst()); return cmp; } } public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Join"); Path userPath = new Path(args[0]); Path infoPath = new Path(args[1]); Path outputPath = new Path(args[2]); MultipleInputs.addInputPath(job, userPath, TextInputFormat.class, JoinUserMapper.class); MultipleInputs.addInputPath(job, infoPath, TextInputFormat.class, JoinInfoMapper.class); FileOutputFormat.setOutputPath(job, outputPath); job.setPartitionerClass(KeyPartitioner.class); job.setGroupingComparatorClass(KeyComparator.class); job.setMapOutputKeyClass(TextPair.class); job.setReducerClass(JoinReducer.class); job.setOutputKeyClass(Text.class); job.waitForCompletion(true); } }
34.316327
120
0.746655
82fceba8ba41f2200457dedd9123abe0c4c71c2d
2,229
package com.ruoyi.app.common.page; import java.io.Serializable; import java.util.List; /** * ่กจๆ ผๅˆ†้กตๆ•ฐๆฎๅฏน่ฑก */ public class ResultData implements Serializable { // private static final long serialVersionUID = -2652773809295318093L; /** ๆถˆๆฏ็Šถๆ€็  */ private int code; private String msg; /** ๆ€ป่ฎฐๅฝ•ๆ•ฐ */ private Long total; /** ๅˆ—่กจๆ•ฐๆฎ */ private List<?> rows; private Object data; /** * * @author zmr */ public ResultData() { super(); } /** * @param code * @param msg * @author zmr */ public ResultData(int code, String msg) { super(); this.code = code; this.msg = msg; } /** * @param code * @param msg * @param data * @author zmr */ public ResultData(int code, String msg, Object data) { super(); this.code = code; this.msg = msg; this.data = data; } /** * @param code * @param msg * @param total * @param rows * @author zmr */ public ResultData(int code, String msg, Long total, List<?> rows) { super(); this.code = code; this.msg = msg; this.total = total; this.rows = rows; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Long getTotal() { return total; } public void setTotal(Long total) { this.total = total; } public List<?> getRows() { return rows; } public void setRows(List<?> rows) { this.rows = rows; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public static ResultData success() { return new ResultData(0, "success"); } public static ResultData success(Object data) { return new ResultData(0, "success", data); } }
16.152174
71
0.493495
7c09ed44808e6854e74a4a8a80f56573546abeda
973
package helvidios.cp.ch3.completesearch; import java.util.Scanner; public class _1260_Sales { public static void main(String... args){ String data = "2\r\n" + "5\r\n" + "38 111 102 111 177\r\n" + "8\r\n" + "276 284 103 439 452 276 452 398\r\n" + ""; Scanner scanner = new Scanner(data); int nTestCases = scanner.nextInt(); while(nTestCases-- > 0){ int size = scanner.nextInt(); int[] sales = new int[size]; for(int i = 0; i < sales.length; i++){ sales[i] = scanner.nextInt(); } System.out.println(solve(sales)); } scanner.close(); } public static int solve(int[] sales){ int[] b = new int[sales.length - 1]; for(int day = 1; day < sales.length; day++){ int count = 0; for(int previousDay = 0; previousDay < day; previousDay++){ if(sales[previousDay] <= sales[day]){ count++; } } b[day - 1] = count; } int sum = 0; for(int item : b){ sum += item; } return sum; } }
21.622222
62
0.577595
d2afbc9cef40a9fef4fa5cb03ea844f890ad999b
1,320
package com.genius.backend.infrastructure.security.social.provider; import com.genius.backend.application.ProviderType; import com.genius.backend.domain.model.auth.Role; import com.genius.backend.domain.model.user.User; import org.springframework.social.connect.Connection; import java.util.Set; public interface SocialProvider<T> { User getUser(); String getProviderId(); String getProviderUserId(); void pushMessage(String object); default User getUser(Connection<?> connection) { var user = new User(); user.setProviderType(ProviderType.valueOf(connection.createData().getProviderId().toUpperCase())); user.setProviderUserId(connection.createData().getProviderUserId()); user.setUsername(connection.getDisplayName()); user.setImageUrl(connection.createData().getImageUrl()); user.getUserSocial().setUser(user); user.getUserSocial().setAccessToken(connection.createData().getAccessToken()); user.getUserSocial().setRefreshToken(connection.createData().getRefreshToken()); user.getUserSocial().setExpiredTime(connection.createData().getExpireTime() == null ? 0l : connection.createData().getExpireTime()); user.setRoles(Set.of(Role.builder().id(3l).name("USER").build())); return user; } String getRefreshAccessToken(); String getAccessToken(); Connection<T> getConnection(); }
33.846154
134
0.777273
43aed4e4ab5379be823b118712af4e50c3df0e67
892
package com.sequenceiq.cloudbreak.controller.mapper; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataIntegrityViolationException; import com.sequenceiq.cloudbreak.logger.MDCBuilder; @Provider public class DataIntegrityViolationExceptionMapper implements ExceptionMapper<DataIntegrityViolationException> { private static final Logger LOGGER = LoggerFactory.getLogger(DataIntegrityViolationExceptionMapper.class); @Override public Response toResponse(DataIntegrityViolationException exception) { MDCBuilder.buildMdcContext(); LOGGER.error(exception.getMessage(), exception); return Response.status(Response.Status.BAD_REQUEST).entity(exception.getLocalizedMessage()) .build(); } }
34.307692
112
0.793722
8be42bc9a3a547392bb939aae781592bd7793c37
2,480
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Base { public void declaredInBase() { System.out.println("declaredInBase: Base"); } public void overridden() { System.out.println("overridden: Base"); } /* src2: removed */ //public void wasOverridden() { // System.out.println("wasOverridden: Base"); //} public void callOverrideWithPublic() { overrideWithPublic(); } public void overrideWithPublic() { System.out.println("overrideWithPublic: Base"); } public void callOverridePublicWithProtected() { overridePublicWithProtected(); } /* src2: public */ public void overridePublicWithProtected() { System.out.println("overridePublicWithProtected: Base"); } public void callOverrideProtectedWithPublic() { overrideProtectedWithPublic(); } protected void overrideProtectedWithPublic() { System.out.println("overrideProtectedWithPublic: Base"); } public void callOverridePublicWithPrivate() { overridePublicWithPrivate(); } /* src2: public */ public void overridePublicWithPrivate() { System.out.println("overridePublicWithPrivate: Base"); } public void callOverridePrivateWithPublic() { overridePrivateWithPublic(); } private void overridePrivateWithPublic() { System.out.println("overridePrivateWithPublic: Base"); } public void callOverrideVirtualWithStatic() { overrideVirtualWithStatic(); } /* src2: non-static */ public void overrideVirtualWithStatic() { System.out.println("overrideVirtualWithStatic: Base"); } public void callOverrideStaticWithVirtual() { overrideStaticWithVirtual(); } public static void overrideStaticWithVirtual() { System.out.println("overrideStaticWithVirtual: Base"); } }
29.52381
75
0.679839
7a137f8e4df50fefc65c2abdd507cce17eedb81a
1,378
package org.damcode.damecom; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; public final class AuthUser { public static byte[] createSalt(){ Random r = new SecureRandom(); byte[] salt = new byte[32]; r.nextBytes(salt); return salt; } public static byte[] hashPassword(char[] pass, byte[] salt){ byte[] hashedPass = null; SecretKeyFactory key = null; PBEKeySpec spec = new PBEKeySpec(pass, salt, 5000, 256); try { key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AuthUser.class.getName()).log(Level.SEVERE, null, ex); } try { hashedPass = key.generateSecret(spec).getEncoded(); } catch (InvalidKeySpecException ex) { Logger.getLogger(AuthUser.class.getName()).log(Level.SEVERE, null, ex); } return hashedPass; } public static byte[] hashPassword(String pass, byte[] salt){ return hashPassword(pass.toCharArray(), salt); } }
29.319149
83
0.640784
3506b388fef154d667294f5e8362463703f431b6
3,603
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * class to define the health summary of the Vault. */ public class VaultHealthProperties { /** * The list of errors on the vault. */ @JsonProperty(value = "vaultErrors") private List<HealthError> vaultErrors; /** * The list of the health detail of the protected items in the vault. */ @JsonProperty(value = "protectedItemsHealth") private ResourceHealthSummary protectedItemsHealth; /** * The list of the health detail of the fabrics in the vault. */ @JsonProperty(value = "fabricsHealth") private ResourceHealthSummary fabricsHealth; /** * The list of the health detail of the containers in the vault. */ @JsonProperty(value = "containersHealth") private ResourceHealthSummary containersHealth; /** * Get the list of errors on the vault. * * @return the vaultErrors value */ public List<HealthError> vaultErrors() { return this.vaultErrors; } /** * Set the list of errors on the vault. * * @param vaultErrors the vaultErrors value to set * @return the VaultHealthProperties object itself. */ public VaultHealthProperties withVaultErrors(List<HealthError> vaultErrors) { this.vaultErrors = vaultErrors; return this; } /** * Get the list of the health detail of the protected items in the vault. * * @return the protectedItemsHealth value */ public ResourceHealthSummary protectedItemsHealth() { return this.protectedItemsHealth; } /** * Set the list of the health detail of the protected items in the vault. * * @param protectedItemsHealth the protectedItemsHealth value to set * @return the VaultHealthProperties object itself. */ public VaultHealthProperties withProtectedItemsHealth(ResourceHealthSummary protectedItemsHealth) { this.protectedItemsHealth = protectedItemsHealth; return this; } /** * Get the list of the health detail of the fabrics in the vault. * * @return the fabricsHealth value */ public ResourceHealthSummary fabricsHealth() { return this.fabricsHealth; } /** * Set the list of the health detail of the fabrics in the vault. * * @param fabricsHealth the fabricsHealth value to set * @return the VaultHealthProperties object itself. */ public VaultHealthProperties withFabricsHealth(ResourceHealthSummary fabricsHealth) { this.fabricsHealth = fabricsHealth; return this; } /** * Get the list of the health detail of the containers in the vault. * * @return the containersHealth value */ public ResourceHealthSummary containersHealth() { return this.containersHealth; } /** * Set the list of the health detail of the containers in the vault. * * @param containersHealth the containersHealth value to set * @return the VaultHealthProperties object itself. */ public VaultHealthProperties withContainersHealth(ResourceHealthSummary containersHealth) { this.containersHealth = containersHealth; return this; } }
29.292683
103
0.680266
f446965dc73c2bc2a4d45f7dadd1e1e7e46ba25f
4,104
/* * Copyright 2020 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.core.request; import com.b2international.commons.exceptions.BadRequestException; import com.b2international.snowowl.core.ServiceProvider; import com.b2international.snowowl.core.codesystem.CodeSystemEntry; import com.b2international.snowowl.core.codesystem.CodeSystemRequests; import com.b2international.snowowl.core.codesystem.CodeSystemVersionEntry; import com.b2international.snowowl.core.codesystem.version.CodeSystemVersionSearchRequestBuilder; import com.b2international.snowowl.core.domain.BranchContext; import com.b2international.snowowl.core.events.DelegatingRequest; import com.b2international.snowowl.core.events.Request; import com.b2international.snowowl.core.uri.CodeSystemURI; import com.fasterxml.jackson.annotation.JsonProperty; /** * @since 7.5 */ public final class CodeSystemResourceRequest<R> extends DelegatingRequest<ServiceProvider, BranchContext, R> { private static final long serialVersionUID = 1L; @JsonProperty private final CodeSystemURI uri; private transient CodeSystemEntry codeSystem; private transient String branchPath; CodeSystemResourceRequest(String codeSystemUri, Request<BranchContext, R> next) { super(next); this.uri = new CodeSystemURI(codeSystemUri); } @Override public R execute(ServiceProvider context) { return new RepositoryRequest<R>(getRepositoryId(context), new BranchRequest<R>(getBranchPath(context), next() ) ).execute(context.inject() .bind(CodeSystemURI.class, uri) .build()); } public CodeSystemEntry getCodeSystem(ServiceProvider context) { if (codeSystem == null) { codeSystem = CodeSystemRequests.getCodeSystem(context, uri.getCodeSystem()); } return codeSystem; } public String getRepositoryId(ServiceProvider context) { return getCodeSystem(context).getRepositoryUuid(); } public String getBranchPath(ServiceProvider context) { if (branchPath == null) { if (uri.isHead()) { // use code system working branch directly when HEAD is specified branchPath = codeSystem.getBranchPath(); } else { CodeSystemVersionSearchRequestBuilder versionSearch = CodeSystemRequests.prepareSearchCodeSystemVersion() .one() .filterByCodeSystemShortName(codeSystem.getShortName()); if (uri.isLatest()) { // fetch the latest code system version if LATEST is specified in the URI versionSearch.sortBy(SearchResourceRequest.SortField.descending(CodeSystemVersionEntry.Fields.EFFECTIVE_DATE)); } else { // try to fetch the path as exact version if not the special LATEST is specified in the URI versionSearch.filterByVersionId(uri.getPath()); } // determine the final branch path, if based on the version search we find a version, then use that, otherwise use the defined path as relative branch of the code system working branch branchPath = versionSearch .build(codeSystem.getRepositoryUuid()) .getRequest() .execute(context) .stream() .findFirst() .map(CodeSystemVersionEntry::getPath) .orElseGet(() -> { if (uri.isLatest()) { throw new BadRequestException("No CodeSystem version is present in '%s'. Explicit '%s/HEAD' can be used to retrieve the latest work in progress version of the CodeSystem.", codeSystem.getShortName(), codeSystem.getShortName()); } else { return codeSystem.getRelativeBranchPath(uri.getPath()); } }); } } return branchPath; } }
36.972973
235
0.751949
32ff3918d4b1fbafbdf40efc1da7a79049933083
981
import java.util.Arrays; public class RemoveDuplicatesFromSortedArray { public int removeDuplicates(int[] nums) { // if only less than 2 items in the array, do nothing if(nums != null && nums.length < 2) return nums.length; int uniqueLength = 0; /* start at second index, go through the array * the first item always a new number */ for(int i=1; i<nums.length; i++) { if(nums[uniqueLength] != nums[i]) { // when we find a new number, store to the next index nums[++uniqueLength] = nums[i]; } } return uniqueLength+1; } public static void main(String[] args) { RemoveDuplicatesFromSortedArray demo = new RemoveDuplicatesFromSortedArray(); int[] array1 = new int[]{1,1,2}; int[] array2 = new int[]{0,0,1,1,1,2,2,3,3,4}; System.out.println(demo.removeDuplicates(array1)); System.out.println(Arrays.toString(array1)); System.out.println(demo.removeDuplicates(array2)); System.out.println(Arrays.toString(array2)); } }
28.852941
79
0.681957
0dc11703c83235730880817b0da89669c08326d7
444
package br.com.neolog.welcomekit; public class CustomerLocal { private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); public static int getCurrentCustomerId() { return threadLocal.get(); } public static void setCurrentCustomerId( final int id ) { threadLocal.set( id ); } public static void removeCurrentCustomerId() { threadLocal.remove(); } }
18.5
80
0.644144